@aglyn/shared-util-email 1.0.0-beta.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +104 -0
  3. package/package.json +37 -0
  4. package/src/index.d.ts +37 -0
  5. package/src/index.js +46 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/email-delivery-events.d.ts +198 -0
  8. package/src/lib/email-delivery-events.js +310 -0
  9. package/src/lib/email-delivery-events.js.map +1 -0
  10. package/src/lib/email-health.d.ts +154 -0
  11. package/src/lib/email-health.js +264 -0
  12. package/src/lib/email-health.js.map +1 -0
  13. package/src/lib/email-media-src.d.ts +33 -0
  14. package/src/lib/email-media-src.js +113 -0
  15. package/src/lib/email-media-src.js.map +1 -0
  16. package/src/lib/email-merge.d.ts +31 -0
  17. package/src/lib/email-merge.js +36 -0
  18. package/src/lib/email-merge.js.map +1 -0
  19. package/src/lib/email-render.d.ts +114 -0
  20. package/src/lib/email-render.js +293 -0
  21. package/src/lib/email-render.js.map +1 -0
  22. package/src/lib/email-revenue-window.d.ts +55 -0
  23. package/src/lib/email-revenue-window.js +58 -0
  24. package/src/lib/email-revenue-window.js.map +1 -0
  25. package/src/lib/host-email-render.d.ts +99 -0
  26. package/src/lib/host-email-render.js +126 -0
  27. package/src/lib/host-email-render.js.map +1 -0
  28. package/src/lib/host-sender.d.ts +86 -0
  29. package/src/lib/host-sender.js +131 -0
  30. package/src/lib/host-sender.js.map +1 -0
  31. package/src/lib/marketing-send.d.ts +466 -0
  32. package/src/lib/marketing-send.js +459 -0
  33. package/src/lib/marketing-send.js.map +1 -0
  34. package/src/lib/platform-sending-domain.d.ts +362 -0
  35. package/src/lib/platform-sending-domain.js +697 -0
  36. package/src/lib/platform-sending-domain.js.map +1 -0
  37. package/src/lib/received-email.d.ts +86 -0
  38. package/src/lib/received-email.js +124 -0
  39. package/src/lib/received-email.js.map +1 -0
  40. package/src/lib/send-ceilings.d.ts +394 -0
  41. package/src/lib/send-ceilings.js +341 -0
  42. package/src/lib/send-ceilings.js.map +1 -0
  43. package/src/lib/send-email.d.ts +385 -0
  44. package/src/lib/send-email.js +586 -0
  45. package/src/lib/send-email.js.map +1 -0
  46. package/src/lib/send-rate.d.ts +298 -0
  47. package/src/lib/send-rate.js +310 -0
  48. package/src/lib/send-rate.js.map +1 -0
  49. package/src/lib/sender-reputation.d.ts +357 -0
  50. package/src/lib/sender-reputation.js +392 -0
  51. package/src/lib/sender-reputation.js.map +1 -0
  52. package/src/lib/sending-domain.d.ts +744 -0
  53. package/src/lib/sending-domain.js +798 -0
  54. package/src/lib/sending-domain.js.map +1 -0
  55. package/src/lib/sending-mailbox.d.ts +132 -0
  56. package/src/lib/sending-mailbox.js +192 -0
  57. package/src/lib/sending-mailbox.js.map +1 -0
  58. package/src/lib/stored-email-nodes.d.ts +38 -0
  59. package/src/lib/stored-email-nodes.js +78 -0
  60. package/src/lib/stored-email-nodes.js.map +1 -0
  61. package/src/lib/svix-signature.d.ts +38 -0
  62. package/src/lib/svix-signature.js +55 -0
  63. package/src/lib/svix-signature.js.map +1 -0
  64. package/src/lib/system-email-catalog.d.ts +170 -0
  65. package/src/lib/system-email-catalog.js +828 -0
  66. package/src/lib/system-email-catalog.js.map +1 -0
  67. package/src/lib/tenant-email-catalog.d.ts +78 -0
  68. package/src/lib/tenant-email-catalog.js +452 -0
  69. package/src/lib/tenant-email-catalog.js.map +1 -0
  70. package/src/lib/text-email-html.d.ts +32 -0
  71. package/src/lib/text-email-html.js +119 -0
  72. package/src/lib/text-email-html.js.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/send-email.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The Resend send endpoint. Every outbound application email in Aglyn goes\n * through here — invites, receipts, usage summaries, campaigns, staff alerts.\n *\n * Auth email (verification, password reset) is Firebase's job and does NOT\n * come through this module.\n */\nimport {\n type EmailSendPriority,\n emailSendRateWindowStartMs,\n getEmailSendGovernor,\n isRefusablePriority,\n resolveSendPriority,\n} from './send-rate'\nimport { renderTextEmailHtml } from './text-email-html'\nimport {\n sendingIdentityRefusal,\n pooledMarketingRefusal,\n type SendingIdentityAudience,\n type SendingIdentityVerdict,\n} from './sending-domain'\nimport {\n appendUnsubscribeHtml,\n appendUnsubscribeText,\n getMarketingSendGate,\n isMarketingMessage,\n unsubscribeHeaders,\n type MarketingSendContext,\n} from './marketing-send'\n\nexport const RESEND_SEND_ENDPOINT = 'https://api.resend.com/emails'\n\n/** A Resend delivery tag, used for webhook attribution (AGL-268). */\nexport interface EmailTag {\n name: string\n value: string\n}\n\nexport interface SendEmailOptions {\n /** One or more recipient addresses. */\n to: string | string[]\n subject: string\n /** Plain-text body. Supply at least one of `text` or `html`. */\n text?: string\n /**\n * HTML body. Supply at least one of `text` or `html`.\n *\n * Omitted, one is synthesized from `text` so the message always carries an\n * HTML part — a text-only message has no anchors, so its links are inert in\n * the inbox and Resend's click tracking has nothing to rewrite. See\n * `text-email-html.ts`.\n */\n html?: string\n /** Extra MIME headers, e.g. `List-Unsubscribe`. */\n headers?: Record<string, string>\n /** Delivery tags for the opens/clicks webhook. */\n tags?: EmailTag[]\n replyTo?: string | string[]\n /*\n * THERE IS NO `from`.\n *\n * There was: a raw override of the configured sender, subordinate to a\n * resolved identity but winning over everything else, verified against\n * nothing. Every address this function can send from now comes from one of\n * exactly two places — the deployment's own `USAGE_EMAIL_FROM`, or a\n * {@link SendingIdentityVerdict} the server resolved from a document — and\n * neither is reachable from a request body.\n *\n * Deleting it rather than guarding it is what makes that a property instead\n * of a habit. A guard would have to be written correctly at each of the\n * ninety-odd call sites, or once here and then trusted; an option that does\n * not exist cannot be passed by the next sender, and `resolveSendingIdentity`\n * becomes the whole of the answer to \"as whom does this leave\".\n *\n * The resolution below reads no `from` from `options` either, so this is not\n * only a compile-time close. Marketplace plugin bundles reach `sendEmail` as\n * JavaScript and are typechecked against nothing.\n */\n /**\n * White-label display name for the sender (White-Label Phase 1). Replaces\n * only the display name in front of the verified address — the address\n * itself is never taken from the caller, so this cannot forge a different\n * sender. Callers pass `resolveBrandingProfile(org).fromName` here so an\n * agency's mail reads as their brand instead of \"Aglyn\".\n */\n fromName?: string\n /**\n * The server-resolved sending identity for this message, from\n * `resolveSendingIdentity`.\n *\n * Supplied, it decides the address and it may refuse the send outright —\n * `fromName` is subordinate to it, because a verdict is the answer to \"may\n * this leave, and as whom\" and a display name is not. Omitted, every\n * existing caller keeps the behavior it had: the configured platform\n * identity with an optional display name.\n *\n * Callers resolve it from the ORG DOCUMENT, never from request input. An\n * address assembled from a request body is a `From:` override wearing a new\n * name, and the invariant `applyFromName` exists to hold is that the\n * address cannot move off a verified identity.\n */\n sendingIdentity?: SendingIdentityVerdict | null\n /**\n * Whose mail this is — see {@link SendingIdentityAudience}.\n *\n * `tenant` says the message belongs to a SITE, and it makes the platform\n * sender unreachable: a tenant message with no resolved identity is refused\n * rather than sent from `aglyn.com`. Pair it with `sendingIdentity` from\n * `hostSendingIdentity(hostId)` and the ordinary path is unchanged; the flag\n * is what decides the behavior when that resolution is missing or refuses.\n *\n * Omitted, a send is platform mail and keeps the configured sender, because\n * that is what the console's own senders are. `email-audience-coverage.spec`\n * sweeps the tenant-owned trees so the omission cannot be an accident there.\n */\n audience?: SendingIdentityAudience\n /**\n * Short label for logs, e.g. `'invite'` or `'usage-summary'`. Makes a\n * failure in the runtime logs traceable to the feature that caused it.\n *\n * Since AGL-2407 it is also stamped as a Resend `context` TAG on every\n * send — see `contextTag` below.\n */\n context?: string\n /**\n * What the platform send-rate governor is allowed to do to this message\n * (AGL-2409). Omitted, it is derived from `context`: `'campaign'` is a\n * campaign and everything else is transactional, so no existing caller\n * changes and the default is the one that can never be refused.\n *\n * Set it to `'bulk'` ONLY from a resumable sweep — a cron that leaves its\n * subject unstamped and picks it up on the next run. A refusal for a bulk\n * send means \"not this hour\", and a caller that cannot come back would turn\n * that into a message nobody ever gets.\n */\n priority?: EmailSendPriority\n /**\n * Declares this message as MARKETING mail for one site's audience — see\n * `marketing-send.ts` for what that means and why it is one seam.\n *\n * Set it and the message gains, in one place, the three things marketing\n * mail owes: the RFC 8058 unsubscribe header pair plus a visible opt-out\n * link, a check against both suppression lists, and a ceiling on how much\n * one person receives from one site.\n *\n * ONE RECIPIENT. An unsubscribe link is an HMAC over the address it belongs\n * to, and a suppression verdict is about one person — so a marketing send\n * addressed to a list would carry the wrong link for everybody after the\n * first, and would ask the gate about one of them. Callers fan out.\n */\n marketing?: MarketingSendContext\n}\n\n/**\n * The `context` tag, attached to every send (AGL-2407).\n *\n * ## Why this is here and not at 37 call sites\n *\n * Until now `tags` were set by exactly one sender, `campaign-send.ts`, which\n * stamps `hostId` and `campaignId` for the opens/clicks webhook. Everything\n * else went out with NO tags at all, so a bounce on an invite, a password\n * reset, a receipt or a usage summary reached the webhook carrying nothing to\n * identify it, and was dropped.\n *\n * The obvious fix — thread an identifier through every call site — asks 37\n * places to remember, which is the shape that produces the 38th that does\n * not. But `context` is ALREADY threaded through 35 of the 37 for logging,\n * and it is exactly the right value: it names the sender. So the tag is\n * derived here, once, and no caller changes.\n *\n * Resend tag values are restricted to ASCII letters, digits, `_` and `-`;\n * anything else is rejected and would fail the whole send. Every `context` in\n * the tree is already a plain slug, but this is mail delivery — a value that\n * makes the send fail is far worse than a value that is sanitised — so the\n * label is normalised rather than trusted, and a context that sanitises to\n * nothing yields no tag rather than an invalid one.\n */\nexport function contextTag(context: string | undefined): EmailTag[] {\n const value = String(context ?? '')\n .trim()\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 64)\n return value ? [{ name: 'context', value }] : []\n}\n\n/**\n * Why a send did not happen. `unconfigured` and `no-recipient` mean nothing\n * was attempted; `rejected` and `network` mean Resend was called and failed;\n * `rate-limited` is either, and says so in `status`.\n *\n * `rate-limited` (AGL-2409) and `frequency-capped` are the two a caller may\n * reasonably retry unchanged — see {@link isDeferrableSendResult}, which is\n * where that distinction is made once rather than at each sweep.\n */\nexport type SendEmailFailureReason =\n | 'unconfigured'\n | 'no-recipient'\n /**\n * Resend answered and would not take this message.\n *\n * Per-message and terminal: a malformed payload, an address the provider\n * will not accept, a tag it rejected. A caller that retries it unchanged\n * gets the same answer, so a batch settles the recipient rather than\n * holding a slot open for them.\n *\n * A 429 is deliberately NOT this. See `rate-limited`.\n */\n | 'rejected'\n | 'network'\n /**\n * A refusal that is about the RATE, not about this message — so the message\n * is intact and a later attempt sends it.\n *\n * Two sources, which is why it is one value. The platform hourly governor\n * refuses before the network and nothing is attempted (AGL-2409). Resend\n * answers `429` on the wire when requests arrive faster than it accepts\n * them, and `status` is 429 in that case.\n *\n * The provider arm reports here rather than as `rejected` because of what\n * the two mean to a batch. A `rejected` recipient is settled and never\n * addressed again, which is right for an address the provider will not take\n * and wrong for every recipient a 429 touches: nothing about them was\n * refused, the request was simply too soon. Classified as `rejected` a\n * single rate-limited burst silently deletes the rest of a campaign's\n * audience while the campaign reports itself complete — and the `sent`\n * figure stays honest throughout, so no rate on the report can show it.\n *\n * The provider's quota errors — `daily_quota_exceeded`,\n * `monthly_quota_exceeded` — are also 429 and also land here. That is the\n * right answer for the same reason: none of them is a statement about the\n * recipient, and all of them clear with time.\n */\n | 'rate-limited'\n /**\n * The org selected a custom sending domain and that domain is not verified.\n *\n * Distinct from `unconfigured` because the two need opposite responses: an\n * unconfigured deployment is the operator's to fix, while this is a\n * customer's DNS that is not finished, and the customer is the only person\n * who can finish it. `detail` carries the sentence naming the domain.\n *\n * This is the LAST line of defence, not the visible one. A caller that\n * reaches it has already skipped the check its route should have made, and\n * a refusal seen only here is a log line — which is the shape of the\n * `USAGE_EMAIL_FROM` outage. `performCampaignSend` refuses first, with a\n * `409`, so a person finds out.\n */\n | 'unverified-domain'\n /**\n * A MARKETING send whose recipient is on a suppression list — they\n * unsubscribed from this site, hard-bounced, or pressed \"report spam\".\n *\n * Terminal, and the only outcome here a caller must not retry: retrying is\n * the behavior the suppression exists to stop. Distinct from `rejected`\n * because nothing was attempted and nothing failed — this is the control\n * working.\n */\n | 'suppressed'\n /**\n * A MARKETING send refused because this person has already received their\n * ceiling from this site inside the window.\n *\n * Retryable, unlike `suppressed`: the window rolls. A resumable sweep does\n * not need to do anything about it — its next run asks again.\n */\n | 'frequency-capped'\n /**\n * A MARKETING send refused because this site has been mailing this person\n * for longer than the sunset window with nothing to show for it.\n *\n * TERMINAL for a sweep, and it sits with `suppressed` rather than with\n * `frequency-capped` for a reason worth stating: the frequency window\n * clears by the passage of time, so waiting works. A sunset clears when the\n * PERSON engages, which more mail from us cannot cause — so a sweep that\n * treated it as deferrable would re-read the same doomed row on every beat\n * forever. Nothing about the recipient has been reduced; the next message\n * after they open anything goes.\n */\n | 'unengaged'\n\nexport type SendEmailResult =\n | { sent: true; id: string | null }\n | {\n sent: false\n reason: SendEmailFailureReason\n /** HTTP status, when Resend answered. */\n status?: number\n /** Resend's error body or the thrown message, trimmed for logs. */\n detail?: string\n /**\n * `rate-limited` only: the earliest instant a caller may try again —\n * when the platform hourly window rolls, or what the provider's own\n * `retry-after` asked for. A resumable sweep does not need to wait on\n * it; its next scheduled run is the retry.\n */\n retryAtMs?: number\n }\n\n/**\n * The retry instant when the platform send-rate governor deferred this\n * message, or `null` for every other outcome (AGL-2409).\n *\n * A FUNCTION rather than `result.reason === 'rate-limited'` at each call site,\n * because `strictNullChecks` is OFF repo-wide and TypeScript will not narrow a\n * boolean-literal discriminant without it: `if (result.sent) … else\n * result.reason` does not compile, in every consumer, for a reason that has\n * nothing to do with this union. One helper is also one place to change if the\n * shape of a deferral ever moves.\n */\nexport function rateLimitedRetryAtMs(\n result: SendEmailResult | null | undefined,\n): number | null {\n const failure = result as { reason?: string; retryAtMs?: number } | null\n if (!failure || failure.reason !== 'rate-limited') return null\n const retryAtMs = Number(failure.retryAtMs)\n return Number.isFinite(retryAtMs) ? retryAtMs : 0\n}\n\n/**\n * How long to wait when the provider names no interval of its own.\n *\n * One second, because Resend's rate limit is counted per second — so a wait\n * of a whole window is the shortest one that is certain to have cleared it.\n */\nconst PROVIDER_RETRY_FALLBACK_MS = 1_000\n\n/**\n * The longest wait a provider header may ask for.\n *\n * A `retry-after` is read off the network and reaches a scheduler, so it is\n * clamped rather than trusted: a header of `86400` would park a campaign for\n * a day on one response nobody saw. An hour is past every documented window\n * and short enough that a wrong one costs a run rather than a day.\n */\nconst PROVIDER_RETRY_MAX_MS = 3_600_000\n\n/** One header as whole seconds, or null when it is absent or unreadable. */\nfunction headerSeconds(\n headers: { get?: (name: string) => string | null } | null | undefined,\n name: string,\n): number | null {\n const raw = headers?.get?.(name)\n // `Number(null)` and `Number('')` are both 0, which would read as \"retry\n // immediately\" for a header that is not there at all.\n if (raw === null || raw === undefined || String(raw).trim() === '') return null\n const seconds = Number(raw)\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : null\n}\n\n/**\n * When the provider says a refused request may be repeated.\n *\n * Read from the two headers Resend documents beside a 429, both in whole\n * seconds: `retry-after` first because it is the direct answer to this\n * question, then `ratelimit-reset`, which names when the window rolls. A\n * response carrying neither falls back to one window.\n */\nexport function providerRetryAtMs(\n headers: { get?: (name: string) => string | null } | null | undefined,\n nowMs: number = Date.now(),\n): number {\n const seconds =\n headerSeconds(headers, 'retry-after') ??\n headerSeconds(headers, 'ratelimit-reset')\n const waitMs =\n seconds === null\n ? PROVIDER_RETRY_FALLBACK_MS\n : Math.min(seconds * 1_000, PROVIDER_RETRY_MAX_MS)\n return nowMs + waitMs\n}\n\n/**\n * Why a send did not happen, or `null` when it did.\n *\n * The same accessor `rateLimitedRetryAtMs` is, generalized: `strictNullChecks`\n * is OFF repo-wide, so TypeScript will not narrow the union on `result.sent`\n * and reading `result.reason` at a call site does not compile.\n */\nexport function sendFailureReason(\n result: SendEmailResult | null | undefined,\n): SendEmailFailureReason | null {\n const failure = result as {\n sent?: boolean\n reason?: SendEmailFailureReason\n } | null\n if (!failure || failure.sent) return null\n return failure.reason ?? null\n}\n\n/**\n * Whether this outcome is worth coming back for.\n *\n * TRUE only for the two refusals a later attempt can pass: the platform hour\n * rolls, and so does the marketing frequency window. Everything else is\n * either a delivery that happened or a failure a retry repeats — a\n * suppression most of all, since retrying is the exact behavior a suppression\n * exists to stop, and a sunset for the same reason at one remove: it clears\n * when the recipient engages, which no amount of further mail from us brings\n * about.\n *\n * A resumable sweep uses this to decide whether to leave its subject\n * unstamped. Stamping on a deferrable refusal discards a message; NOT\n * stamping on a terminal one re-reads the same doomed row on every beat until\n * it crowds out the work that could succeed. Both are silent, so the\n * distinction lives here instead of at each sweep.\n *\n * A FUNCTION rather than `result.reason === …` at each call site, because\n * `strictNullChecks` is OFF repo-wide and TypeScript will not narrow a\n * boolean-literal discriminant without it — the same reason\n * {@link rateLimitedRetryAtMs} beside it is one.\n */\nexport function isDeferrableSendResult(\n result: SendEmailResult | null | undefined,\n): boolean {\n const reason = sendFailureReason(result)\n return reason === 'rate-limited' || reason === 'frequency-capped'\n}\n\nexport interface EmailConfig {\n apiKey: string | undefined\n from: string | undefined\n}\n\n/**\n * Reads the email environment.\n *\n * Deliberately read per call rather than captured at module load: these run\n * in serverless handlers where the module may be evaluated during a build,\n * long before the runtime env exists.\n */\nexport function getEmailConfig(): EmailConfig {\n return {\n apiKey: process.env.RESEND_API_KEY || undefined,\n from: process.env.USAGE_EMAIL_FROM || undefined,\n }\n}\n\n/**\n * True when both `RESEND_API_KEY` and `USAGE_EMAIL_FROM` are present.\n *\n * Callers that answer an HTTP request (rather than firing best-effort mail)\n * use this to return a 501 with an actionable message instead of pretending\n * to have sent something.\n */\nexport function isEmailConfigured(): boolean {\n const { apiKey, from } = getEmailConfig()\n return Boolean(apiKey && from)\n}\n\n/**\n * Applies a white-label display name to a configured sender while keeping\n * its verified address (White-Label Phase 1). Accepts either a bare address\n * (`noreply@aglyn.com`) or an RFC-5322 `Name <addr>` header and returns\n * `\"<fromName>\" <addr>`. A blank name, or a value with no extractable\n * address, yields the original `from` untouched — the sender identity is\n * never dropped on the floor.\n */\nexport function applyFromName(\n from: string | undefined,\n fromName: string | undefined,\n): string | undefined {\n const name = (fromName ?? '').trim()\n if (!from || !name) return from\n const angle = from.match(/<([^>]+)>/)\n const address = (angle ? angle[1] : from).trim()\n if (!address.includes('@')) return from\n // Quote the display name so commas/specials stay inside one mailbox.\n return `\"${name.replace(/\"/g, '')}\" <${address}>`\n}\n\nfunction normalizeRecipients(to: string | string[]): string[] {\n const list = Array.isArray(to) ? to : [to]\n return list\n .map((address) => String(address ?? '').trim())\n .filter((address) => address.includes('@'))\n}\n\n/** A Resend send payload in the provider's own wire shape. */\nexport interface ResendSendPayload {\n to?: unknown\n from?: unknown\n subject?: unknown\n [field: string]: unknown\n}\n\n/**\n * The one place that POSTs to Resend's send endpoint, and the last thing\n * standing between a payload and the network.\n *\n * A payload carrying no recipient cannot become a message. Resend answers it\n * `422 missing_required_field`, which costs an API call and then shows up in\n * the vendor dashboard as a red line indistinguishable from mail that\n * genuinely failed to deliver — carrying no subject, no recipient and nothing\n * naming the code that produced it. Diagnosing that means reading a log\n * outside the deployment and guessing. So the refusal happens here, before\n * the fetch, and names the caller's `context`.\n *\n * It throws rather than returning a `SendEmailResult`: this is a programming\n * error, not a delivery outcome. `sendEmail` filters recipients well before\n * it reaches this call, so nothing on the ordinary path can trip it. The\n * guard exists because `RESEND_SEND_ENDPOINT` is exported and any module can\n * therefore reach the send endpoint on its own, bypassing every check\n * `sendEmail` owns.\n */\nexport async function postResendEmail(\n apiKey: string,\n payload: ResendSendPayload,\n context?: string,\n): Promise<Response> {\n const raw = payload?.to\n const recipients = (Array.isArray(raw) ? raw : raw == null ? [] : [raw])\n .map((address) => String(address ?? '').trim())\n .filter(Boolean)\n if (!recipients.length) {\n throw new Error(\n `${context ? `${context} ` : ''}send refused before the network — a ` +\n 'Resend payload with no `to` field cannot become a message, and the ' +\n 'attempt would surface only as a 422 in the Resend dashboard',\n )\n }\n\n return fetch(RESEND_SEND_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n })\n}\n\n/**\n * Sends one email through Resend.\n *\n * **Never throws and never rejects.** Outbound mail is best-effort across\n * every caller in this codebase — a checkout must not fail because a receipt\n * bounced — so every outcome comes back as a `SendEmailResult` instead. The\n * one thing callers must not do is ignore the result: `sent` is what tells\n * the user whether a message actually went out (AGL-708).\n *\n * When the env vars are missing this warns once per call and returns\n * `{ sent: false, reason: 'unconfigured' }` rather than failing, so local and\n * preview environments keep working without a Resend account.\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n const { apiKey, from: configuredFrom } = getEmailConfig()\n const label = options.context ? `${options.context} email` : 'email'\n\n /*\n * THE SENDING-IDENTITY REFUSAL.\n *\n * Enforced here AND at the campaign route, independently, for the reason\n * the send-rate governor is enforced twice: the route's check is the one a\n * person sees, and this one is what holds when a caller does not make it.\n * A governor is injectable and a route is skippable, so neither may be the\n * only thing standing between an unverified domain and a send.\n *\n * Placed above the `apiKey`/`from` gate so a refusal cannot be reported as\n * `unconfigured` — the two have different owners and different fixes.\n */\n const identityRefusal = sendingIdentityRefusal(options.sendingIdentity)\n if (identityRefusal) {\n console.warn(`${label} refused — ${identityRefusal.message}`)\n return {\n sent: false,\n reason: 'unverified-domain',\n detail: identityRefusal.message,\n }\n }\n\n // A resolved identity outranks the configured sender: it is the server's\n // answer to which verified address this message leaves on. Without one, the\n // white-label display name is applied to the configured verified sender\n // (White-Label Phase 1).\n //\n // Two sources, and `options` is neither of them. Nothing the caller passes\n // reaches the address — only the display name in front of it.\n const resolvedFrom = options.sendingIdentity?.from ?? null\n\n /*\n * THE PLATFORM DOMAIN IS NOT A FALLBACK FOR TENANT MAIL.\n *\n * `configuredFrom` is `USAGE_EMAIL_FROM` — an address on `aglyn.com`, where\n * Aglyn's own billing, account and console mail leaves from. A site's mail\n * reaching it means that site's list quality is charged against the domain\n * every other customer's password reset depends on.\n *\n * `resolveHostSendingIdentity` already refuses above, so a tenant caller\n * that resolved an identity never arrives here with `resolvedFrom` null.\n * This is the arm for a tenant caller that resolved NOTHING — the shape a\n * new send site takes when its author does not know an identity is owed —\n * and it is checked here rather than left to the call sites because ninety\n * of them cannot each be relied on to remember.\n */\n if (options.audience === 'tenant' && !resolvedFrom) {\n console.warn(\n `${label} refused — a site's mail cannot leave on the shared platform ` +\n 'domain, and no sending identity was resolved for it',\n )\n return {\n sent: false,\n reason: 'unverified-domain',\n detail:\n 'This message belongs to a site and no sending identity was ' +\n 'resolved for it, so it was refused rather than sent from the ' +\n 'shared Aglyn address.',\n }\n }\n\n const from = applyFromName(\n resolvedFrom ?? configuredFrom,\n options.fromName,\n )\n\n if (!apiKey || !from) {\n console.warn(\n `${label} skipped — set RESEND_API_KEY and USAGE_EMAIL_FROM to ` +\n 'deliver mail',\n )\n return { sent: false, reason: 'unconfigured' }\n }\n\n const to = normalizeRecipients(options.to)\n if (!to.length) {\n console.warn(`${label} skipped — no valid recipient address`)\n return { sent: false, reason: 'no-recipient' }\n }\n\n /*\n * THE MARKETING GATE.\n *\n * Everything a marketing message owes, asked once, here — because the four\n * merchant-triggered bulk paths that owed it discharged none of it, and\n * asking four call sites to remember is the shape that produces the fifth\n * that does not.\n *\n * Ahead of the send-rate governor deliberately. A refusal here is a message\n * that must never leave, so spending platform hourly budget deciding that\n * would be budget the rest of the hour's mail no longer has.\n *\n * Nothing installed is UNGATED. Same posture as the governor: the durable\n * half lives in another library, and a deployment that never installs it\n * must still send.\n */\n /*\n * TWO URLS, and which one goes where is the whole RFC 8058 story.\n *\n * `unsubscribeUrl` is what a PERSON clicks in the footer below, and the\n * gate points it at the preference page so the stream this message belongs\n * to is one of the things they can stop instead of all of it.\n * `oneClickUrl` is what `List-Unsubscribe` names, and it must stay on the\n * route whose POST writes immediately — a mailbox provider POSTs it with\n * nobody present and reads the 200 as \"done\", which a page of checkboxes\n * cannot honor.\n *\n * It falls back to `unsubscribeUrl` for a caller that minted one link and\n * named no page, which is the only shape that was ever possible before the\n * gate minted the pair.\n */\n let unsubscribeUrl = options.marketing?.unsubscribeUrl ?? ''\n let oneClickUrl = options.marketing?.oneClickUrl ?? ''\n if (options.marketing) {\n if (to.length !== 1) {\n // Not a delivery outcome — a caller error, and one that would put the\n // first recipient's signed unsubscribe link in everybody else's copy.\n console.error(\n `${label} refused — a marketing send addresses exactly one ` +\n `recipient, and this one names ${to.length}`,\n )\n return {\n sent: false,\n reason: 'no-recipient',\n detail: 'A marketing send addresses exactly one recipient.',\n }\n }\n const gate = getMarketingSendGate()\n if (gate) {\n let verdict: Awaited<ReturnType<typeof gate>> | null\n try {\n verdict = await gate({\n hostId: options.marketing.hostId,\n siteBase: options.marketing.siteBase,\n email: to[0],\n context: options.context,\n capped: options.marketing.capped !== false,\n // Passed through verbatim, INCLUDING absent. A default topic\n // applied here would invent a stream for every caller that named\n // none and let a topic opt-out refuse messages that belong to no\n // stream — see `MarketingSendContext.topicId`.\n ...(options.marketing.topicId\n ? { topicId: options.marketing.topicId }\n : {}),\n })\n } catch (error) {\n /*\n * FAILS OPEN, and the asymmetry with `filterSendableForHost` is\n * deliberate rather than an oversight. That helper fails CLOSED\n * because a suppression list it could not read is not a list that\n * said an address is safe to mail — and it keeps doing so, inside\n * the gate. What is being caught here is the gate itself being\n * unreachable or throwing, which is an outage on the control; an\n * outage on a control that becomes an outage on the product is the\n * worse of the two bugs, and it is the posture `sendEmail` takes\n * everywhere else.\n */\n console.error(`${label} marketing gate failed — allowing`, error)\n verdict = null\n }\n if (verdict && !verdict.allowed) {\n /*\n * A cadence refusal reports as `frequency-capped` rather than earning\n * a value of its own in {@link SendEmailFailureReason}.\n *\n * That union is what {@link isDeferrableSendResult} switches on, and\n * the two are deferrable for exactly the same reason: a later attempt\n * passes because time went by. A third value would have to be added\n * to that predicate as well, and a sweep built against the older\n * vocabulary would silently treat the recipient's own request as\n * terminal and stamp the subject — discarding a message the recipient\n * asked to receive later rather than never. Which of the two it was\n * is in `detail`, where a person reading a log needs it.\n */\n const reason: SendEmailFailureReason =\n verdict.refusal === 'frequency-capped' ||\n verdict.refusal === 'cadence-limited'\n ? 'frequency-capped'\n : verdict.refusal === 'unengaged'\n ? 'unengaged'\n : 'suppressed'\n console.warn(`${label} not sent — ${verdict.detail ?? reason}`)\n return { sent: false, reason, detail: verdict.detail }\n }\n unsubscribeUrl = unsubscribeUrl || verdict?.unsubscribeUrl || ''\n oneClickUrl = oneClickUrl || verdict?.oneClickUrl || ''\n }\n if (!unsubscribeUrl) {\n // A marketing message with no way out is the defect this gate exists to\n // close, so it is said out loud rather than shipped quietly. Not a\n // refusal: the cause is a missing `EMAIL_UNSUBSCRIBE_SECRET` or a host\n // with no public origin — an operator's configuration, not the\n // recipient's problem — and refusing here would turn it into silence.\n console.warn(\n `${label} carries no unsubscribe link — set ` +\n 'EMAIL_UNSUBSCRIBE_SECRET and publish the site on a domain',\n )\n }\n }\n\n /*\n * BULK MAIL WITH NO WAY OUT DOES NOT LEAVE ON THE POOLED IDENTITY.\n *\n * The pool carries marketing for every site that has no domain of its own,\n * and what keeps that survivable is that a recipient can always stop it: the\n * complaint that would otherwise be charged to every other site on the member\n * has a cheaper alternative one click away. A message that lost its\n * unsubscribe link removes that alternative, so it is refused here rather\n * than sent at other people's expense.\n *\n * Asked AFTER the gate, because only here is the answer known. The URL may\n * arrive from the caller, from the gate that mints one per recipient, or —\n * for a campaign, which composes its own one-click pair upstream — as a\n * `List-Unsubscribe` header and no marketing context at all. Reading only one\n * of the three would refuse the senders that are behaving.\n *\n * The classification is DERIVED, never declared. See `isMarketingMessage`.\n */\n const pooledRefusal = isMarketingMessage(options)\n ? pooledMarketingRefusal(\n options.sendingIdentity,\n Boolean(unsubscribeUrl) ||\n Boolean(options.headers?.['List-Unsubscribe']),\n )\n : null\n if (pooledRefusal) {\n console.warn(`${label} refused — ${pooledRefusal.message}`)\n return {\n sent: false,\n reason: 'unverified-domain',\n detail: pooledRefusal.message,\n }\n }\n\n /*\n * THE PLATFORM SEND-RATE GOVERNOR (AGL-2409).\n *\n * Asked on EVERY send, including transactional ones, because the ceiling is\n * about total volume on one sending domain — a governor that only saw\n * campaigns would report a quiet hour while ten thousand receipts went out.\n * The governor counts what it grants.\n *\n * Two properties this block must have, in order:\n *\n * 1. **A refusal is honoured only for a refusable priority.** This is the\n * second of the two enforcement points described in `send-rate.ts`.\n * `emailSendRateVerdict` already cannot refuse a transactional send;\n * the governor is INJECTABLE, so a wrong one is reachable, and the send\n * path must still be unable to drop a password reset. Anything that is\n * not explicitly a campaign or a bulk sweep sends regardless of the\n * answer.\n * 2. **It fails open.** A governor that throws — Firestore unreachable, no\n * Admin app, a bug — must not stop mail. The counter being unavailable\n * is an outage on the control, and an outage on a control that turns\n * into an outage on the product is a worse bug than the burst it was\n * guarding. The same posture `sendEmail` takes everywhere else: it\n * never throws, and neither does this.\n */\n const priority = resolveSendPriority(options.context, options.priority)\n const governor = getEmailSendGovernor()\n if (governor) {\n let verdict: Awaited<ReturnType<typeof governor>> | null\n try {\n verdict = await governor({\n priority,\n count: to.length,\n context: options.context,\n })\n } catch (error) {\n console.error(`${label} send-rate governor failed — allowing`, error)\n verdict = null\n }\n if (verdict && !verdict.allowed && isRefusablePriority(priority)) {\n const retryAtMs =\n verdict.retryAtMs ?? emailSendRateWindowStartMs(Date.now())\n console.warn(\n `${label} deferred — platform send rate reached ` +\n `(${verdict.used ?? '?'}/${verdict.ceiling ?? '?'} this hour)`,\n )\n return {\n sent: false,\n reason: 'rate-limited',\n retryAtMs,\n detail:\n `Platform hourly send rate reached (${verdict.ceiling ?? '?'}/hour). ` +\n 'Transactional mail is unaffected.',\n }\n }\n }\n\n /*\n * THE VISIBLE OPT-OUT, on both parts.\n *\n * The header pair below is for the mailbox provider; this is for the person\n * — CAN-SPAM asks for a mechanism the recipient can see and use, and most\n * clients render no control for the header at all. Both helpers are\n * idempotent by URL, so a sender that placed its own link (a designed\n * template rendering `{{unsubscribeUrl}}`, the campaign body's footer)\n * keeps its own placement and does not get a second one.\n *\n * `text` first and `html` from the result, so the synthesized HTML part\n * that stands in for a text-only message carries the link as an anchor\n * rather than as characters.\n */\n const text = unsubscribeUrl\n ? appendUnsubscribeText(options.text ?? '', unsubscribeUrl)\n : options.text\n const html = unsubscribeUrl\n ? options.html\n ? appendUnsubscribeHtml(options.html, unsubscribeUrl)\n : renderTextEmailHtml(text ?? '', options.subject)\n : options.html\n\n try {\n const response = await postResendEmail(\n apiKey,\n {\n from,\n to,\n subject: options.subject,\n ...(text ? { text } : {}),\n // The HTML part, from the caller when it has one and otherwise\n // synthesized from `text`. A message with no HTML part carries no\n // anchors, so its links are not links in the inbox AND Resend has\n // nothing to rewrite for click tracking — see `text-email-html.ts`.\n // The caller always wins: this can only fill a gap, never override a\n // designed template.\n ...(() => {\n const body = html || renderTextEmailHtml(text ?? '', options.subject)\n return body ? { html: body } : {}\n })(),\n // The caller's headers plus the RFC 8058 pair for a marketing send.\n // Caller-first, so the campaign sender's own pair is the one that\n // ships and a merchant-authored header is never silently replaced.\n ...(() => {\n const headers = {\n ...unsubscribeHeaders(oneClickUrl || unsubscribeUrl),\n ...(options.headers ?? {}),\n }\n return Object.keys(headers).length ? { headers } : {}\n })(),\n // The caller's tags plus the `context` tag (AGL-2407). Caller-first\n // so a sender that stamps its own `context` keeps it: a tag list with\n // two entries of one name is not a shape worth discovering in\n // production, and the explicit one is the more specific.\n ...(() => {\n const caller = options.tags ?? []\n const derived = caller.some((tag) => tag?.name === 'context')\n ? []\n : contextTag(options.context)\n const tags = [...caller, ...derived]\n return tags.length ? { tags } : {}\n })(),\n ...(options.replyTo ? { reply_to: options.replyTo } : {}),\n },\n options.context,\n )\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n /*\n * A 429 IS NOT A STATEMENT ABOUT THIS RECIPIENT, so it does not report\n * as one. See the `rate-limited` member of\n * {@link SendEmailFailureReason} for why the distinction is load-bearing\n * rather than cosmetic — every caller in the tree already has a branch\n * for a deferral, and none of them has one for \"rejected, but try this\n * exact address again later\".\n *\n * A warning rather than an error: the provider asking for a slower pace\n * is a normal thing to be told, and logging it at the level a failed\n * delivery uses is what teaches an operator to skim past both.\n */\n if (response.status === 429) {\n const retryAtMs = providerRetryAtMs(response.headers)\n console.warn(\n `${label} deferred — the provider is rate limiting; retry in ` +\n `${Math.max(0, Math.round((retryAtMs - Date.now()) / 1000))}s`,\n )\n return {\n sent: false,\n reason: 'rate-limited',\n status: response.status,\n retryAtMs,\n detail: detail.slice(0, 500),\n }\n }\n console.error(`${label} failed`, response.status, detail)\n return {\n sent: false,\n reason: 'rejected',\n status: response.status,\n detail: detail.slice(0, 500),\n }\n }\n\n const body = (await response.json().catch(() => null)) as {\n id?: string\n } | null\n return { sent: true, id: body?.id ?? null }\n } catch (error) {\n console.error(`${label} failed`, error)\n return {\n sent: false,\n reason: 'network',\n detail: String((error as Error)?.message ?? error).slice(0, 500),\n }\n }\n}\n\nexport default sendEmail\n"],"names":["emailSendRateWindowStartMs","getEmailSendGovernor","isRefusablePriority","resolveSendPriority","renderTextEmailHtml","sendingIdentityRefusal","pooledMarketingRefusal","appendUnsubscribeHtml","appendUnsubscribeText","getMarketingSendGate","isMarketingMessage","unsubscribeHeaders","RESEND_SEND_ENDPOINT","contextTag","context","value","String","trim","replace","slice","name","rateLimitedRetryAtMs","result","failure","reason","retryAtMs","Number","isFinite","PROVIDER_RETRY_FALLBACK_MS","PROVIDER_RETRY_MAX_MS","headerSeconds","headers","raw","get","undefined","seconds","providerRetryAtMs","nowMs","Date","now","waitMs","Math","min","sendFailureReason","sent","isDeferrableSendResult","getEmailConfig","apiKey","process","env","RESEND_API_KEY","from","USAGE_EMAIL_FROM","isEmailConfigured","Boolean","applyFromName","fromName","angle","match","address","includes","normalizeRecipients","to","list","Array","isArray","map","filter","postResendEmail","payload","recipients","length","Error","fetch","method","Authorization","body","JSON","stringify","sendEmail","options","configuredFrom","label","identityRefusal","sendingIdentity","console","warn","message","detail","resolvedFrom","audience","unsubscribeUrl","marketing","oneClickUrl","error","gate","verdict","hostId","siteBase","email","capped","topicId","allowed","refusal","pooledRefusal","priority","governor","count","used","ceiling","text","html","subject","response","Object","keys","caller","tags","derived","some","tag","replyTo","reply_to","ok","catch","status","max","round","json","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GACD,SAEEA,0BAA0B,EAC1BC,oBAAoB,EACpBC,mBAAmB,EACnBC,mBAAmB,QACd,iBAAa;AACpB,SAASC,mBAAmB,QAAQ,uBAAmB;AACvD,SACEC,sBAAsB,EACtBC,sBAAsB,QAGjB,sBAAkB;AACzB,SACEC,qBAAqB,EACrBC,qBAAqB,EACrBC,oBAAoB,EACpBC,kBAAkB,EAClBC,kBAAkB,QAEb,sBAAkB;AAEzB,OAAO,MAAMC,uBAAuB,gCAA+B;AA2HnE;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASC,WAAWC,OAA2B;IACpD,MAAMC,QAAQC,OAAOF,kBAAAA,UAAW,IAC7BG,IAAI,GACJC,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,YAAY,IACpBC,KAAK,CAAC,GAAG;IACZ,OAAOJ,QAAQ;QAAC;YAAEK,MAAM;YAAWL;QAAM;KAAE,GAAG,EAAE;AAClD;AAmHA;;;;;;;;;;CAUC,GACD,OAAO,SAASM,qBACdC,MAA0C;IAE1C,MAAMC,UAAUD;IAChB,IAAI,CAACC,WAAWA,QAAQC,MAAM,KAAK,gBAAgB,OAAO;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KAAKqF,GAAG,CAAC,GAAGrF,KAAKsF,KAAK,CAAC,AAACtG,CAAAA,YAAYa,KAAKC,GAAG,EAAC,IAAK,OAAO,CAAC,CAAC;gBAElE,OAAO;oBACLK,MAAM;oBACNpB,QAAQ;oBACRqG,QAAQZ,SAASY,MAAM;oBACvBpG;oBACA+D,QAAQA,OAAOrE,KAAK,CAAC,GAAG;gBAC1B;YACF;YACAkE,QAAQS,KAAK,CAAC,GAAGZ,MAAM,OAAO,CAAC,EAAE+B,SAASY,MAAM,EAAErC;YAClD,OAAO;gBACL5C,MAAM;gBACNpB,QAAQ;gBACRqG,QAAQZ,SAASY,MAAM;gBACvBrC,QAAQA,OAAOrE,KAAK,CAAC,GAAG;YAC1B;QACF;QAEA,MAAMyD,OAAQ,MAAMqC,SAASe,IAAI,GAAGJ,KAAK,CAAC,IAAM;QAGhD,OAAO;YAAEhF,MAAM;YAAMqF,EAAE,WAAErD,wBAAAA,KAAMqD,EAAE,oBAAI;QAAK;IAC5C,EAAE,OAAOnC,OAAO;;QACdT,QAAQS,KAAK,CAAC,GAAGZ,MAAM,OAAO,CAAC,EAAEY;QACjC,OAAO;YACLlD,MAAM;YACNpB,QAAQ;YACRgE,QAAQxE,gBAAQ8E,yBAAD,AAACA,MAAiBP,OAAO,oBAAIO,OAAO3E,KAAK,CAAC,GAAG;QAC9D;IACF;AACF;AAEA,eAAe4D,UAAS"}
