sently 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +61 -30
- package/dist/adapters/bun.js +1 -1
- package/dist/adapters/cf.js +2 -2
- package/dist/adapters/cf.js.map +1 -1
- package/dist/adapters/deno.js +1 -1
- package/dist/adapters/node.js +1 -1
- package/dist/auth/oauth2.js +2 -2
- package/dist/auth/oauth2.js.map +1 -1
- package/dist/chunk-1cmggzw0.js +4 -0
- package/dist/chunk-1cmggzw0.js.map +10 -0
- package/dist/{chunk-32dj0v9g.js → chunk-50ycrgx6.js} +2 -2
- package/dist/{chunk-32dj0v9g.js.map → chunk-50ycrgx6.js.map} +1 -1
- package/dist/chunk-9ckbc9mk.js +4 -0
- package/dist/chunk-9ckbc9mk.js.map +10 -0
- package/dist/{chunk-nj3wmg69.js → chunk-bzw0fdmy.js} +2 -2
- package/dist/{chunk-nj3wmg69.js.map → chunk-bzw0fdmy.js.map} +1 -1
- package/dist/chunk-gkec86xg.js +13 -0
- package/dist/chunk-gkec86xg.js.map +11 -0
- package/dist/chunk-pqp843mh.js +4 -0
- package/dist/chunk-pqp843mh.js.map +10 -0
- package/dist/chunk-q8k3m6qe.js +4 -0
- package/dist/chunk-q8k3m6qe.js.map +10 -0
- package/dist/{chunk-zwm5bfa4.js → chunk-qp4y0kp2.js} +2 -2
- package/dist/{chunk-zwm5bfa4.js.map → chunk-qp4y0kp2.js.map} +1 -1
- package/dist/{chunk-rhade81v.js → chunk-rszb1n1d.js} +2 -2
- package/dist/{chunk-rhade81v.js.map → chunk-rszb1n1d.js.map} +1 -1
- package/dist/{chunk-ntqmn6pe.js → chunk-tfxje74k.js} +2 -2
- package/dist/{chunk-ntqmn6pe.js.map → chunk-tfxje74k.js.map} +1 -1
- package/dist/{chunk-nhec1319.js → chunk-v8eh0n8d.js} +3 -3
- package/dist/{chunk-nhec1319.js.map → chunk-v8eh0n8d.js.map} +1 -1
- package/dist/chunk-wp4qxk1j.js +4 -0
- package/dist/chunk-wp4qxk1j.js.map +11 -0
- package/dist/{chunk-kdqxhybf.js → chunk-xdx6ypr5.js} +3 -3
- package/dist/{chunk-kdqxhybf.js.map → chunk-xdx6ypr5.js.map} +1 -1
- package/dist/{chunk-cvmk9h1r.js → chunk-z7j2n9k8.js} +3 -3
- package/dist/{chunk-cvmk9h1r.js.map → chunk-z7j2n9k8.js.map} +1 -1
- package/dist/chunk-zm7fe0wb.js +4 -0
- package/dist/{chunk-j5m37k1c.js.map → chunk-zm7fe0wb.js.map} +2 -2
- package/dist/core/errors.d.ts +55 -0
- package/dist/core/smtp.d.ts +3 -3
- package/dist/core/smtp.js +2 -2
- package/dist/core/smtp.js.map +1 -1
- package/dist/core/types.d.ts +28 -1
- package/dist/detect.js +2 -2
- package/dist/detect.js.map +3 -3
- package/dist/dkim.js +2 -2
- package/dist/dkim.js.map +2 -2
- package/dist/errors.d.ts +29 -0
- package/dist/errors.js +8 -0
- package/dist/{react.js.map → errors.js.map} +1 -1
- package/dist/idempotency.js +2 -2
- package/dist/idempotency.js.map +1 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +9 -0
- package/dist/mailer.d.ts +4 -3
- package/dist/mailer.js +2 -2
- package/dist/mailer.js.map +1 -1
- package/dist/plugins/react.js +2 -2
- package/dist/plugins/react.js.map +1 -1
- package/dist/plugins/template.js +1 -1
- package/dist/pool/pool.js +2 -2
- package/dist/pool/pool.js.map +2 -2
- package/dist/react.js +4 -3
- package/dist/transports/brevo.d.ts +3 -3
- package/dist/transports/brevo.js +2 -2
- package/dist/transports/brevo.js.map +3 -3
- package/dist/transports/mailgun.d.ts +2 -1
- package/dist/transports/mailgun.js +2 -2
- package/dist/transports/mailgun.js.map +3 -3
- package/dist/transports/postmark.d.ts +2 -1
- package/dist/transports/postmark.js +2 -2
- package/dist/transports/postmark.js.map +3 -3
- package/dist/transports/preview.js +2 -2
- package/dist/transports/preview.js.map +1 -1
- package/dist/transports/resend.d.ts +2 -1
- package/dist/transports/resend.js +2 -2
- package/dist/transports/resend.js.map +3 -3
- package/dist/transports/retry.d.ts +9 -0
- package/dist/transports/retry.js +2 -2
- package/dist/transports/retry.js.map +3 -4
- package/dist/transports/sendgrid.d.ts +2 -1
- package/dist/transports/sendgrid.js +2 -2
- package/dist/transports/sendgrid.js.map +3 -3
- package/dist/transports/ses.d.ts +3 -3
- package/dist/transports/ses.js +5 -5
- package/dist/transports/ses.js.map +3 -3
- package/dist/transports/smtp.js +2 -2
- package/dist/transports/smtp.js.map +1 -1
- package/dist/webhooks/brevo.js +3 -0
- package/dist/webhooks/brevo.js.map +10 -0
- package/dist/webhooks/mailgun.js +3 -0
- package/dist/webhooks/mailgun.js.map +10 -0
- package/dist/webhooks/postmark.js +3 -0
- package/dist/webhooks/postmark.js.map +10 -0
- package/dist/webhooks/resend.js +3 -0
- package/dist/webhooks/resend.js.map +10 -0
- package/dist/webhooks/sendgrid.js +3 -0
- package/dist/webhooks/sendgrid.js.map +10 -0
- package/dist/webhooks/ses.js +3 -0
- package/dist/webhooks/ses.js.map +10 -0
- package/dist/webhooks/timing-safe-equal.js +3 -0
- package/dist/{webhooks.js.map → webhooks/timing-safe-equal.js.map} +1 -1
- package/dist/webhooks.js +13 -3
- package/package.json +5 -1
- package/dist/chunk-j5m37k1c.js +0 -4
- package/dist/chunk-m2njnxre.js +0 -13
- package/dist/chunk-m2njnxre.js.map +0 -11
- package/dist/chunk-pjzsvsm6.js +0 -4
- package/dist/chunk-pjzsvsm6.js.map +0 -11
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/transports/resend.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * @module\n * Resend HTTP API transport for sending email via api.resend.com.\n *\n * @example\n * ```ts\n * import { ResendTransport } from \"sently/transports/resend\";\n * import { createMailer } from \"sently\";\n *\n * const mailer = await createMailer({\n * transport: new ResendTransport({ apiKey: process.env.RESEND_API_KEY! }),\n * });\n *\n * await mailer.send({\n * from: \"onboarding@yourdomain.com\",\n * to: \"recipient@example.com\",\n * subject: \"Hello\",\n * html: \"<p>Sent via Resend</p>\",\n * });\n * ```\n */\nimport { extractEmails, parseAddresses, toMIMEHeader } from \"../core/address.js\";\nimport { encodeBase64 } from \"../core/base64.js\";\nimport { resolveIdempotencyKey } from \"../core/idempotency-key.js\";\nimport { RateLimiter } from \"../core/rate-limiter.js\";\nimport type { MailOptions, SendResult, Transport, VerifyResult } from \"../core/types.js\";\nimport { resolveAttachments } from \"./resolve-attachments.js\";\n\n/** Resend API configuration. */\nexport interface ResendConfig {\n /** Resend API key (starts with `re_`). */\n apiKey: string;\n /** API base URL. Default: `https://api.resend.com`. */\n baseUrl?: string;\n /** Max batch HTTP requests per rate window. Default: `2` (Resend API limit). Set `0` to disable. */\n rateDelta?: number;\n /** Rate limit window in milliseconds. Default: `1000`. */\n rateLimit?: number;\n}\n\n/** Maximum messages per Resend batch request (overridable per account). */\nexport const RESEND_BATCH_MAX = 100;\n\n/** Error thrown when the Resend API returns a non-success response. */\nexport class ResendError extends
|
|
5
|
+
"/**\n * @module\n * Resend HTTP API transport for sending email via api.resend.com.\n *\n * @example\n * ```ts\n * import { ResendTransport } from \"sently/transports/resend\";\n * import { createMailer } from \"sently\";\n *\n * const mailer = await createMailer({\n * transport: new ResendTransport({ apiKey: process.env.RESEND_API_KEY! }),\n * });\n *\n * await mailer.send({\n * from: \"onboarding@yourdomain.com\",\n * to: \"recipient@example.com\",\n * subject: \"Hello\",\n * html: \"<p>Sent via Resend</p>\",\n * });\n * ```\n */\nimport { extractEmails, parseAddresses, toMIMEHeader } from \"../core/address.js\";\nimport { encodeBase64 } from \"../core/base64.js\";\nimport { httpStatusToSentlyCode, SentlyError } from \"../core/errors.js\";\nimport { resolveIdempotencyKey } from \"../core/idempotency-key.js\";\nimport { RateLimiter } from \"../core/rate-limiter.js\";\nimport type { MailOptions, SendResult, Transport, VerifyResult } from \"../core/types.js\";\nimport { resolveAttachments } from \"./resolve-attachments.js\";\n\n/** Resend API configuration. */\nexport interface ResendConfig {\n /** Resend API key (starts with `re_`). */\n apiKey: string;\n /** API base URL. Default: `https://api.resend.com`. */\n baseUrl?: string;\n /** Max batch HTTP requests per rate window. Default: `2` (Resend API limit). Set `0` to disable. */\n rateDelta?: number;\n /** Rate limit window in milliseconds. Default: `1000`. */\n rateLimit?: number;\n}\n\n/** Maximum messages per Resend batch request (overridable per account). */\nexport const RESEND_BATCH_MAX = 100;\n\n/** Error thrown when the Resend API returns a non-success response. */\nexport class ResendError extends SentlyError {\n /** Creates a Resend API error with status code and response payload. */\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly apiError: unknown,\n ) {\n super(message, httpStatusToSentlyCode(statusCode), {\n statusCode,\n provider: \"resend\",\n cause: apiError,\n });\n this.name = \"ResendError\";\n }\n}\n\n/**\n * Resend HTTP API transport.\n */\nexport class ResendTransport implements Transport {\n /** Resend API key for Bearer authentication. */\n private readonly apiKey: string;\n /** Resend API base URL. */\n private readonly baseUrl: string;\n /** Optional rate limiter for multi-chunk batch sends. */\n private readonly rateLimiter: RateLimiter | null;\n\n /** Maximum messages per batch HTTP request. */\n readonly batchMax = RESEND_BATCH_MAX;\n\n /** Creates a Resend transport with the given API key. */\n constructor(config: ResendConfig) {\n this.apiKey = config.apiKey;\n this.baseUrl = config.baseUrl ?? \"https://api.resend.com\";\n\n const rateDelta = config.rateDelta ?? 2;\n if (rateDelta > 0) {\n this.rateLimiter = new RateLimiter(rateDelta, config.rateLimit ?? 1000);\n } else {\n this.rateLimiter = null;\n }\n }\n\n /** Build the JSON body for a single Resend email. */\n private async buildEmailBody(options: MailOptions): Promise<Record<string, unknown>> {\n const attachments = await resolveAttachments(options.attachments);\n const from = parseAddresses(options.from)[0];\n return {\n from: from ? toMIMEHeader(from) : \"\",\n to: extractEmails(options.to),\n subject: options.subject,\n ...(options.cc ? { cc: extractEmails(options.cc) } : {}),\n ...(options.bcc ? { bcc: extractEmails(options.bcc) } : {}),\n ...(options.replyTo ? { reply_to: extractEmails(options.replyTo) } : {}),\n ...(options.text ? { text: options.text } : {}),\n ...(options.html ? { html: options.html } : {}),\n ...(options.headers ? { headers: options.headers } : {}),\n ...(attachments.length > 0\n ? {\n attachments: attachments.map((att) => ({\n filename: att.filename,\n content:\n att.content instanceof Uint8Array\n ? encodeBase64(att.content).replace(/\\r\\n/g, \"\")\n : att.content,\n ...(att.contentType ? { content_type: att.contentType } : {}),\n })),\n }\n : {}),\n };\n }\n\n /** Map a Resend API response id to a normalized SendResult. */\n private toSendResult(\n options: MailOptions,\n payload: { id?: string; message?: string; batchError?: unknown },\n ): SendResult {\n const from = parseAddresses(options.from)[0];\n return {\n messageId: payload.id ?? options.messageId ?? \"\",\n accepted: extractEmails(options.to),\n rejected: [],\n response: payload.message ?? \"Email sent\",\n envelope: {\n from: from?.address ?? \"\",\n to: [\n ...extractEmails(options.to),\n ...(options.cc ? extractEmails(options.cc) : []),\n ...(options.bcc ? extractEmails(options.bcc) : []),\n ],\n },\n ...(payload.batchError !== undefined ? { batchError: payload.batchError } : {}),\n };\n }\n\n /** Sends an email via the Resend HTTP API. */\n async send(options: MailOptions): Promise<SendResult> {\n const body = await this.buildEmailBody(options);\n const idempotencyKey = resolveIdempotencyKey(options);\n\n const response = await fetch(`${this.baseUrl}/emails`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(idempotencyKey ? { \"Idempotency-Key\": idempotencyKey } : {}),\n },\n body: JSON.stringify(body),\n });\n\n const payload = (await response.json()) as { id?: string; message?: string };\n\n if (!response.ok) {\n throw new ResendError(payload.message ?? \"Resend API error\", response.status, payload);\n }\n\n return this.toSendResult(options, payload);\n }\n\n /** Send up to {@link RESEND_BATCH_MAX} attachment-free messages per batch request. */\n async sendBatch(messages: MailOptions[]): Promise<SendResult[]> {\n if (messages.length === 0) {\n return [];\n }\n\n const results: SendResult[] = [];\n for (let offset = 0; offset < messages.length; offset += RESEND_BATCH_MAX) {\n if (offset > 0 && this.rateLimiter) {\n await this.rateLimiter.acquire();\n }\n\n const chunk = messages.slice(offset, offset + RESEND_BATCH_MAX);\n const bodies = await Promise.all(chunk.map((message) => this.buildEmailBody(message)));\n\n const response = await fetch(`${this.baseUrl}/emails/batch`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(bodies),\n });\n\n const payload = (await response.json()) as {\n data?: Array<{ id?: string; error?: string }>;\n message?: string;\n };\n\n if (!response.ok) {\n throw new ResendError(\n payload.message ?? \"Resend batch API error\",\n response.status,\n payload,\n );\n }\n\n const ids = payload.data ?? [];\n for (let i = 0; i < chunk.length; i++) {\n const message = chunk[i] as MailOptions;\n const item = ids[i];\n if (item?.id !== undefined) {\n results.push(\n this.toSendResult(message, {\n id: item.id,\n ...(payload.message !== undefined ? { message: payload.message } : {}),\n }),\n );\n continue;\n }\n\n const errorMessage = item?.error ?? \"Batch item failed\";\n results.push(\n this.toSendResult(message, {\n message: errorMessage,\n batchError: new ResendError(errorMessage, response.status, item ?? {}),\n }),\n );\n }\n }\n\n return results;\n }\n\n /** Verifies the Resend API key by listing domains. */\n async verify(): Promise<VerifyResult> {\n try {\n const response = await fetch(`${this.baseUrl}/domains`, {\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n },\n });\n\n if (!response.ok) {\n const payload = (await response.json().catch(() => ({}))) as { message?: string };\n return {\n ok: false,\n provider: \"resend\",\n message: payload.message ?? `HTTP ${response.status}`,\n };\n }\n\n return { ok: true, provider: \"resend\", message: \"API key is valid\" };\n } catch (err) {\n return {\n ok: false,\n provider: \"resend\",\n message: err instanceof Error ? err.message : String(err),\n };\n }\n }\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "sUA0CO,DAAM,HAAmB,DAG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Ae,MAAQ,EAAI,QAAU,OAAO,CAAG,CAC1D,GAGN",
|
|
8
|
+
"debugId": "0065781B51F4526264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -17,12 +17,21 @@ export declare class RetryTransport implements Transport {
|
|
|
17
17
|
private readonly retryOn;
|
|
18
18
|
/** Optional callback invoked before each retry attempt. */
|
|
19
19
|
private readonly onRetry;
|
|
20
|
+
/** Additional onRetry callback wired by {@link MailerImpl} hooks per send. */
|
|
21
|
+
private mailerOnRetry;
|
|
20
22
|
/** Wraps an inner transport with retry logic and optional backoff configuration. */
|
|
21
23
|
constructor(
|
|
22
24
|
/** Transport that performs the actual send on each attempt. */
|
|
23
25
|
inner: Transport, config?: RetryConfig,
|
|
24
26
|
/** Injectable sleep function for testing backoff timing. */
|
|
25
27
|
_sleep?: (ms: number) => Promise<void>);
|
|
28
|
+
/**
|
|
29
|
+
* Register a per-send onRetry callback from mailer lifecycle hooks.
|
|
30
|
+
* Do not share one {@link RetryTransport} across multiple mailers — the last
|
|
31
|
+
* `setMailerOnRetry` wins; overwriting an active callback logs a dev warning.
|
|
32
|
+
* @internal Used by {@link MailerImpl}; cleared after each send.
|
|
33
|
+
*/
|
|
34
|
+
setMailerOnRetry(callback: RetryConfig["onRetry"] | undefined): void;
|
|
26
35
|
/** Sends with retries according to configured backoff and retry rules. */
|
|
27
36
|
send(options: MailOptions): Promise<SendResult>;
|
|
28
37
|
/** Delegates to the inner transport verify or returns a default success result. */
|
package/dist/transports/retry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{v as
|
|
1
|
+
import{v as a}from"../chunk-1cmggzw0.js";import"../chunk-gkec86xg.js";import"../chunk-9ckbc9mk.js";import"../chunk-50ycrgx6.js";import"../chunk-rszb1n1d.js";export{a as RetryTransport};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=E23A1A46F1523BB564756E2164756E21
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
3
|
+
"sources": [],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * @module\n * RetryTransport — decorator that wraps any sently transport\n * and retries failed sends with configurable backoff.\n * Works with SMTP, Resend, SendGrid, SES, and any custom transport.\n *\n * @example\n * ```ts\n * import { RetryTransport } from 'sently/transports/retry'\n * import { ResendTransport } from 'sently/transports/resend'\n *\n * const transport = new RetryTransport(\n * new ResendTransport({ apiKey }),\n * { maxAttempts: 3, backoff: 'exponential', retryOn: [429, 503] }\n * )\n * ```\n */\nimport { SMTPError } from \"../core/smtp.js\";\nimport type {\n MailOptions,\n RetryConfig,\n SendResult,\n Transport,\n VerifyResult,\n} from \"../core/types.js\";\n\nconst DEFAULT_RETRY_ON = [429, 500, 502, 503, 504];\n\nfunction computeDelay(attempt: number, backoff: string, base: number): number {\n if (backoff === \"exponential\") {\n return base * 2 ** (attempt - 1);\n }\n if (backoff === \"linear\") {\n return base * attempt;\n }\n return base;\n}\n\nfunction shouldRetry(err: unknown, retryOn: number[]): boolean {\n if (err instanceof SMTPError && err.code === 535) {\n return false;\n }\n\n if (\n typeof err === \"object\" &&\n err !== null &&\n \"statusCode\" in err &&\n typeof (err as { statusCode: unknown }).statusCode === \"number\"\n ) {\n return retryOn.includes((err as { statusCode: number }).statusCode);\n }\n\n return true;\n}\n\n/**\n * Decorator transport that retries failed sends with configurable backoff.\n */\nexport class RetryTransport implements Transport {\n /** Maximum send attempts including the initial try. */\n private readonly maxAttempts: number;\n /** Backoff strategy between retries. */\n private readonly backoff: \"exponential\" | \"linear\" | \"fixed\";\n /** Base delay in milliseconds before the first retry. */\n private readonly baseDelay: number;\n /** HTTP status codes that trigger a retry. */\n private readonly retryOn: number[];\n /** Optional callback invoked before each retry attempt. */\n private readonly onRetry: RetryConfig[\"onRetry\"];\n\n /** Wraps an inner transport with retry logic and optional backoff configuration. */\n constructor(\n /** Transport that performs the actual send on each attempt. */\n private readonly inner: Transport,\n config?: RetryConfig,\n /** Injectable sleep function for testing backoff timing. */\n private readonly _sleep: (ms: number) => Promise<void> = (ms) =>\n new Promise((resolve) => setTimeout(resolve, ms)),\n ) {\n this.maxAttempts = config?.maxAttempts ?? 3;\n this.backoff = config?.backoff ?? \"exponential\";\n this.baseDelay = config?.baseDelay ?? 1000;\n this.retryOn = config?.retryOn ?? DEFAULT_RETRY_ON;\n this.onRetry = config?.onRetry;\n }\n\n /** Sends with retries according to configured backoff and retry rules. */\n async send(options: MailOptions): Promise<SendResult> {\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n try {\n return await this.inner.send(options);\n } catch (err) {\n lastError = err;\n if (attempt === this.maxAttempts) {\n throw err;\n }\n if (!shouldRetry(err, this.retryOn)) {\n throw err;\n }\n const delay = computeDelay(attempt, this.backoff, this.baseDelay);\n this.onRetry?.(attempt, err);\n await this._sleep(delay);\n }\n }\n\n throw lastError;\n }\n\n /** Delegates to the inner transport verify or returns a default success result. */\n async verify(): Promise<VerifyResult> {\n if (this.inner.verify) {\n return this.inner.verify();\n }\n return { ok: true, provider: \"retry\" };\n }\n\n /** Delegates close to the inner transport if available. */\n async close(): Promise<void> {\n await this.inner.close?.();\n }\n\n /** Delegates batch sends to the inner transport when available. */\n async sendBatch(messages: MailOptions[]): Promise<SendResult[]> {\n if (this.inner.sendBatch) {\n return this.inner.sendBatch(messages);\n }\n return Promise.all(messages.map((message) => this.send(message)));\n }\n}\n"
|
|
6
5
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
6
|
+
"mappings": "",
|
|
7
|
+
"debugId": "E23A1A46F1523BB564756E2164756E21",
|
|
9
8
|
"names": []
|
|
10
9
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { SentlyError } from "../core/errors.js";
|
|
1
2
|
import type { MailOptions, SendResult, Transport, VerifyResult } from "../core/types.js";
|
|
2
3
|
/** SendGrid API configuration. */
|
|
3
4
|
export interface SendGridConfig {
|
|
@@ -5,7 +6,7 @@ export interface SendGridConfig {
|
|
|
5
6
|
apiKey: string;
|
|
6
7
|
}
|
|
7
8
|
/** Error thrown when the SendGrid API returns a non-success response. */
|
|
8
|
-
export declare class SendGridError extends
|
|
9
|
+
export declare class SendGridError extends SentlyError {
|
|
9
10
|
readonly statusCode: number;
|
|
10
11
|
readonly apiError: unknown;
|
|
11
12
|
/** Creates a SendGrid API error with status code and response payload. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{s as R}from"../chunk-z7j2n9k8.js";import{A as K,y as H}from"../chunk-xdx6ypr5.js";import{O,P as Q}from"../chunk-9ckbc9mk.js";import{R as N}from"../chunk-50ycrgx6.js";import"../chunk-rszb1n1d.js";class M extends O{statusCode;apiError;constructor(q,w,D){super(q,Q(w),{statusCode:w,provider:"sendgrid",cause:D});this.statusCode=w;this.apiError=D;this.name="SendGridError"}}class U{apiKey;constructor(q){this.apiKey=q.apiKey}buildPersonalization(q){return{to:H(q.to).map((w)=>({email:w.address,name:w.name})),...q.cc?{cc:H(q.cc).map((w)=>({email:w.address,name:w.name}))}:{},...q.bcc?{bcc:H(q.bcc).map((w)=>({email:w.address,name:w.name}))}:{},subject:q.subject,...q.headers?{headers:q.headers}:{}}}buildContent(q){return[...q.text?[{type:"text/plain",value:q.text}]:[],...q.html?[{type:"text/html",value:q.html}]:[]]}toSendResult(q,w,D="Accepted"){let J=H(q.from)[0];return{messageId:w,accepted:K(q.to),rejected:[],response:D,envelope:{from:J?.address??"",to:[...K(q.to),...q.cc?K(q.cc):[],...q.bcc?K(q.bcc):[]]}}}async send(q){let w=await R(q.attachments),D=H(q.from)[0],J={personalizations:[this.buildPersonalization(q)],from:D?{email:D.address,...D.name?{name:D.name}:{}}:{email:""},...q.replyTo?{reply_to:H(q.replyTo).map((z)=>({email:z.address,name:z.name}))[0]}:{},content:this.buildContent(q),...w.length>0?{attachments:w.map((z)=>({filename:z.filename,type:z.contentType??"application/octet-stream",content:z.content instanceof Uint8Array?N(z.content).replace(/\r\n/g,""):z.content,...z.contentId?{content_id:z.contentId}:{},disposition:z.inline?"inline":"attachment"}))}:{}},F=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(J)});if(!F.ok){let z=await F.text();throw new M("SendGrid API error",F.status,z)}let L=F.headers.get("x-message-id")??q.messageId??"";return this.toSendResult(q,L)}async sendBatch(q){if(q.length===0)return[];let w=q[0],D=H(w.from)[0],J={personalizations:q.map((z)=>this.buildPersonalization(z)),from:D?{email:D.address,...D.name?{name:D.name}:{}}:{email:""},...w.replyTo?{reply_to:H(w.replyTo).map((z)=>({email:z.address,name:z.name}))[0]}:{},content:this.buildContent(w)},F=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(J)});if(!F.ok){let z=await F.text();throw new M("SendGrid API error",F.status,z)}let L=F.headers.get("x-message-id")??"";return q.map((z)=>this.toSendResult(z,L||z.messageId||""))}async verify(){try{let q=await fetch("https://api.sendgrid.com/v3/user/profile",{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!q.ok)return{ok:!1,provider:"sendgrid",message:await q.text().catch(()=>"")||`HTTP ${q.status}`};let w=await q.json();return{ok:!0,provider:"sendgrid",...w.username?{message:w.username}:{}}}catch(q){return{ok:!1,provider:"sendgrid",message:q instanceof Error?q.message:String(q)}}}}export{U as SendGridTransport,M as SendGridError};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=D5356E710A7D1CC664756E2164756E21
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/transports/sendgrid.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * @module\n * SendGrid v3 HTTP API transport for sending email via api.sendgrid.com.\n *\n * @example\n * ```ts\n * import { SendGridTransport } from \"sently/transports/sendgrid\";\n * import { createMailer } from \"sently\";\n *\n * const mailer = await createMailer({\n * transport: new SendGridTransport({ apiKey: process.env.SENDGRID_API_KEY! }),\n * });\n *\n * await mailer.send({\n * from: \"sender@example.com\",\n * to: \"recipient@example.com\",\n * subject: \"Hello\",\n * text: \"Plain text body\",\n * });\n * ```\n */\nimport { extractEmails, parseAddresses } from \"../core/address.js\";\nimport { encodeBase64 } from \"../core/base64.js\";\nimport type { MailOptions, SendResult, Transport, VerifyResult } from \"../core/types.js\";\nimport { resolveAttachments } from \"./resolve-attachments.js\";\n\n/** SendGrid API configuration. */\nexport interface SendGridConfig {\n /** SendGrid API key (Bearer token). */\n apiKey: string;\n}\n\n/** Error thrown when the SendGrid API returns a non-success response. */\nexport class SendGridError extends
|
|
5
|
+
"/**\n * @module\n * SendGrid v3 HTTP API transport for sending email via api.sendgrid.com.\n *\n * @example\n * ```ts\n * import { SendGridTransport } from \"sently/transports/sendgrid\";\n * import { createMailer } from \"sently\";\n *\n * const mailer = await createMailer({\n * transport: new SendGridTransport({ apiKey: process.env.SENDGRID_API_KEY! }),\n * });\n *\n * await mailer.send({\n * from: \"sender@example.com\",\n * to: \"recipient@example.com\",\n * subject: \"Hello\",\n * text: \"Plain text body\",\n * });\n * ```\n */\nimport { extractEmails, parseAddresses } from \"../core/address.js\";\nimport { encodeBase64 } from \"../core/base64.js\";\nimport { httpStatusToSentlyCode, SentlyError } from \"../core/errors.js\";\nimport type { MailOptions, SendResult, Transport, VerifyResult } from \"../core/types.js\";\nimport { resolveAttachments } from \"./resolve-attachments.js\";\n\n/** SendGrid API configuration. */\nexport interface SendGridConfig {\n /** SendGrid API key (Bearer token). */\n apiKey: string;\n}\n\n/** Error thrown when the SendGrid API returns a non-success response. */\nexport class SendGridError extends SentlyError {\n /** Creates a SendGrid API error with status code and response payload. */\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly apiError: unknown,\n ) {\n super(message, httpStatusToSentlyCode(statusCode), {\n statusCode,\n provider: \"sendgrid\",\n cause: apiError,\n });\n this.name = \"SendGridError\";\n }\n}\n\n/**\n * SendGrid v3 HTTP API transport.\n */\nexport class SendGridTransport implements Transport {\n /** SendGrid API key for Bearer authentication. */\n private readonly apiKey: string;\n\n /** Creates a SendGrid transport with the given API key. */\n constructor(config: SendGridConfig) {\n this.apiKey = config.apiKey;\n }\n\n /** Build a SendGrid personalization for one message. */\n private buildPersonalization(options: MailOptions): Record<string, unknown> {\n return {\n to: parseAddresses(options.to).map((addr) => ({ email: addr.address, name: addr.name })),\n ...(options.cc\n ? {\n cc: parseAddresses(options.cc).map((addr) => ({\n email: addr.address,\n name: addr.name,\n })),\n }\n : {}),\n ...(options.bcc\n ? {\n bcc: parseAddresses(options.bcc).map((addr) => ({\n email: addr.address,\n name: addr.name,\n })),\n }\n : {}),\n subject: options.subject,\n ...(options.headers ? { headers: options.headers } : {}),\n };\n }\n\n /** Build SendGrid content parts from text/html options. */\n private buildContent(options: MailOptions): Array<{ type: string; value: string }> {\n return [\n ...(options.text ? [{ type: \"text/plain\", value: options.text }] : []),\n ...(options.html ? [{ type: \"text/html\", value: options.html }] : []),\n ];\n }\n\n /** Map a SendGrid response to a normalized SendResult for one message. */\n private toSendResult(\n options: MailOptions,\n messageId: string,\n responseText = \"Accepted\",\n ): SendResult {\n const from = parseAddresses(options.from)[0];\n return {\n messageId,\n accepted: extractEmails(options.to),\n rejected: [],\n response: responseText,\n envelope: {\n from: from?.address ?? \"\",\n to: [\n ...extractEmails(options.to),\n ...(options.cc ? extractEmails(options.cc) : []),\n ...(options.bcc ? extractEmails(options.bcc) : []),\n ],\n },\n };\n }\n\n /** Sends an email via the SendGrid v3 HTTP API. */\n async send(options: MailOptions): Promise<SendResult> {\n const attachments = await resolveAttachments(options.attachments);\n const from = parseAddresses(options.from)[0];\n\n const body = {\n personalizations: [this.buildPersonalization(options)],\n from: from\n ? { email: from.address, ...(from.name ? { name: from.name } : {}) }\n : { email: \"\" },\n ...(options.replyTo\n ? {\n reply_to: parseAddresses(options.replyTo).map((addr) => ({\n email: addr.address,\n name: addr.name,\n }))[0],\n }\n : {}),\n content: this.buildContent(options),\n ...(attachments.length > 0\n ? {\n attachments: attachments.map((att) => ({\n filename: att.filename,\n type: att.contentType ?? \"application/octet-stream\",\n content:\n att.content instanceof Uint8Array\n ? encodeBase64(att.content).replace(/\\r\\n/g, \"\")\n : att.content,\n ...(att.contentId ? { content_id: att.contentId } : {}),\n disposition: att.inline ? \"inline\" : \"attachment\",\n })),\n }\n : {}),\n };\n\n const response = await fetch(\"https://api.sendgrid.com/v3/mail/send\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const apiError = await response.text();\n throw new SendGridError(\"SendGrid API error\", response.status, apiError);\n }\n\n const messageId = response.headers.get(\"x-message-id\") ?? options.messageId ?? \"\";\n\n return this.toSendResult(options, messageId);\n }\n\n /** Send multiple messages in one request using SendGrid personalizations. */\n async sendBatch(messages: MailOptions[]): Promise<SendResult[]> {\n if (messages.length === 0) {\n return [];\n }\n\n const first = messages[0] as MailOptions;\n const from = parseAddresses(first.from)[0];\n\n const body = {\n personalizations: messages.map((message) => this.buildPersonalization(message)),\n from: from\n ? { email: from.address, ...(from.name ? { name: from.name } : {}) }\n : { email: \"\" },\n ...(first.replyTo\n ? {\n reply_to: parseAddresses(first.replyTo).map((addr) => ({\n email: addr.address,\n name: addr.name,\n }))[0],\n }\n : {}),\n content: this.buildContent(first),\n };\n\n const response = await fetch(\"https://api.sendgrid.com/v3/mail/send\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const apiError = await response.text();\n throw new SendGridError(\"SendGrid API error\", response.status, apiError);\n }\n\n const messageId = response.headers.get(\"x-message-id\") ?? \"\";\n return messages.map((message) =>\n this.toSendResult(message, messageId || message.messageId || \"\"),\n );\n }\n\n /** Verifies the SendGrid API key by fetching the user profile. */\n async verify(): Promise<VerifyResult> {\n try {\n const response = await fetch(\"https://api.sendgrid.com/v3/user/profile\", {\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n },\n });\n\n if (!response.ok) {\n const apiError = await response.text().catch(() => \"\");\n return {\n ok: false,\n provider: \"sendgrid\",\n message: apiError || `HTTP ${response.status}`,\n };\n }\n\n const payload = (await response.json()) as { username?: string };\n return {\n ok: true,\n provider: \"sendgrid\",\n ...(payload.username ? { message: payload.username } : {}),\n };\n } catch (err) {\n return {\n ok: false,\n provider: \"sendgrid\",\n message: err instanceof Error ? err.message : String(err),\n };\n }\n }\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "8NAkCO,CAAM,KAAsB,JAAY,JAI3B,WACA,SAHlB,WAAW,CACT,EACgB,EACA,EAChB,CACA,MAAM,EAAS,EAAuB,CAAU,EAAG,CACjD,aACA,SAAU,WACV,MAAO,CACT,CAAC,EAPe,kBACA,gBAOhB,KAAK,KAAO,gBAEhB,CAKO,MAAM,CAAuC,CAEjC,OAGjB,WAAW,CAAC,EAAwB,CAClC,KAAK,OAAS,EAAO,OAIf,oBAAoB,CAAC,EAA+C,CAC1E,MAAO,CACL,GAAI,EAAe,EAAQ,EAAE,EAAE,IAAI,CAAC,KAAU,CAAE,MAAO,EAAK,QAAS,KAAM,EAAK,IAAK,EAAE,KACnF,EAAQ,GACR,CACE,GAAI,EAAe,EAAQ,EAAE,EAAE,IAAI,CAAC,KAAU,CAC5C,MAAO,EAAK,QACZ,KAAM,EAAK,IACb,EAAE,CACJ,EACA,CAAC,KACD,EAAQ,IACR,CACE,IAAK,EAAe,EAAQ,GAAG,EAAE,IAAI,CAAC,KAAU,CAC9C,MAAO,EAAK,QACZ,KAAM,EAAK,IACb,EAAE,CACJ,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AAI,CAChB,IAAM,EAAW,MAAM,EAAS,KAAK,EACrC,MAAM,IAAI,EAAc,qBAAsB,EAAS,OAAQ,CAAQ,EAGzE,IAAM,EAAY,EAAS,QAAQ,IAAI,cAAc,GAAK,GAC1D,OAAO,EAAS,IAAI,CAAC,IACnB,KAAK,aAAa,EAAS,GAAa,EAAQ,WAAa,EAAE,CACjE,OAII,OAAM,EAA0B,CACpC,GAAI,CACF,IAAM,EAAW,MAAM,MAAM,2CAA4C,CACvE,QAAS,CACP,cAAe,UAAU,KAAK,QAChC,CACF,CAAC,EAED,GAAI,CAAC,EAAS,GAEZ,MAAO,CACL,GAAI,GACJ,SAAU,WACV,QAJe,MAAM,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,GAI9B,QAAQ,EAAS,QACxC,EAGF,IAAM,EAAW,MAAM,EAAS,KAAK,EACrC,MAAO,CACL,GAAI,GACJ,SAAU,cACN,EAAQ,SAAW,CAAE,QAAS,EAAQ,QAAS,EAAI,CAAC,CAC1D,EACA,MAAO,EAAK,CACZ,MAAO,CACL,GAAI,GACJ,SAAU,WACV,QAAS,aAAe,MAAQ,EAAI,QAAU,OAAO,CAAG,CAC1D,GAGN",
|
|
8
|
+
"debugId": "D5356E710A7D1CC664756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/dist/transports/ses.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
+
import { SentlyError } from "../core/errors.js";
|
|
1
2
|
import type { MailOptions, SESConfig, SendResult, Transport, VerifyResult } from "../core/types.js";
|
|
2
3
|
/** Error thrown when the AWS SES API returns a non-success response. */
|
|
3
|
-
export declare class SESError extends
|
|
4
|
+
export declare class SESError extends SentlyError {
|
|
4
5
|
readonly statusCode: number;
|
|
5
|
-
readonly code: string;
|
|
6
6
|
readonly requestId: string;
|
|
7
7
|
/** Creates an AWS SES API error with status code, error code, and request ID. */
|
|
8
|
-
constructor(message: string, statusCode: number,
|
|
8
|
+
constructor(message: string, statusCode: number, awsCode: string, requestId: string);
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
11
|
* AWS SES v2 HTTP API transport.
|
package/dist/transports/ses.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as v}from"../chunk-v8eh0n8d.js";import{s as b}from"../chunk-z7j2n9k8.js";import{A as D,y as C,z as R}from"../chunk-xdx6ypr5.js";import{O as A,P as k}from"../chunk-9ckbc9mk.js";import{R as x}from"../chunk-50ycrgx6.js";import"../chunk-rszb1n1d.js";var z=new TextEncoder;async function K(F){let G=await crypto.subtle.digest("SHA-256",z.encode(F));return T(new Uint8Array(G))}async function w(F,G){let J=typeof F==="string"?z.encode(F):new Uint8Array(F),X=await crypto.subtle.importKey("raw",J,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),L=await crypto.subtle.sign("HMAC",X,z.encode(G));return new Uint8Array(L)}async function B(F){let{method:G,url:J,body:X,credentials:L}=F,Y=new URL(J),Z=F._date??`${new Date().toISOString().replace(/[-:]/g,"").slice(0,15)}Z`,Q=Z.slice(0,8),$={...Object.fromEntries(Object.entries(F.headers).map(([N,S])=>[N.toLowerCase(),S.trim()])),host:Y.host,"x-amz-date":Z};if(L.sessionToken)$["x-amz-security-token"]=L.sessionToken;let O=Object.keys($).map((N)=>N.toLowerCase()).sort(),V=O.join(";"),P=`${O.map((N)=>`${N}:${$[N]}`).join(`
|
|
2
2
|
`)}
|
|
3
|
-
`,
|
|
4
|
-
`),
|
|
5
|
-
`),
|
|
3
|
+
`,I=y(Y.searchParams),U=await K(X),W=[G.toUpperCase(),u(Y.pathname),I,P,V,U].join(`
|
|
4
|
+
`),_=`${Q}/${L.region}/${L.service}/aws4_request`,M=["AWS4-HMAC-SHA256",Z,_,await K(W)].join(`
|
|
5
|
+
`),H=await h(L.secretAccessKey,Q,L.region,L.service),f=T(await w(H,M)),E=[`AWS4-HMAC-SHA256 Credential=${L.accessKeyId}/${_}`,`SignedHeaders=${V}`,`Signature=${f}`].join(", ");return{headers:{...$,Authorization:E}}}async function h(F,G,J,X){let L=await w(`AWS4${F}`,G),Y=await w(L,J),Z=await w(Y,X);return w(Z,"aws4_request")}function u(F){if(!F||F==="/")return"/";return F.split("/").map((G)=>encodeURIComponent(decodeURIComponent(G))).join("/")}function y(F){let G=[];for(let[J,X]of F.entries())G.push(`${j(J)}=${j(X)}`);return G.sort(),G.join("&")}function j(F){return encodeURIComponent(F).replace(/[!'()*]/g,(G)=>`%${G.charCodeAt(0).toString(16).toUpperCase()}`)}function T(F){return Array.from(F,(G)=>G.toString(16).padStart(2,"0")).join("")}class q extends A{statusCode;requestId;constructor(F,G,J,X){super(F,k(G),{statusCode:G,provider:"ses"});this.statusCode=G;this.requestId=X;this.name="SESError",this.code=J}}class g{accessKeyId;secretAccessKey;region;sessionToken;dkim;constructor(F){this.accessKeyId=F.accessKeyId,this.secretAccessKey=F.secretAccessKey,this.region=F.region??"us-east-1",this.sessionToken=F.sessionToken,this.dkim=F.dkim}async send(F){let G=await b(F.attachments),J={...F,attachments:G},X=C(F.from)[0],L=X?R(X):"",Y=D(F.to),Z=F.cc?D(F.cc):[],Q=F.bcc?D(F.bcc):[],$={ToAddresses:Y,CcAddresses:Z,BccAddresses:Q},O;if(G.length>0){let M=await v(J,this.dkim);O={FromEmailAddress:L,Destination:$,Content:{Raw:{Data:x(M.raw).replace(/\r\n/g,"")}}}}else O={FromEmailAddress:L,Destination:$,Content:{Simple:{Subject:{Data:F.subject,Charset:"UTF-8"},Body:{...F.text?{Text:{Data:F.text,Charset:"UTF-8"}}:{},...F.html?{Html:{Data:F.html,Charset:"UTF-8"}}:{}}}}};let V=JSON.stringify(O),P=`https://email.${this.region}.amazonaws.com/v2/email/outbound-emails`,I=await B({method:"POST",url:P,headers:{"content-type":"application/json"},body:V,credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey,region:this.region,service:"ses",...this.sessionToken?{sessionToken:this.sessionToken}:{}}}),U=await fetch(P,{method:"POST",headers:I.headers,body:V}),W=await U.json();if(!U.ok)throw new q(W.message??"SES API error",U.status,W.Code??"",U.headers.get("x-amzn-requestid")??"");let _=W.MessageId??"";return{messageId:_,accepted:[...Y,...Z,...Q],rejected:[],response:`MessageId: ${_}`,envelope:{from:X?.address??"",to:Y}}}async verify(){try{let F=`https://email.${this.region}.amazonaws.com/v2/email/configuration-sets`,G=await B({method:"GET",url:F,headers:{},body:"",credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey,region:this.region,service:"ses",...this.sessionToken?{sessionToken:this.sessionToken}:{}}}),J=await fetch(F,{method:"GET",headers:G.headers}),X=await J.json().catch(()=>({}));if(!J.ok)return{ok:!1,provider:"ses",message:X.message??`HTTP ${J.status}`};return{ok:!0,provider:"ses",message:"Credentials are valid"}}catch(F){return{ok:!1,provider:"ses",message:F instanceof Error?F.message:String(F)}}}}export{g as SESTransport,q as SESError};
|
|
6
6
|
|
|
7
|
-
//# debugId=
|
|
7
|
+
//# debugId=25B092B6A81597F664756E2164756E21
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
"sources": ["../src/core/sigv4.ts", "../src/transports/ses.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * @module\n * AWS Signature Version 4 signing using Web Crypto (HMAC-SHA256).\n * Works on Node.js, Bun, Deno, and Cloudflare Workers.\n * No external dependencies.\n *\n * @example\n * ```ts\n * import { signRequest } from \"sently/core/sigv4\";\n * const signed = await signRequest({\n * method: \"POST\",\n * url: \"https://email.us-east-1.amazonaws.com/v2/email/outbound-emails\",\n * headers: { \"content-type\": \"application/json\" },\n * body: '{\"...\"}',\n * credentials: { accessKeyId, secretAccessKey, region: \"us-east-1\", service: \"ses\" },\n * });\n * ```\n */\n\n/** AWS credentials and signing scope for SigV4. */\nexport interface SigV4Credentials {\n /** AWS access key ID. */\n accessKeyId: string;\n /** AWS secret access key. */\n secretAccessKey: string;\n /** AWS region (e.g. `us-east-1`). */\n region: string;\n /** AWS service name (e.g. `ses`, `s3`). */\n service: string;\n /** Optional STS session token for temporary credentials. */\n sessionToken?: string;\n}\n\n/** HTTP request to sign with AWS Signature Version 4. */\nexport interface SigV4Request {\n /** HTTP method (e.g. `POST`). */\n method: string;\n /** Full request URL including path and query. */\n url: string;\n /** Request headers to include in the signature. */\n headers: Record<string, string>;\n /** Request body as a string (empty for GET). */\n body: string;\n /** AWS credentials and signing scope. */\n credentials: SigV4Credentials;\n /** Override datetime for testing. Full 'YYYYMMDDTHHMMSSZ' when provided. */\n _date?: string;\n}\n\n/** Signed request headers including Authorization. */\nexport interface SigV4Result {\n /** All headers including Authorization, x-amz-date, and x-amz-security-token */\n headers: Record<string, string>;\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Compute SHA-256 hash of a string using Web Crypto.\n * Returns lowercase hex string.\n * @internal\n */\nexport async function sha256Hex(data: string): Promise<string> {\n const hash = await crypto.subtle.digest(\"SHA-256\", encoder.encode(data));\n return bytesToHex(new Uint8Array(hash));\n}\n\n/**\n * Compute HMAC-SHA256 using Web Crypto.\n * @internal\n */\nexport async function hmacSHA256(key: Uint8Array | string, data: string): Promise<Uint8Array> {\n const keyBytes = typeof key === \"string\" ? encoder.encode(key) : new Uint8Array(key);\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n keyBytes,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(data));\n return new Uint8Array(signature);\n}\n\n/**\n * Sign an HTTP request with AWS Signature Version 4.\n * Returns the complete set of headers to include in the request.\n */\nexport async function signRequest(request: SigV4Request): Promise<SigV4Result> {\n const { method, url, body, credentials } = request;\n const parsed = new URL(url);\n const amzDate = request._date ?? `${new Date().toISOString().replace(/[-:]/g, \"\").slice(0, 15)}Z`;\n const dateStamp = amzDate.slice(0, 8);\n\n const headers: Record<string, string> = {\n ...Object.fromEntries(\n Object.entries(request.headers).map(([key, value]) => [key.toLowerCase(), value.trim()]),\n ),\n host: parsed.host,\n \"x-amz-date\": amzDate,\n };\n\n if (credentials.sessionToken) {\n headers[\"x-amz-security-token\"] = credentials.sessionToken;\n }\n\n const signedHeaderNames = Object.keys(headers)\n .map((name) => name.toLowerCase())\n .sort();\n const signedHeaders = signedHeaderNames.join(\";\");\n const canonicalHeaders = `${signedHeaderNames.map((name) => `${name}:${headers[name]}`).join(\"\\n\")}\\n`;\n const canonicalQuery = normalizeQuery(parsed.searchParams);\n const payloadHash = await sha256Hex(body);\n const canonicalRequest = [\n method.toUpperCase(),\n canonicalUri(parsed.pathname),\n canonicalQuery,\n canonicalHeaders,\n signedHeaders,\n payloadHash,\n ].join(\"\\n\");\n\n const credentialScope = `${dateStamp}/${credentials.region}/${credentials.service}/aws4_request`;\n const stringToSign = [\n \"AWS4-HMAC-SHA256\",\n amzDate,\n credentialScope,\n await sha256Hex(canonicalRequest),\n ].join(\"\\n\");\n\n const signingKey = await deriveSigningKey(\n credentials.secretAccessKey,\n dateStamp,\n credentials.region,\n credentials.service,\n );\n const signature = bytesToHex(await hmacSHA256(signingKey, stringToSign));\n const authorization = [\n `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${credentialScope}`,\n `SignedHeaders=${signedHeaders}`,\n `Signature=${signature}`,\n ].join(\", \");\n\n return {\n headers: {\n ...headers,\n Authorization: authorization,\n },\n };\n}\n\nasync function deriveSigningKey(\n secretAccessKey: string,\n dateStamp: string,\n region: string,\n service: string,\n): Promise<Uint8Array> {\n const kDate = await hmacSHA256(`AWS4${secretAccessKey}`, dateStamp);\n const kRegion = await hmacSHA256(kDate, region);\n const kService = await hmacSHA256(kRegion, service);\n return hmacSHA256(kService, \"aws4_request\");\n}\n\nfunction canonicalUri(pathname: string): string {\n if (!pathname || pathname === \"/\") {\n return \"/\";\n }\n return pathname\n .split(\"/\")\n .map((segment) => encodeURIComponent(decodeURIComponent(segment)))\n .join(\"/\");\n}\n\nfunction normalizeQuery(searchParams: URLSearchParams): string {\n const pairs: string[] = [];\n for (const [key, value] of searchParams.entries()) {\n pairs.push(`${encodeRfc3986(key)}=${encodeRfc3986(value)}`);\n }\n pairs.sort();\n return pairs.join(\"&\");\n}\n\nfunction encodeRfc3986(value: string): string {\n return encodeURIComponent(value).replace(\n /[!'()*]/g,\n (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n",
|
|
6
|
-
"/**\n * @module\n * AWS SES v2 HTTP transport for sently.\n * Signs requests with AWS Signature Version 4 using Web Crypto.\n * Works on Node.js, Bun, Deno, and Cloudflare Workers.\n *\n * @example\n * ```ts\n * import { SESTransport } from \"sently/transports/ses\";\n * import { createMailer } from \"sently\";\n *\n * const mailer = await createMailer({\n * transport: new SESTransport({\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * region: \"us-east-1\",\n * }),\n * });\n * ```\n */\nimport { extractEmails, parseAddresses, toMIMEHeader } from \"../core/address.js\";\nimport { encodeBase64 } from \"../core/base64.js\";\nimport { buildMIME } from \"../core/mime.js\";\nimport { signRequest } from \"../core/sigv4.js\";\nimport type { MailOptions, SESConfig, SendResult, Transport, VerifyResult } from \"../core/types.js\";\nimport { resolveAttachments } from \"./resolve-attachments.js\";\n\n/** Error thrown when the AWS SES API returns a non-success response. */\nexport class SESError extends
|
|
6
|
+
"/**\n * @module\n * AWS SES v2 HTTP transport for sently.\n * Signs requests with AWS Signature Version 4 using Web Crypto.\n * Works on Node.js, Bun, Deno, and Cloudflare Workers.\n *\n * @example\n * ```ts\n * import { SESTransport } from \"sently/transports/ses\";\n * import { createMailer } from \"sently\";\n *\n * const mailer = await createMailer({\n * transport: new SESTransport({\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * region: \"us-east-1\",\n * }),\n * });\n * ```\n */\nimport { extractEmails, parseAddresses, toMIMEHeader } from \"../core/address.js\";\nimport { encodeBase64 } from \"../core/base64.js\";\nimport { httpStatusToSentlyCode, SentlyError } from \"../core/errors.js\";\nimport { buildMIME } from \"../core/mime.js\";\nimport { signRequest } from \"../core/sigv4.js\";\nimport type { MailOptions, SESConfig, SendResult, Transport, VerifyResult } from \"../core/types.js\";\nimport { resolveAttachments } from \"./resolve-attachments.js\";\n\n/** Error thrown when the AWS SES API returns a non-success response. */\nexport class SESError extends SentlyError {\n /** Creates an AWS SES API error with status code, error code, and request ID. */\n constructor(\n message: string,\n public readonly statusCode: number,\n awsCode: string,\n public readonly requestId: string,\n ) {\n super(message, httpStatusToSentlyCode(statusCode), {\n statusCode,\n provider: \"ses\",\n });\n this.name = \"SESError\";\n this.code = awsCode;\n }\n}\n\n/**\n * AWS SES v2 HTTP API transport.\n */\nexport class SESTransport implements Transport {\n /** AWS access key ID for SigV4 signing. */\n private readonly accessKeyId: string;\n /** AWS secret access key for SigV4 signing. */\n private readonly secretAccessKey: string;\n /** AWS region for the SES endpoint. */\n private readonly region: string;\n /** Optional STS session token for temporary credentials. */\n private readonly sessionToken: string | undefined;\n /** Optional DKIM config for raw MIME attachment sends. */\n private readonly dkim: SESConfig[\"dkim\"];\n\n /** Creates an SES transport with AWS credentials. */\n constructor(config: SESConfig) {\n this.accessKeyId = config.accessKeyId;\n this.secretAccessKey = config.secretAccessKey;\n this.region = config.region ?? \"us-east-1\";\n this.sessionToken = config.sessionToken;\n this.dkim = config.dkim;\n }\n\n /** Sends an email via the AWS SES v2 HTTP API. */\n async send(options: MailOptions): Promise<SendResult> {\n const attachments = await resolveAttachments(options.attachments);\n const resolvedOptions = { ...options, attachments };\n const from = parseAddresses(options.from)[0];\n const fromEmail = from ? toMIMEHeader(from) : \"\";\n const toEmails = extractEmails(options.to);\n const ccEmails = options.cc ? extractEmails(options.cc) : [];\n const bccEmails = options.bcc ? extractEmails(options.bcc) : [];\n\n const destination = {\n ToAddresses: toEmails,\n CcAddresses: ccEmails,\n BccAddresses: bccEmails,\n };\n\n let requestBody: Record<string, unknown>;\n\n if (attachments.length > 0) {\n const mime = await buildMIME(resolvedOptions, this.dkim);\n requestBody = {\n FromEmailAddress: fromEmail,\n Destination: destination,\n Content: {\n Raw: {\n Data: encodeBase64(mime.raw).replace(/\\r\\n/g, \"\"),\n },\n },\n };\n } else {\n requestBody = {\n FromEmailAddress: fromEmail,\n Destination: destination,\n Content: {\n Simple: {\n Subject: { Data: options.subject, Charset: \"UTF-8\" },\n Body: {\n ...(options.text ? { Text: { Data: options.text, Charset: \"UTF-8\" } } : {}),\n ...(options.html ? { Html: { Data: options.html, Charset: \"UTF-8\" } } : {}),\n },\n },\n },\n };\n }\n\n const body = JSON.stringify(requestBody);\n const url = `https://email.${this.region}.amazonaws.com/v2/email/outbound-emails`;\n const signed = await signRequest({\n method: \"POST\",\n url,\n headers: {\n \"content-type\": \"application/json\",\n },\n body,\n credentials: {\n accessKeyId: this.accessKeyId,\n secretAccessKey: this.secretAccessKey,\n region: this.region,\n service: \"ses\",\n ...(this.sessionToken ? { sessionToken: this.sessionToken } : {}),\n },\n });\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: signed.headers,\n body,\n });\n\n const payload = (await response.json()) as {\n MessageId?: string;\n message?: string;\n Code?: string;\n };\n\n if (!response.ok) {\n throw new SESError(\n payload.message ?? \"SES API error\",\n response.status,\n payload.Code ?? \"\",\n response.headers.get(\"x-amzn-requestid\") ?? \"\",\n );\n }\n\n const messageId = payload.MessageId ?? \"\";\n return {\n messageId,\n accepted: [...toEmails, ...ccEmails, ...bccEmails],\n rejected: [],\n response: `MessageId: ${messageId}`,\n envelope: {\n from: from?.address ?? \"\",\n to: toEmails,\n },\n };\n }\n\n /** Verifies AWS credentials by listing SES configuration sets. */\n async verify(): Promise<VerifyResult> {\n try {\n const url = `https://email.${this.region}.amazonaws.com/v2/email/configuration-sets`;\n const signed = await signRequest({\n method: \"GET\",\n url,\n headers: {},\n body: \"\",\n credentials: {\n accessKeyId: this.accessKeyId,\n secretAccessKey: this.secretAccessKey,\n region: this.region,\n service: \"ses\",\n ...(this.sessionToken ? { sessionToken: this.sessionToken } : {}),\n },\n });\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: signed.headers,\n });\n\n const payload = (await response.json().catch(() => ({}))) as { message?: string };\n\n if (!response.ok) {\n return {\n ok: false,\n provider: \"ses\",\n message: payload.message ?? `HTTP ${response.status}`,\n };\n }\n\n return { ok: true, provider: \"ses\", message: \"Credentials are valid\" };\n } catch (err) {\n return {\n ok: false,\n provider: \"ses\",\n message: err instanceof Error ? err.message : String(err),\n };\n }\n }\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": "
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": "wRAuDA,DAAM,HAAU,DAAI,OAOpB,UAAsB,CAAS,CAAC,EAA+B,CAC7D,IAAM,EAAO,MAAM,OAAO,OAAO,OAAO,UAAW,EAAQ,OAAO,CAAI,CAAC,EACvE,OAAO,EAAW,IAAI,WAAW,CAAI,CAAC,EAOxC,eAAsB,CAAU,CAAC,EAA0B,EAAmC,CAC5F,IAAM,EAAW,OAAO,IAAQ,SAAW,EAAQ,OAAO,CAAG,EAAI,IAAI,WAAW,CAAG,EAC7E,EAAY,MAAM,OAAO,OAAO,UACpC,MACA,EACA,CAAE,KAAM,OAAQ,KAAM,SAAU,EAChC,GACA,CAAC,MAAM,CACT,EACM,EAAY,MAAM,OAAO,OAAO,KAAK,OAAQ,EAAW,EAAQ,OAAO,CAAI,CAAC,EAClF,OAAO,IAAI,WAAW,CAAS,EAOjC,eAAsB,CAAW,CAAC,EAA6C,CAC7E,IAAQ,SAAQ,MAAK,OAAM,eAAgB,EACrC,EAAS,IAAI,IAAI,CAAG,EACpB,EAAU,EAAQ,OAAS,GAAG,IAAI,KAAK,EAAE,YAAY,EAAE,QAAQ,QAAS,EAAE,EAAE,MAA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AAI,EACR,EAAQ,SAAW,gBACnB,EAAS,OACT,EAAQ,MAAQ,GAChB,EAAS,QAAQ,IAAI,kBAAkB,GAAK,EAC9C,EAGF,IAAM,EAAY,EAAQ,WAAa,GACvC,MAAO,CACL,YACA,SAAU,CAAC,GAAG,EAAU,GAAG,EAAU,GAAG,CAAS,EACjD,SAAU,CAAC,EACX,SAAU,cAAc,IACxB,SAAU,CACR,KAAM,GAAM,SAAW,GACvB,GAAI,CACN,CACF,OAII,OAAM,EAA0B,CACpC,GAAI,CACF,IAAM,EAAM,iBAAiB,KAAK,mDAC5B,EAAS,MAAM,EAAY,CAC/B,OAAQ,MACR,MACA,QAAS,CAAC,EACV,KAAM,GACN,YAAa,CACX,YAAa,KAAK,YAClB,gBAAiB,KAAK,gBACtB,OAAQ,KAAK,OACb,QAAS,SACL,KAAK,aAAe,CAAE,aAAc,KAAK,YAAa,EAAI,CAAC,CACjE,CACF,CAAC,EAEK,EAAW,MAAM,MAAM,EAAK,CAChC,OAAQ,MACR,QAAS,EAAO,OAClB,CAAC,EAEK,EAAW,MAAM,EAAS,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAEvD,GAAI,CAAC,EAAS,GACZ,MAAO,CACL,GAAI,GACJ,SAAU,MACV,QAAS,EAAQ,SAAW,QAAQ,EAAS,QAC/C,EAGF,MAAO,CAAE,GAAI,GAAM,SAAU,MAAO,QAAS,uBAAwB,EACrE,MAAO,EAAK,CACZ,MAAO,CACL,GAAI,GACJ,SAAU,MACV,QAAS,aAAe,MAAQ,EAAI,QAAU,OAAO,CAAG,CAC1D,GAGN",
|
|
9
|
+
"debugId": "25B092B6A81597F664756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/dist/transports/smtp.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{h as b,i as c,j as d,k as e,l as f,m as g}from"../chunk-bzw0fdmy.js";import"../chunk-zm7fe0wb.js";import"../chunk-v8eh0n8d.js";import"../chunk-z7j2n9k8.js";import"../chunk-xdx6ypr5.js";import{N as a}from"../chunk-gkec86xg.js";import"../chunk-9ckbc9mk.js";import"../chunk-50ycrgx6.js";import"../chunk-rszb1n1d.js";export{c as resolveSMTPConfig,g as readSMTPResponse,d as openSMTPSession,a as encodeLine,e as deliverSMTPMessage,f as closeSMTPSession,b as SMTPTransport};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=72E6D49ED16F0C8B64756E2164756E21
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{d as F,e as u,f as G,g as H}from"../chunk-q8k3m6qe.js";import"../chunk-rszb1n1d.js";var K={delivered:"delivered",hard_bounce:"bounced",hardBounce:"bounced",soft_bounce:"bounced",soft_bounced:"bounced",softBounce:"bounced",blocked:"bounced",invalid:"bounced",invalid_email:"bounced",deferred:"deferred",spam:"complained",opened:"opened",unique_opened:"opened",uniqueOpened:"opened",click:"clicked",clicked:"clicked",unique_click:"clicked",uniqueClicked:"clicked",sent:"unknown",request:"unknown",unsubscribe:"complained",unsubscribed:"complained"};function L(f){return u(f.ts_event)??u(f.ts)??u(f.date_event)??u(f.date)??u(f.ts_epoch!==void 0?Number(f.ts_epoch):void 0)}function Q(f){if(typeof f["message-id"]==="string")return f["message-id"];if(typeof f.messageId==="string")return f.messageId;return}function U(f){return G(f).flatMap((x)=>{if(typeof x!=="object"||x===null)return[];let q=x,J=typeof q.event==="string"?q.event:"",C=L(q),D=Q(q);return[H({provider:"brevo",type:F(J,K),...D!==void 0?{messageId:D}:{},...typeof q.email==="string"?{recipient:q.email}:{},...C!==void 0?{timestamp:C}:{},raw:x})]})}export{U as parse};
|
|
2
|
+
|
|
3
|
+
//# debugId=916BC5D0AADEB5C764756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/webhooks/brevo.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { EmailEvent } from \"./types.js\";\nimport { asArray, emailEvent, mapEventType, parseTimestamp } from \"./types.js\";\n\nconst BREVO_EVENT_MAP: Record<string, EmailEvent[\"type\"]> = {\n delivered: \"delivered\",\n hard_bounce: \"bounced\",\n hardBounce: \"bounced\",\n soft_bounce: \"bounced\",\n soft_bounced: \"bounced\",\n softBounce: \"bounced\",\n blocked: \"bounced\",\n invalid: \"bounced\",\n invalid_email: \"bounced\",\n deferred: \"deferred\",\n spam: \"complained\",\n opened: \"opened\",\n unique_opened: \"opened\",\n uniqueOpened: \"opened\",\n click: \"clicked\",\n clicked: \"clicked\",\n unique_click: \"clicked\",\n uniqueClicked: \"clicked\",\n sent: \"unknown\",\n request: \"unknown\",\n unsubscribe: \"complained\",\n unsubscribed: \"complained\",\n};\n\nfunction resolveBrevoTimestamp(record: Record<string, unknown>): Date | undefined {\n return (\n parseTimestamp(record.ts_event) ??\n parseTimestamp(record.ts) ??\n parseTimestamp(record.date_event) ??\n parseTimestamp(record.date) ??\n parseTimestamp(record.ts_epoch !== undefined ? Number(record.ts_epoch) : undefined)\n );\n}\n\nfunction resolveBrevoMessageId(record: Record<string, unknown>): string | undefined {\n if (typeof record[\"message-id\"] === \"string\") {\n return record[\"message-id\"];\n }\n if (typeof record.messageId === \"string\") {\n return record.messageId;\n }\n return undefined;\n}\n\n/** Parse a Brevo webhook payload into normalized {@link EmailEvent} records. */\nexport function parse(payload: unknown): EmailEvent[] {\n return asArray(payload).flatMap((item) => {\n if (typeof item !== \"object\" || item === null) {\n return [];\n }\n\n const record = item as Record<string, unknown>;\n const event = typeof record.event === \"string\" ? record.event : \"\";\n const timestamp = resolveBrevoTimestamp(record);\n const messageId = resolveBrevoMessageId(record);\n\n return [\n emailEvent({\n provider: \"brevo\",\n type: mapEventType(event, BREVO_EVENT_MAP),\n ...(messageId !== undefined ? { messageId } : {}),\n ...(typeof record.email === \"string\" ? { recipient: record.email } : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n raw: item,\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
|
|
10
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as G,c as H}from"../chunk-pqp843mh.js";import{d as Y,e as Z,g as $}from"../chunk-q8k3m6qe.js";import"../chunk-rszb1n1d.js";var R={accepted:"unknown",delivered:"delivered",rejected:"bounced",complained:"complained",opened:"opened",clicked:"clicked",stored:"unknown",unsubscribed:"unknown"};function U(z){let J=typeof z.event==="string"?z.event:"";if(J==="failed")return z.severity==="temporary"?"deferred":"bounced";return Y(J,R)}function b(z){if(!z)return;let J=z.headers;if(typeof J==="object"&&J!==null){let C=J["message-id"];if(typeof C==="string")return C}return typeof z["message-id"]==="string"?z["message-id"]:void 0}function N(z){if(typeof z!=="object"||z===null)return[];let J=z,C=typeof J["event-data"]==="object"&&J["event-data"]!==null?J["event-data"]:J,O=typeof C.message==="object"&&C.message!==null?C.message:void 0,Q=b(O),W=Z(C.timestamp);return[$({provider:"mailgun",type:U(C),...Q!==void 0?{messageId:Q}:{},...typeof C.recipient==="string"?{recipient:C.recipient}:{},...W!==void 0?{timestamp:W}:{},raw:z})]}async function q(z,J,C,O){let Q=await crypto.subtle.importKey("raw",new TextEncoder().encode(O),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),W=new TextEncoder().encode(z+J),L=await crypto.subtle.sign("HMAC",Q,W),P=new Uint8Array(L),X=H(C);if(X===null)return!1;return G(P,X)}async function S(z,J){if(typeof z!=="object"||z===null)return!1;let C=z.signature;if(typeof C!=="object"||C===null)return!1;let O=C;if(typeof O.timestamp!=="string"||typeof O.token!=="string"||typeof O.signature!=="string")return!1;return q(O.timestamp,O.token,O.signature,J)}export{q as verifySignature,S as verifyPayload,N as parse};
|
|
2
|
+
|
|
3
|
+
//# debugId=7FB21CD9E29B4FE264756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/webhooks/mailgun.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { decodeHexBytes, timingSafeEqual } from \"./timing-safe-equal.js\";\nimport type { EmailEvent } from \"./types.js\";\nimport { emailEvent, mapEventType, parseTimestamp } from \"./types.js\";\n\nconst MAILGUN_EVENT_MAP: Record<string, EmailEvent[\"type\"]> = {\n accepted: \"unknown\",\n delivered: \"delivered\",\n rejected: \"bounced\",\n complained: \"complained\",\n opened: \"opened\",\n clicked: \"clicked\",\n stored: \"unknown\",\n unsubscribed: \"unknown\",\n};\n\n/** Map a Mailgun event (and failed severity) to a normalized type. */\nfunction mapMailgunType(eventData: Record<string, unknown>): EmailEvent[\"type\"] {\n const event = typeof eventData.event === \"string\" ? eventData.event : \"\";\n if (event === \"failed\") {\n return eventData.severity === \"temporary\" ? \"deferred\" : \"bounced\";\n }\n return mapEventType(event, MAILGUN_EVENT_MAP);\n}\n\nfunction extractMailgunMessageId(message: Record<string, unknown> | undefined): string | undefined {\n if (!message) {\n return undefined;\n }\n const headers = message.headers;\n if (typeof headers === \"object\" && headers !== null) {\n const messageId = (headers as Record<string, unknown>)[\"message-id\"];\n if (typeof messageId === \"string\") {\n return messageId;\n }\n }\n return typeof message[\"message-id\"] === \"string\" ? message[\"message-id\"] : undefined;\n}\n\n/** Parse a Mailgun webhook payload into normalized {@link EmailEvent} records. */\nexport function parse(payload: unknown): EmailEvent[] {\n if (typeof payload !== \"object\" || payload === null) {\n return [];\n }\n\n const record = payload as Record<string, unknown>;\n const eventData =\n typeof record[\"event-data\"] === \"object\" && record[\"event-data\"] !== null\n ? (record[\"event-data\"] as Record<string, unknown>)\n : record;\n\n const message =\n typeof eventData.message === \"object\" && eventData.message !== null\n ? (eventData.message as Record<string, unknown>)\n : undefined;\n\n const messageId = extractMailgunMessageId(message);\n const timestamp = parseTimestamp(eventData.timestamp);\n\n return [\n emailEvent({\n provider: \"mailgun\",\n type: mapMailgunType(eventData),\n ...(messageId !== undefined ? { messageId } : {}),\n ...(typeof eventData.recipient === \"string\" ? { recipient: eventData.recipient } : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n raw: payload,\n }),\n ];\n}\n\n/**\n * Verify a Mailgun webhook signature using HMAC-SHA256 (Web Crypto).\n * signingKey is the Mailgun webhook signing key.\n */\nexport async function verifySignature(\n timestamp: string,\n token: string,\n signature: string,\n signingKey: string,\n): Promise<boolean> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(signingKey),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n\n const data = new TextEncoder().encode(timestamp + token);\n const expected = await crypto.subtle.sign(\"HMAC\", key, data);\n const expectedBytes = new Uint8Array(expected);\n const providedBytes = decodeHexBytes(signature);\n\n if (providedBytes === null) {\n return false;\n }\n\n return timingSafeEqual(expectedBytes, providedBytes);\n}\n\n/**\n * Verify a Mailgun webhook payload using the nested `signature` object.\n * Returns false when the payload shape is invalid.\n */\nexport async function verifyPayload(payload: unknown, signingKey: string): Promise<boolean> {\n if (typeof payload !== \"object\" || payload === null) {\n return false;\n }\n\n const signatureField = (payload as Record<string, unknown>).signature;\n if (typeof signatureField !== \"object\" || signatureField === null) {\n return false;\n }\n\n const signature = signatureField as Record<string, unknown>;\n if (\n typeof signature.timestamp !== \"string\" ||\n typeof signature.token !== \"string\" ||\n typeof signature.signature !== \"string\"\n ) {\n return false;\n }\n\n return verifySignature(signature.timestamp, signature.token, signature.signature, signingKey);\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "8IAIA,DAAM,HAAwD,CAC5D,SAAU,UACV,UAAW,YACX,SAAU,UACV,WAAY,aACZ,OAAQ,SACR,QAAS,UACT,OAAQ,UACR,aAAc,SAChB,EAGA,SAAS,CAAc,CAAC,EAAwD,CAC9E,IAAM,EAAQ,OAAO,EAAU,QAAU,SAAW,EAAU,MAAQ,GACtE,GAAI,IAAU,SACZ,OAAO,EAAU,WAAa,YAAc,WAAa,UAE3D,OAAO,EAAa,EAAO,CAAiB,EAG9C,SAAS,CAAuB,CAAC,EAAkE,CACjG,GA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MAAO,GAGT,IAAM,EAAkB,EAAoC,UAC5D,GAAI,OAAO,IAAmB,UAAY,IAAmB,KAC3D,MAAO,GAGT,IAAM,EAAY,EAClB,GACE,OAAO,EAAU,YAAc,UAC/B,OAAO,EAAU,QAAU,UAC3B,OAAO,EAAU,YAAc,SAE/B,MAAO,GAGT,OAAO,EAAgB,EAAU,UAAW,EAAU,MAAO,EAAU,UAAW,CAAU",
|
|
8
|
+
"debugId": "7FB21CD9E29B4FE264756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{d as u,e as q,g as x}from"../chunk-q8k3m6qe.js";import"../chunk-rszb1n1d.js";var C={Delivery:"delivered",Bounce:"bounced",SpamComplaint:"complained",Open:"opened",Click:"clicked",SubscriptionChange:"unknown",Inbound:"unknown"};function F(g){if(typeof g!=="object"||g===null)return[];let f=g,B=typeof f.RecordType==="string"?f.RecordType:"";return[x({provider:"postmark",type:u(B,C),...typeof f.MessageID==="string"?{messageId:f.MessageID}:{},...typeof f.Recipient==="string"?{recipient:f.Recipient}:typeof f.Email==="string"?{recipient:f.Email}:{},...q(f.DeliveredAt??f.BouncedAt??f.ReceivedAt??f.ChangedAt)!==void 0?{timestamp:q(f.DeliveredAt??f.BouncedAt??f.ReceivedAt??f.ChangedAt)}:{},raw:g})]}export{F as parse};
|
|
2
|
+
|
|
3
|
+
//# debugId=7CD05BB54D484C3864756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/webhooks/postmark.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { EmailEvent } from \"./types.js\";\nimport { emailEvent, mapEventType, parseTimestamp } from \"./types.js\";\n\nconst POSTMARK_EVENT_MAP: Record<string, EmailEvent[\"type\"]> = {\n Delivery: \"delivered\",\n Bounce: \"bounced\",\n SpamComplaint: \"complained\",\n Open: \"opened\",\n Click: \"clicked\",\n SubscriptionChange: \"unknown\",\n Inbound: \"unknown\",\n};\n\n/** Parse a Postmark webhook payload into normalized {@link EmailEvent} records. */\nexport function parse(payload: unknown): EmailEvent[] {\n if (typeof payload !== \"object\" || payload === null) {\n return [];\n }\n\n const record = payload as Record<string, unknown>;\n const recordType = typeof record.RecordType === \"string\" ? record.RecordType : \"\";\n\n return [\n emailEvent({\n provider: \"postmark\",\n type: mapEventType(recordType, POSTMARK_EVENT_MAP),\n ...(typeof record.MessageID === \"string\" ? { messageId: record.MessageID } : {}),\n ...(typeof record.Recipient === \"string\"\n ? { recipient: record.Recipient }\n : typeof record.Email === \"string\"\n ? { recipient: record.Email }\n : {}),\n ...(parseTimestamp(\n record.DeliveredAt ?? record.BouncedAt ?? record.ReceivedAt ?? record.ChangedAt,\n ) !== undefined\n ? {\n timestamp: parseTimestamp(\n record.DeliveredAt ?? record.BouncedAt ?? record.ReceivedAt ?? record.ChangedAt,\n ),\n }\n : {}),\n raw: payload,\n }),\n ];\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "yFAGA,DAAM,EAAyD,CAC7D,SAAU,YACV,OAAQ,UACR,cAAe,aACf,KAAM,SACN,MAAO,UACP,mBAAoB,UACpB,QAAS,SACX,EAGO,SAAS,CAAK,CAAC,EAAgC,CACpD,GAAI,OAAO,IAAY,UAAY,IAAY,KAC7C,MAAO,CAAC,EAGV,IAAM,EAAS,EACT,EAAa,OAAO,EAAO,aAAe,SAAW,EAAO,WAAa,GAE/E,MAAO,CACL,EAAW,CACT,SAAU,WACV,KAAM,EAAa,EAAY,CAAkB,KAC7C,OAAO,EAAO,YAAc,SAAW,CAAE,UAAW,EAAO,SAAU,EAAI,CAAC,KAC1E,OAAO,EAAO,YAAc,SAC5B,CAAE,UAAW,EAAO,SAAU,EAC9B,OAAO,EAAO,QAAU,SACtB,CAAE,UAAW,EAAO,KAAM,EAC1B,CAAC,KACH,EACF,EAAO,aAAe,EAAO,WAAa,EAAO,YAAc,EAAO,SACxE,IAAM,OACF,CACE,UAAW,EACT,EAAO,aAAe,EAAO,WAAa,EAAO,YAAc,EAAO,SACxE,CACF,EACA,CAAC,EACL,IAAK,CACP,CAAC,CACH",
|
|
8
|
+
"debugId": "7CD05BB54D484C3864756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as $,b as A}from"../chunk-pqp843mh.js";import{d as X,e as Y,g as Z}from"../chunk-q8k3m6qe.js";import"../chunk-rszb1n1d.js";var j={"email.sent":"unknown","email.scheduled":"unknown","email.delivered":"delivered","email.delivery_delayed":"deferred","email.bounced":"bounced","email.failed":"bounced","email.complained":"complained","email.opened":"opened","email.clicked":"clicked","email.received":"unknown","email.suppressed":"unknown"};function k(G){let F=G.startsWith("whsec_")?G.slice(6):G,K=atob(F),J=new Uint8Array(K.length);for(let z=0;z<K.length;z++)J[z]=K.charCodeAt(z);return J.buffer}function H(G){if(typeof G!=="object"||G===null)return[];let F=G,K=typeof F.type==="string"?F.type:"",J=typeof F.data==="object"&&F.data!==null?F.data:{},z=J.to,L=Array.isArray(z)?typeof z[0]==="string"?z[0]:void 0:typeof z==="string"?z:void 0,O=Y(F.created_at??J.created_at);return[Z({provider:"resend",type:X(K,j),...typeof J.email_id==="string"?{messageId:J.email_id}:{},...L!==void 0?{recipient:L}:{},...O!==void 0?{timestamp:O}:{},raw:G})]}async function I(G,F,K){let J=F["svix-id"],z=F["svix-timestamp"],L=F["svix-signature"];if(!J||!z||!L)return!1;let O=`${J}.${z}.${G}`,D=await crypto.subtle.importKey("raw",k(K),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),M=await crypto.subtle.sign("HMAC",D,new TextEncoder().encode(O)),P=new Uint8Array(M);for(let W of L.split(" ")){let Q=W.split(",",2)[1];if(Q===void 0)continue;let U=A(Q);if(U===null)continue;if($(P,U))return!0}return!1}export{I as verifySignature,H as parse};
|
|
2
|
+
|
|
3
|
+
//# debugId=2EA62D07463E258664756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/webhooks/resend.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { decodeBase64Bytes, timingSafeEqual } from \"./timing-safe-equal.js\";\nimport type { EmailEvent } from \"./types.js\";\nimport { emailEvent, mapEventType, parseTimestamp } from \"./types.js\";\n\nconst RESEND_EVENT_MAP: Record<string, EmailEvent[\"type\"]> = {\n \"email.sent\": \"unknown\",\n \"email.scheduled\": \"unknown\",\n \"email.delivered\": \"delivered\",\n \"email.delivery_delayed\": \"deferred\",\n \"email.bounced\": \"bounced\",\n \"email.failed\": \"bounced\",\n \"email.complained\": \"complained\",\n \"email.opened\": \"opened\",\n \"email.clicked\": \"clicked\",\n \"email.received\": \"unknown\",\n \"email.suppressed\": \"unknown\",\n};\n\n/** Decode a Svix signing secret (`whsec_…`) to raw key bytes. */\nfunction decodeSvixSecret(secret: string): ArrayBuffer {\n const encoded = secret.startsWith(\"whsec_\") ? secret.slice(6) : secret;\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes.buffer;\n}\n\n/** Parse a Resend webhook payload into normalized {@link EmailEvent} records. */\nexport function parse(payload: unknown): EmailEvent[] {\n if (typeof payload !== \"object\" || payload === null) {\n return [];\n }\n\n const record = payload as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n const data =\n typeof record.data === \"object\" && record.data !== null\n ? (record.data as Record<string, unknown>)\n : {};\n\n const to = data.to;\n const recipient = Array.isArray(to)\n ? typeof to[0] === \"string\"\n ? to[0]\n : undefined\n : typeof to === \"string\"\n ? to\n : undefined;\n\n const timestamp = parseTimestamp(record.created_at ?? data.created_at);\n\n return [\n emailEvent({\n provider: \"resend\",\n type: mapEventType(type, RESEND_EVENT_MAP),\n ...(typeof data.email_id === \"string\" ? { messageId: data.email_id } : {}),\n ...(recipient !== undefined ? { recipient } : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n raw: payload,\n }),\n ];\n}\n\n/**\n * Verify a Resend webhook signature (Svix-style) using Web Crypto.\n * Returns false when verification cannot be performed or the signature is invalid.\n */\nexport async function verifySignature(\n payload: string,\n headers: { \"svix-id\"?: string; \"svix-timestamp\"?: string; \"svix-signature\"?: string },\n secret: string,\n): Promise<boolean> {\n const msgId = headers[\"svix-id\"];\n const timestamp = headers[\"svix-timestamp\"];\n const signatureHeader = headers[\"svix-signature\"];\n\n if (!msgId || !timestamp || !signatureHeader) {\n return false;\n }\n\n const signedContent = `${msgId}.${timestamp}.${payload}`;\n const key = await crypto.subtle.importKey(\n \"raw\",\n decodeSvixSecret(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n\n const expected = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(signedContent));\n const expectedBytes = new Uint8Array(expected);\n\n for (const part of signatureHeader.split(\" \")) {\n const versioned = part.split(\",\", 2);\n const sig = versioned[1];\n if (sig === undefined) {\n continue;\n }\n const providedBytes = decodeBase64Bytes(sig);\n if (providedBytes === null) {\n continue;\n }\n if (timingSafeEqual(expectedBytes, providedBytes)) {\n return true;\n }\n }\n\n return false;\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "8IAIA,DAAM,HAAuD,CAC3D,aAAc,UACd,kBAAmB,UACnB,kBAAmB,YACnB,yBAA0B,WAC1B,gBAAiB,UACjB,eAAgB,UAChB,mBAAoB,aACpB,eAAgB,SAChB,gBAAiB,UACjB,iBAAkB,UAClB,mBAAoB,SACtB,EAGA,SAAS,CAAgB,CAAC,EAA6B,CACrD,IAAM,EAAU,EAAO,WAAW,QAAQ,EAAI,EAAO,MAAM,CAAC,EAAI,EAC1D,EAAS,KAAK,CAAO,EACrB,EAAQ,IAAI,WAAW,EAAO,MAAM,EAC1C,QAAS,EAAI,EAAG,EAAI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tB,GAAI,IAAQ,OACV,SAEF,IAAM,EAAgB,EAAkB,CAAG,EAC3C,GAAI,IAAkB,KACpB,SAEF,GAAI,EAAgB,EAAe,CAAa,EAC9C,MAAO,GAIX,MAAO",
|
|
8
|
+
"debugId": "2EA62D07463E258664756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{d as w,e as x,f as B,g as C}from"../chunk-q8k3m6qe.js";import"../chunk-rszb1n1d.js";var F={processed:"unknown",delivered:"delivered",deferred:"deferred",bounce:"bounced",dropped:"bounced",spamreport:"complained",unsubscribe:"complained",group_unsubscribe:"complained",group_resubscribe:"unknown",open:"opened",click:"clicked"};function H(q){let g=typeof q.event==="string"?q.event:"";if(g==="bounce"&&q.type==="blocked")return"deferred";return w(g,F)}function K(q){return B(q).flatMap((g)=>{if(typeof g!=="object"||g===null)return[];let f=g,u=x(f.timestamp);return[C({provider:"sendgrid",type:H(f),...typeof f.sg_message_id==="string"?{messageId:f.sg_message_id}:typeof f["smtp-id"]==="string"?{messageId:f["smtp-id"]}:{},...typeof f.email==="string"?{recipient:f.email}:{},...u!==void 0?{timestamp:u}:{},raw:g})]})}export{K as parse};
|
|
2
|
+
|
|
3
|
+
//# debugId=D4C7DDEE719D449764756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/webhooks/sendgrid.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { EmailEvent } from \"./types.js\";\nimport { asArray, emailEvent, mapEventType, parseTimestamp } from \"./types.js\";\n\nconst SENDGRID_EVENT_MAP: Record<string, EmailEvent[\"type\"]> = {\n processed: \"unknown\",\n delivered: \"delivered\",\n deferred: \"deferred\",\n bounce: \"bounced\",\n dropped: \"bounced\",\n spamreport: \"complained\",\n unsubscribe: \"complained\",\n group_unsubscribe: \"complained\",\n group_resubscribe: \"unknown\",\n open: \"opened\",\n click: \"clicked\",\n};\n\n/** Map a SendGrid event name (and bounce subtype) to a normalized type. */\nfunction mapSendGridType(record: Record<string, unknown>): EmailEvent[\"type\"] {\n const event = typeof record.event === \"string\" ? record.event : \"\";\n if (event === \"bounce\" && record.type === \"blocked\") {\n return \"deferred\";\n }\n return mapEventType(event, SENDGRID_EVENT_MAP);\n}\n\n/** Parse a SendGrid Event Webhook payload into normalized {@link EmailEvent} records. */\nexport function parse(payload: unknown): EmailEvent[] {\n return asArray(payload).flatMap((item) => {\n if (typeof item !== \"object\" || item === null) {\n return [];\n }\n\n const record = item as Record<string, unknown>;\n const timestamp = parseTimestamp(record.timestamp);\n\n return [\n emailEvent({\n provider: \"sendgrid\",\n type: mapSendGridType(record),\n ...(typeof record.sg_message_id === \"string\"\n ? { messageId: record.sg_message_id }\n : typeof record[\"smtp-id\"] === \"string\"\n ? { messageId: record[\"smtp-id\"] }\n : {}),\n ...(typeof record.email === \"string\" ? { recipient: record.email } : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n raw: item,\n }),\n ];\n });\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "gGAGA,DAAM,EAAyD,CAC7D,UAAW,UACX,UAAW,YACX,SAAU,WACV,OAAQ,UACR,QAAS,UACT,WAAY,aACZ,YAAa,aACb,kBAAmB,aACnB,kBAAmB,UACnB,KAAM,SACN,MAAO,SACT,EAGA,SAAS,CAAe,CAAC,EAAqD,CAC5E,IAAM,EAAQ,OAAO,EAAO,QAAU,SAAW,EAAO,MAAQ,GAChE,GAAI,IAAU,UAAY,EAAO,OAAS,UACxC,MAAO,WAET,OAAO,EAAa,EAAO,CAAkB,EAIxC,SAAS,CAAK,CAAC,EAAgC,CACpD,OAAO,EAAQ,CAAO,EAAE,QAAQ,CAAC,IAAS,CACxC,GAAI,OAAO,IAAS,UAAY,IAAS,KACvC,MAAO,CAAC,EAGV,IAAM,EAAS,EACT,EAAY,EAAe,EAAO,SAAS,EAEjD,MAAO,CACL,EAAW,CACT,SAAU,WACV,KAAM,EAAgB,CAAM,KACxB,OAAO,EAAO,gBAAkB,SAChC,CAAE,UAAW,EAAO,aAAc,EAClC,OAAO,EAAO,aAAe,SAC3B,CAAE,UAAW,EAAO,UAAW,EAC/B,CAAC,KACH,OAAO,EAAO,QAAU,SAAW,CAAE,UAAW,EAAO,KAAM,EAAI,CAAC,KAClE,IAAc,OAAY,CAAE,WAAU,EAAI,CAAC,EAC/C,IAAK,CACP,CAAC,CACH,EACD",
|
|
8
|
+
"debugId": "D4C7DDEE719D449764756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{d as Q,e as U,g as X}from"../chunk-q8k3m6qe.js";import"../chunk-rszb1n1d.js";var $={Delivery:"delivered",Bounce:"bounced",Complaint:"complained",Open:"opened",Click:"clicked",DeliveryDelay:"deferred",Send:"unknown",Reject:"bounced","Rendering Failure":"bounced",Subscription:"unknown"};function h(q){if(typeof q.eventType==="string")return q.eventType;if(typeof q.notificationType==="string")return q.notificationType;return""}function j(q){let J=typeof q.delivery==="object"&&q.delivery!==null?q.delivery:void 0;if(J&&Array.isArray(J.recipients)&&typeof J.recipients[0]==="string")return J.recipients[0];let K=typeof q.bounce==="object"&&q.bounce!==null?q.bounce:void 0;if(K&&Array.isArray(K.bouncedRecipients)){let I=K.bouncedRecipients[0];if(typeof I==="object"&&I!==null&&typeof I.emailAddress==="string")return I.emailAddress}let B=typeof q.complaint==="object"&&q.complaint!==null?q.complaint:void 0;if(B&&Array.isArray(B.complainedRecipients)){let I=B.complainedRecipients[0];if(typeof I==="object"&&I!==null&&typeof I.emailAddress==="string")return I.emailAddress}let G=typeof q.mail==="object"&&q.mail!==null?q.mail:void 0;if(Array.isArray(G?.destination)&&typeof G.destination[0]==="string")return G.destination[0];return}function w(q){let J=h(q),K=typeof q.mail==="object"&&q.mail!==null?q.mail:void 0,B=typeof q.bounce==="object"&&q.bounce!==null?q.bounce:void 0,G=typeof q.complaint==="object"&&q.complaint!==null?q.complaint:void 0,I=typeof q.open==="object"&&q.open!==null?q.open:void 0,Y=typeof q.click==="object"&&q.click!==null?q.click:void 0,Z=typeof q.deliveryDelay==="object"&&q.deliveryDelay!==null?q.deliveryDelay:void 0,L=j(q),O=U(q.timestamp??B?.timestamp??G?.timestamp??I?.timestamp??Y?.timestamp??Z?.timestamp??K?.timestamp);return[X({provider:"ses",type:Q(J,$),...typeof K?.messageId==="string"?{messageId:K.messageId}:{},...L!==void 0?{recipient:L}:{},...O!==void 0?{timestamp:O}:{},raw:q})]}function z(q){if(typeof q!=="object"||q===null)return[];let J=q,K=typeof J.Type==="string"?J.Type:"";if(K==="SubscriptionConfirmation")return[];if(K!=="Notification")return[];let B=J.Message,G;if(typeof B==="string")try{G=JSON.parse(B)}catch{return[{provider:"ses",type:"unknown",raw:q}]}else if(typeof B==="object"&&B!==null)G=B;else return[];if(typeof G!=="object"||G===null)return[{provider:"ses",type:"unknown",raw:q}];return w(G)}export{z as parse};
|
|
2
|
+
|
|
3
|
+
//# debugId=C5FC4A2C6082819B64756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/webhooks/ses.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { EmailEvent } from \"./types.js\";\nimport { emailEvent, mapEventType, parseTimestamp } from \"./types.js\";\n\nconst SES_EVENT_MAP: Record<string, EmailEvent[\"type\"]> = {\n Delivery: \"delivered\",\n Bounce: \"bounced\",\n Complaint: \"complained\",\n Open: \"opened\",\n Click: \"clicked\",\n DeliveryDelay: \"deferred\",\n Send: \"unknown\",\n Reject: \"bounced\",\n \"Rendering Failure\": \"bounced\",\n Subscription: \"unknown\",\n};\n\nfunction resolveSesEventType(record: Record<string, unknown>): string {\n if (typeof record.eventType === \"string\") {\n return record.eventType;\n }\n if (typeof record.notificationType === \"string\") {\n return record.notificationType;\n }\n return \"\";\n}\n\nfunction extractSesRecipient(record: Record<string, unknown>): string | undefined {\n const delivery =\n typeof record.delivery === \"object\" && record.delivery !== null\n ? (record.delivery as Record<string, unknown>)\n : undefined;\n if (\n delivery &&\n Array.isArray(delivery.recipients) &&\n typeof delivery.recipients[0] === \"string\"\n ) {\n return delivery.recipients[0];\n }\n\n const bounce =\n typeof record.bounce === \"object\" && record.bounce !== null\n ? (record.bounce as Record<string, unknown>)\n : undefined;\n if (bounce && Array.isArray(bounce.bouncedRecipients)) {\n const first = bounce.bouncedRecipients[0];\n if (\n typeof first === \"object\" &&\n first !== null &&\n typeof (first as Record<string, unknown>).emailAddress === \"string\"\n ) {\n return (first as Record<string, unknown>).emailAddress as string;\n }\n }\n\n const complaint =\n typeof record.complaint === \"object\" && record.complaint !== null\n ? (record.complaint as Record<string, unknown>)\n : undefined;\n if (complaint && Array.isArray(complaint.complainedRecipients)) {\n const first = complaint.complainedRecipients[0];\n if (\n typeof first === \"object\" &&\n first !== null &&\n typeof (first as Record<string, unknown>).emailAddress === \"string\"\n ) {\n return (first as Record<string, unknown>).emailAddress as string;\n }\n }\n\n const mail =\n typeof record.mail === \"object\" && record.mail !== null\n ? (record.mail as Record<string, unknown>)\n : undefined;\n if (Array.isArray(mail?.destination) && typeof mail.destination[0] === \"string\") {\n return mail.destination[0];\n }\n\n return undefined;\n}\n\nfunction parseSesEvent(record: Record<string, unknown>): EmailEvent[] {\n const eventType = resolveSesEventType(record);\n const mail =\n typeof record.mail === \"object\" && record.mail !== null\n ? (record.mail as Record<string, unknown>)\n : undefined;\n\n const bounce =\n typeof record.bounce === \"object\" && record.bounce !== null\n ? (record.bounce as Record<string, unknown>)\n : undefined;\n const complaint =\n typeof record.complaint === \"object\" && record.complaint !== null\n ? (record.complaint as Record<string, unknown>)\n : undefined;\n const open =\n typeof record.open === \"object\" && record.open !== null\n ? (record.open as Record<string, unknown>)\n : undefined;\n const click =\n typeof record.click === \"object\" && record.click !== null\n ? (record.click as Record<string, unknown>)\n : undefined;\n const deliveryDelay =\n typeof record.deliveryDelay === \"object\" && record.deliveryDelay !== null\n ? (record.deliveryDelay as Record<string, unknown>)\n : undefined;\n\n const recipient = extractSesRecipient(record);\n const timestamp = parseTimestamp(\n record.timestamp ??\n bounce?.timestamp ??\n complaint?.timestamp ??\n open?.timestamp ??\n click?.timestamp ??\n deliveryDelay?.timestamp ??\n mail?.timestamp,\n );\n\n return [\n emailEvent({\n provider: \"ses\",\n type: mapEventType(eventType, SES_EVENT_MAP),\n ...(typeof mail?.messageId === \"string\" ? { messageId: mail.messageId } : {}),\n ...(recipient !== undefined ? { recipient } : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n raw: record,\n }),\n ];\n}\n\n/**\n * Parse an AWS SES webhook payload (SNS envelope) into normalized {@link EmailEvent} records.\n * Handles SubscriptionConfirmation (returns `[]`) and double-encoded Notification messages.\n */\nexport function parse(payload: unknown): EmailEvent[] {\n if (typeof payload !== \"object\" || payload === null) {\n return [];\n }\n\n const envelope = payload as Record<string, unknown>;\n const snsType = typeof envelope.Type === \"string\" ? envelope.Type : \"\";\n\n if (snsType === \"SubscriptionConfirmation\") {\n return [];\n }\n\n if (snsType !== \"Notification\") {\n return [];\n }\n\n const messageField = envelope.Message;\n let inner: unknown;\n\n if (typeof messageField === \"string\") {\n try {\n inner = JSON.parse(messageField);\n } catch {\n return [\n {\n provider: \"ses\",\n type: \"unknown\" as const,\n raw: payload,\n },\n ];\n }\n } else if (typeof messageField === \"object\" && messageField !== null) {\n inner = messageField;\n } else {\n return [];\n }\n\n if (typeof inner !== \"object\" || inner === null) {\n return [\n {\n provider: \"ses\",\n type: \"unknown\" as const,\n raw: payload,\n },\n ];\n }\n\n return parseSesEvent(inner as Record<string, unknown>);\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "yFAGA,DAAM,EAAoD,CACxD,SAAU,YACV,OAAQ,UACR,UAAW,aACX,KAAM,SACN,MAAO,UACP,cAAe,WACf,KAAM,UACN,OAAQ,UACR,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