@@ -0,0 +1,298 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * THE PLATFORM SEND-RATE GOVERNOR — policy half (AGL-2409).
19
+ *
20
+ * Everything Aglyn sends leaves on ONE Resend key, from ONE verified sending
21
+ * domain, under `p=reject`. A throttle or a reputation hit there is not a spam
22
+ * folder: it is a rejection, and it lands on every customer's password resets
23
+ * and receipts at the same time. Before this there was no per-hour or per-day
24
+ * throttle, no batching and no concurrency limiter anywhere in the email path
25
+ * — so the two bursts the product can already produce (the monthly usage
26
+ * summary fanning out to 1,000 orgs in one invocation, and scheduled campaigns
27
+ * at a ceiling of 10 × 500 × 4 = 20,000 messages an hour) had nothing to ramp
28
+ * against, and the day a ramp was needed there would have been nothing to
29
+ * turn.
30
+ *
31
+ * ## Why the policy is pure and dependency-free
32
+ *
33
+ * Same split as `plugin-api-rate-limit.ts` and `api-http.ts`: the decision is
34
+ * a pure function of (priority, ceiling, used, count) and is unit-testable
35
+ * without a Firestore harness or a route. The durable counter lives in
36
+ * `@aglyn/tenant-data-admin` (`email-send-rate.ts`), which is the only layer
37
+ * that may hold the Admin SDK — `@aglyn/shared-util-email` is `scope:shared`
38
+ * and may not import it, and the existing edge already runs the other way
39
+ * (`tenant-data-admin` imports THIS library). So the governor reaches
40
+ * `sendEmail` by injection, {@link setEmailSendGovernor}, rather than by an
41
+ * import that would be a dependency cycle.
42
+ *
43
+ * ## THE BOUNDARY THAT MATTERS MOST
44
+ *
45
+ * **A rate control may only ever refuse a CAMPAIGN or a BULK sweep. It may
46
+ * never refuse a transactional message.** A password reset or an order
47
+ * receipt refused by a throttle is a strictly worse outcome than the burst
48
+ * being throttled: it converts a reputation risk into an outage on somebody
49
+ * else's business, and the mail explaining why is itself mail that will not
50
+ * send. That is the same rule `email-metering.ts` states for the monthly
51
+ * quota, applied to time distribution instead of monthly totals.
52
+ *
53
+ * The rule is enforced in two independent places on purpose — here, in
54
+ * {@link emailSendRateVerdict}, which cannot return `allowed: false` for a
55
+ * transactional send at all; and again in `sendEmail`, which ignores a
56
+ * refusal for a transactional priority whatever the installed governor says.
57
+ * A governor is injectable, so a wrong one is reachable; the send path must
58
+ * still be unable to drop a password reset.
59
+ */
60
+ /** The three send priorities, ordered by what a control may do to them. */
61
+ export type EmailSendPriority =
62
+ /**
63
+ * Answers something a human just did, or a machine event a customer's
64
+ * business depends on: password reset, invite, order confirmation, booking
65
+ * reminder, workflow notification, membership recovery. **Never refused,
66
+ * never delayed.** Counted, because the ceiling is about total domain
67
+ * volume and this volume is real.
68
+ */
69
+ 'transactional'
70
+ /**
71
+ * A scheduled fan-out that answers no immediate human action: the monthly
72
+ * usage summary, abandoned-cart and restock sweeps, booking reminder
73
+ * batches. Refusable, because the caller is a resumable cron — a refusal
74
+ * means "not this hour", and the next run picks the subject up. A caller
75
+ * that is NOT resumable must not use this priority.
76
+ */
77
+ | 'bulk'
78
+ /**
79
+ * Merchant marketing. Refusable outright, with a message the merchant
80
+ * sees. The one discretionary class, exactly as in `email-metering.ts`.
81
+ */
82
+ | 'campaign';
83
+ /** Fixed one-hour window, matching the unit the issue and the ramp speak in. */
84
+ export declare const EMAIL_SEND_RATE_WINDOW_MS = 3600000;
85
+ /**
86
+ * The default ceiling, in messages per hour, when nothing has been
87
+ * configured.
88
+ *
89
+ * **This number is a default, not the policy.** The whole point of AGL-2409
90
+ * is that a ramp must be a value change and not a deploy, so the live ceiling
91
+ * is read from `rateLimits/sendRateConfig` and set from the staff console.
92
+ * This is only what an unconfigured deployment (a fork, a self-host, a
93
+ * preview) gets.
94
+ *
95
+ * 2,000/hour is chosen against measured shape rather than taste. Steady-state
96
+ * volume on the domain is a few hundred a day, so this is roughly two orders
97
+ * of magnitude of headroom over normal traffic — it cannot trip on real use,
98
+ * which is the property that keeps a limit from being raised until it means
99
+ * nothing. What it does remove is the two bursts named in the issue: 20,000
100
+ * campaign messages an hour becomes 2,000, and a 1,000-org usage fan-out in
101
+ * one invocation becomes a fan-out that has to ask.
102
+ */
103
+ export declare const EMAIL_SEND_RATE_DEFAULT_PER_HOUR = 2000;
104
+ /**
105
+ * Hard bound on a configured ceiling. Not a business rule — a typo guard, so
106
+ * a slipped digit in the console cannot set a ceiling that is effectively no
107
+ * ceiling. Raising it past this is a deploy, which is the correct friction
108
+ * for a change of that size.
109
+ */
110
+ export declare const EMAIL_SEND_RATE_MAX_PER_HOUR = 100000;
111
+ /** A configured ceiling of 0 would refuse every campaign; 1 is the floor. */
112
+ export declare const EMAIL_SEND_RATE_MIN_PER_HOUR = 1;
113
+ /**
114
+ * Requests per second the provider accepts, from its published default.
115
+ *
116
+ * Resend documents 10 requests per second PER TEAM — across every API key on
117
+ * the account, not per key and not per sending domain. Past it the API
118
+ * answers HTTP 429 `rate_limit_exceeded`, carrying `retry-after` and
119
+ * `ratelimit-reset` in whole seconds
120
+ * (https://resend.com/changelog/api-rate-limit).
121
+ *
122
+ * A vendor's number, so it is stated once here rather than divided into an
123
+ * interval at the one loop that has to respect it. It can be raised by
124
+ * arrangement with the provider; raising it here without that arrangement
125
+ * buys 429s.
126
+ */
127
+ export declare const EMAIL_PROVIDER_REQUESTS_PER_SECOND = 10;
128
+ /**
129
+ * Requests per second a BATCH may take of that rate.
130
+ *
131
+ * One less than the provider allows, and the missing request is not a safety
132
+ * margin — it is the transactional mail. The limit is counted per TEAM, so a
133
+ * campaign loop running flat out at the full rate is a campaign that answers
134
+ * a password reset arriving in the same second with a 429. That is the
135
+ * outcome this file's opening rule forbids a rate control from producing, and
136
+ * a batch is the only sender in the tree fast enough to produce it.
137
+ *
138
+ * One request per second is not much headroom, and it is not meant to be a
139
+ * budget for concurrent campaigns: it is enough for the one-off sends that
140
+ * make up all of this deployment's other traffic. It also keeps a batch off
141
+ * the exact boundary, where clock jitter alone would earn a 429 on a send
142
+ * that is nominally inside the limit.
143
+ */
144
+ export declare const EMAIL_BATCH_REQUESTS_PER_SECOND: number;
145
+ /** The shortest gap between two batch requests that stays inside that rate. */
146
+ export declare const EMAIL_BATCH_MIN_REQUEST_INTERVAL_MS: number;
147
+ /**
148
+ * Environment name for a provider rate that is not the published default.
149
+ *
150
+ * Deployment-level rather than stored config, because it is a property of the
151
+ * Resend ACCOUNT the deployment holds a key for — the same layer
152
+ * `RESEND_API_KEY` lives at, and a different question from the hourly ceiling
153
+ * an operator ramps. Resend raises the limit for trusted senders on request,
154
+ * and a self-host runs its own account entirely, so the number cannot be a
155
+ * constant in a shipped build.
156
+ */
157
+ export declare const EMAIL_PROVIDER_RATE_ENV = "EMAIL_PROVIDER_REQUESTS_PER_SECOND";
158
+ /**
159
+ * The interval a batch paces itself by on this deployment.
160
+ *
161
+ * Unset or unreadable resolves to the published default, never to zero: a
162
+ * typo in an env var must not silently remove a rate control. Zero is
163
+ * accepted only when it is written explicitly, and it disables pacing — which
164
+ * is what a harness with no provider behind it passes, and what an operator
165
+ * who has moved rate control somewhere else in front of this process sets.
166
+ */
167
+ export declare function batchRequestIntervalMs(raw?: unknown): number;
168
+ /**
169
+ * A pace for a loop that issues one provider request per iteration.
170
+ *
171
+ * Returns a function to await once per iteration. It waits only for whatever
172
+ * is LEFT of the interval since the previous request rather than sleeping a
173
+ * fixed amount, which is the property that makes it free where it is not
174
+ * needed: a loop whose own work already takes longer than the interval —
175
+ * every send in production, which pays a network round trip and a Firestore
176
+ * read per recipient — never waits at all, and a loop that would otherwise
177
+ * fire five hundred requests as fast as the socket allows is spread out to
178
+ * the documented rate.
179
+ *
180
+ * Per-caller state rather than a module-level clock, so two concurrent sends
181
+ * do not share one pace. That is deliberately NOT a claim that the process as
182
+ * a whole stays under the rate: the provider counts the whole team, and this
183
+ * bounds one loop. It removes the burst a single batch produces, which is the
184
+ * only place in this codebase that issues requests in a tight loop.
185
+ *
186
+ * `intervalMs` of 0 (or anything unreadable) disables the wait entirely,
187
+ * which is what a caller with nothing to pace passes. Read per call rather
188
+ * than captured at module load, for the reason `getEmailConfig` is: these run
189
+ * in serverless handlers where the module may be evaluated during a build,
190
+ * long before the runtime env exists.
191
+ */
192
+ export declare function createProviderRequestPacer(intervalMs?: number): () => Promise<void>;
193
+ /** The live ceiling, as stored and as the console edits it. */
194
+ export interface EmailSendRateConfig {
195
+ /** Messages per hour across the whole platform. */
196
+ perHour: number;
197
+ /**
198
+ * False parks the governor: every priority is granted and still counted,
199
+ * so the console keeps showing real volume. The off switch exists because
200
+ * an operator who suspects the governor is refusing legitimate mail must be
201
+ * able to stop it in one click rather than by raising a number they then
202
+ * have to remember to lower.
203
+ */
204
+ enabled: boolean;
205
+ /** When staff last changed it, ms. Null when never configured. */
206
+ updatedAtMs: number | null;
207
+ /** Who changed it; shown beside the value so a ramp has an author. */
208
+ updatedByEmail: string | null;
209
+ /** Why — the ramp step, the incident. Free text, bounded. */
210
+ note: string;
211
+ }
212
+ /** Bound on the stored note, so a config read stays a small document. */
213
+ export declare const EMAIL_SEND_RATE_NOTE_MAX = 500;
214
+ /**
215
+ * Reads a stored config document into a usable shape.
216
+ *
217
+ * Every field is clamped rather than trusted. This document decides whether a
218
+ * campaign goes out, and a `perHour` of `NaN` (or `-1`, or a string) reaching
219
+ * the comparison would silently refuse everything refusable on the platform —
220
+ * an outage produced by a bad write. An unreadable value falls back to the
221
+ * default ceiling, never to zero and never to unlimited.
222
+ */
223
+ export declare function normalizeEmailSendRateConfig(raw: Partial<EmailSendRateConfig> | null | undefined): EmailSendRateConfig;
224
+ /**
225
+ * The priority for a send. An explicit `priority` always wins; otherwise a
226
+ * campaign context is recognised, and everything else is transactional.
227
+ */
228
+ export declare function resolveSendPriority(context: string | undefined, explicit?: EmailSendPriority): EmailSendPriority;
229
+ /** True when a control is permitted to refuse this priority at all. */
230
+ export declare function isRefusablePriority(priority: EmailSendPriority): boolean;
231
+ /** Start of the fixed window containing `nowMs`. */
232
+ export declare function emailSendRateWindowStartMs(nowMs: number, windowMs?: number): number;
233
+ export interface EmailSendRateInput {
234
+ priority: EmailSendPriority;
235
+ /** Messages already counted in this window. */
236
+ used: number;
237
+ /** Messages this send would add. */
238
+ count: number;
239
+ /** The live ceiling for the window. */
240
+ ceiling: number;
241
+ /** False parks the governor — grant everything, still count it. */
242
+ enabled?: boolean;
243
+ /** Start of the window, for `retryAtMs`. */
244
+ windowStartMs: number;
245
+ windowMs?: number;
246
+ }
247
+ export interface EmailSendRateVerdict {
248
+ allowed: boolean;
249
+ priority: EmailSendPriority;
250
+ ceiling: number;
251
+ /** Count in the window BEFORE this send. */
252
+ used: number;
253
+ /** Headroom left after this send, floored at 0. */
254
+ remaining: number;
255
+ /** When the window rolls and a refused caller may try again. */
256
+ retryAtMs: number;
257
+ /**
258
+ * True when the send was granted despite there being no headroom, because
259
+ * refusing it was not permitted. This is how the console shows that a
260
+ * window went over its ceiling on transactional volume — which is not an
261
+ * error, it is the ceiling declining to enforce, exactly like the monthly
262
+ * overage `emailSendsOverage` records.
263
+ */
264
+ overCeiling: boolean;
265
+ }
266
+ /**
267
+ * The decision. Pure.
268
+ *
269
+ * A transactional send is ALWAYS `allowed`, whatever the numbers say — there
270
+ * is no branch in this function that can refuse one. That is deliberate and
271
+ * is the first of the two enforcement points described at the top of this
272
+ * file.
273
+ */
274
+ export declare function emailSendRateVerdict(input: EmailSendRateInput): EmailSendRateVerdict;
275
+ /** What `sendEmail` asks the installed governor. */
276
+ export interface EmailSendGovernorRequest {
277
+ priority: EmailSendPriority;
278
+ /** Recipient addresses on this one send. */
279
+ count: number;
280
+ context?: string;
281
+ }
282
+ /** What the governor answers. A subset of the verdict `sendEmail` needs. */
283
+ export interface EmailSendGovernorVerdict {
284
+ allowed: boolean;
285
+ ceiling?: number;
286
+ used?: number;
287
+ remaining?: number;
288
+ retryAtMs?: number;
289
+ /** True when the durable counter was unreachable and this failed open. */
290
+ degraded?: boolean;
291
+ }
292
+ export type EmailSendGovernor = (request: EmailSendGovernorRequest) => Promise<EmailSendGovernorVerdict>;
293
+ /** Installs the durable governor. Called once, from `@aglyn/tenant-data-admin`. */
294
+ export declare function setEmailSendGovernor(governor: EmailSendGovernor | null): void;
295
+ /** The installed governor, or null when nothing has been installed. */
296
+ export declare function getEmailSendGovernor(): EmailSendGovernor | null;
297
+ /** Test seam: forget any installed governor. */
298
+ export declare function resetEmailSendGovernorForTests(): void;