@aglyn/shared-util-email 1.0.0-beta.234 → 1.0.0-beta.235
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/package.json +3 -3
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/src/index.js.map +1 -1
- package/src/lib/mail-provider-resend.js +3 -1
- package/src/lib/mail-provider-resend.js.map +1 -1
- package/src/lib/mail-provider-webhook.d.ts +3 -0
- package/src/lib/mail-provider-webhook.js +6 -1
- package/src/lib/mail-provider-webhook.js.map +1 -1
- package/src/lib/mail-provider.d.ts +2 -0
- package/src/lib/mail-provider.js.map +1 -1
- package/src/lib/retention-emails.d.ts +104 -0
- package/src/lib/retention-emails.js +375 -0
- package/src/lib/retention-emails.js.map +1 -0
- package/src/lib/send-email.d.ts +8 -0
- package/src/lib/send-email.js +21 -3
- package/src/lib/send-email.js.map +1 -1
- package/src/lib/system-email-catalog.js +11 -1
- package/src/lib/system-email-catalog.js.map +1 -1
|
@@ -1 +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 send seam. Every outbound application email in Aglyn goes through\n * here — invites, receipts, usage summaries, campaigns, staff alerts — and\n * everything that decides whether, as whom and to whom a message leaves is\n * decided here. The provider that then carries it is chosen by\n * `mail-providers.ts` and only carries it.\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'\nimport {\n EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS,\n getEmailDeliverabilityPreflight,\n type EmailDeliverabilityPreflightVerdict,\n type EmailSendPurpose,\n} from './email-deliverability'\nimport { bareSenderAddress } from './email-delivery-events'\nimport { screenTenantMessage } from './outbound-screen-gate'\nimport { providerRetryAtMs, type MailProviderSendResult } from './mail-provider'\nimport { mailProvider, mailProviderProblem } from './mail-providers'\n\n/**\n * A delivery tag: attribution the provider hands back on every delivery\n * event for the message, which is how a bounce finds its sender (AGL-268).\n */\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 the provider'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 * A SITE's mail leaves under the site's own name instead (AGL-3442): an\n * identity from `hostSendingIdentity` carries it, and it takes the place of\n * the org's branding default. A name of the caller's own, such as the\n * person writing a CRM email, still wins. See {@link messageFromName}.\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 * Delivers to an address whose account is BANNED (AGL-3420). A banned\n * account is sent nothing after its ban notice, by any sender; the lock\n * and lift notices themselves are the only mail that states this, and no\n * other sender may.\n */\n accountBanExempt?: boolean\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 `context` TAG on every send —\n * 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 * What the RECIPIENT did that makes this message owed to them (AGL-3356):\n * `order` — a receipt, a gift card, a shipping notice for something they\n * bought; `booking` — a confirmation, reminder or change to something they\n * booked; `account` — a password reset or sign-in link they asked for.\n *\n * The outbound phishing screen's SOFT rules never hold an owed message; a\n * lookalike link still does, because a receipt that links to a brand's\n * disguise is the disguise. Omitted — the default, and the one a forgotten\n * caller gets — the message is treated as merchant-authored and every\n * tier applies. A MARKETING message is never owed, whatever it declares.\n */\n owedFor?: 'order' | 'booking' | 'account'\n /**\n * A review row that the caller's own screen held and staff RELEASED for\n * exactly this content — a campaign put back on the clock, an automation\n * step whose hold was dismissed. The send seam's screen honors it only\n * after confirming, through the installed gate, that it is a release for\n * this site; naming a row is not a way past the screen.\n */\n releasedReviewId?: string | null\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 * Providers restrict tag values — to ASCII letters, digits, `_` and `-` at\n * the strictest — and one that rejects a value fails 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 the provider was asked 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 * The provider 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). The\n * provider asks for a slower pace when requests arrive faster than it\n * accepts them, and `status` is its answer (429 over HTTP) 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 /**\n * The recipient's domain takes no mail — no MX and no address record, or\n * an RFC 7505 null MX — so the message would only have bounced\n * (AGL-3328). Refused for every purpose, transactional included, before\n * the provider was called; the address is suppressed with a reason of its\n * own. Terminal: the preflight answers the same until the domain's DNS\n * changes, which it re-reads daily.\n */\n | 'undeliverable'\n /**\n * A BULK or cold message whose recipient sits behind a mail gateway that\n * refused this sending domain twice in thirty days and delivered nothing\n * (AGL-3328). Terminal for this message rather than deferrable: the hold\n * lifts when the gateway delivers again or the refusals age out, which is\n * not something a sweep's next beat can wait out. Mail the recipient asked\n * for is never held.\n */\n | 'gateway-held'\n /**\n * The site or workspace this message belongs to is under a full lockdown\n * (AGL-3356), carried in on its sending identity. Terminal for this\n * message: a sweep that holds work across a suspension skips the host\n * before it gets here, so a caller that reaches this refusal is one with\n * no way to come back, and retrying would only ask the same question.\n */\n | 'suspended'\n /**\n * The outbound phishing screen held this message for staff review, or\n * staff already rejected a message carrying the same signals from this\n * site (AGL-3356). Nothing was attempted. Terminal for this message:\n * `detail` names the `HS-…` reference, and once staff release the review\n * the site's next message carrying the same signals sends.\n */\n | 'held-for-review'\n\nexport type SendEmailResult =\n | { sent: true; id: string | null }\n | {\n sent: false\n reason: SendEmailFailureReason\n /** HTTP status, when the provider answered over HTTP. */\n status?: number\n /** The provider's error text 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 * 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\n/**\n * Who a message is for, as the deliverability preflight reads it\n * (AGL-3328): `bulk` for anything a control may already refuse — marketing\n * by either of its two marks, a campaign, a resumable sweep — and\n * `transactional` for the rest, which a gateway hold never touches.\n *\n * Derived from what a sender already declares, for the reason\n * `isMarketingMessage` is: a label callers had to remember would be\n * forgotten by the one that matters, and the permissive answer is the one a\n * forgotten caller gets.\n */\nexport function emailSendPurpose(\n options: Pick<SendEmailOptions, 'priority' | 'context' | 'headers'> & { marketing?: unknown },\n): EmailSendPurpose {\n if (isMarketingMessage(options)) return 'bulk'\n if (options.headers?.['List-Unsubscribe']) return 'bulk'\n return isRefusablePriority(resolveSendPriority(options.context, options.priority))\n ? 'bulk'\n : 'transactional'\n}\n\n/** The preflight's answer, or `null` when none is installed, it failed or it ran out of time. */\nasync function askDeliverabilityPreflight(\n request: Parameters<NonNullable<ReturnType<typeof getEmailDeliverabilityPreflight>>>[0],\n label: string,\n): Promise<EmailDeliverabilityPreflightVerdict | null> {\n const preflight = getEmailDeliverabilityPreflight()\n if (!preflight) return null\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n preflight(request),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n console.warn(`${label} deliverability preflight timed out — allowing`)\n resolve(null)\n }, EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS)\n ;(timer as { unref?: () => void })?.unref?.()\n }),\n ])\n } catch (error) {\n // Fails OPEN, the governor's posture: an outage on the control must not\n // become an outage on the mail.\n console.error(`${label} deliverability preflight failed — allowing`, error)\n return null\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\n/**\n * The display name a message leaves under (AGL-3442).\n *\n * A site's mail goes out under the site's own name — the business name its\n * emails render as `{{host.businessName}}`, else its display name, else the\n * org's branding default — which `hostSendingIdentity` resolves with the\n * address from the host and org documents it already reads. That is decided\n * here rather than at each sender because every site sender passes the org's\n * branding default as `fromName`, and to a visitor that is the platform's or\n * the agency's name rather than the business they dealt with. So the default\n * is replaced, and only the default: a name of the caller's own, such as the\n * person writing a CRM email, is still the name the message leaves under.\n *\n * Mail on any other identity — the platform's own, or a campaign's, which\n * resolves its identity without a host stamp and records the name its\n * composer chose — keeps the caller's `fromName` unchanged.\n */\nexport function messageFromName(\n options: Pick<SendEmailOptions, 'fromName' | 'sendingIdentity'>,\n): string | undefined {\n const given = String(options.fromName ?? '').trim()\n const identity = options.sendingIdentity\n const siteName = String(identity?.fromName ?? '').trim()\n if (!siteName) return given || undefined\n const brandDefault = String(identity?.brandFromName ?? '').trim()\n return given && given !== brandDefault ? given : siteName\n}\n\n/**\n * The send seam's half of the outbound phishing screen (AGL-3356): every\n * message a SITE sends whose identity carries the workspace\n * `hostSendingIdentity` stamped, through {@link screenTenantMessage} — the\n * pure screen, its tiers, and the installed review store. `null` when the\n * message may go; fails open, as that function documents.\n */\nexport async function askOutboundScreen(\n options: SendEmailOptions,\n label = 'email',\n): Promise<SendEmailResult | null> {\n const workspace = options.sendingIdentity?.workspace\n if (options.audience !== 'tenant' || !workspace?.hostId) return null\n const refusal = await screenTenantMessage(\n {\n workspace,\n subject: options.subject,\n // The name the message actually leaves under, so a site named after\n // somebody else's brand is screened on the `From:` line it would send.\n fromName: messageFromName(options) ?? null,\n // The resolved address, never anything the caller passed: the only\n // `From:` this message can leave on (AGL-3362).\n fromAddress: options.sendingIdentity?.from ?? null,\n replyTo: options.replyTo ?? null,\n bodies: [options.text, options.html],\n // A marketing message is never owed, whatever it declares.\n owed: Boolean(options.owedFor) && !isMarketingMessage(options),\n context: options.context ?? null,\n releasedReviewId: options.releasedReviewId ?? null,\n },\n label,\n )\n if (!refusal) return null\n console.warn(`${label} not sent — ${refusal.detail}`)\n return { sent: false, reason: 'held-for-review', detail: refusal.detail }\n}\n\nexport interface EmailConfig {\n /** The id of the provider mail is handed to — see `mail-providers.ts`. */\n provider: string\n /** Settings that provider still needs before it can send; empty when it can. */\n missingSettings: string[]\n /** The platform's own sender, `USAGE_EMAIL_FROM`. */\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 const provider = mailProvider()\n return {\n provider: provider.id,\n missingSettings: provider.missingSettings(),\n from: process.env.USAGE_EMAIL_FROM || undefined,\n }\n}\n\n/**\n * True when the provider has its settings and `USAGE_EMAIL_FROM` is 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 { missingSettings, from } = getEmailConfig()\n return !missingSettings.length && Boolean(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/**\n * Sends one email through the deployment's mail provider.\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 mail provider.\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n const provider = mailProvider()\n const configuredFrom = process.env.USAGE_EMAIL_FROM || undefined\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 provider/`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 // A suspension is not a DNS state, and the merchant reading the\n // failure has nothing to finish — so it is named for what it is.\n reason:\n identityRefusal.code === 'workspace-suspended'\n ? 'suspended'\n : '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 messageFromName(options),\n )\n\n const missing = [\n ...provider.missingSettings(),\n ...(from ? [] : ['USAGE_EMAIL_FROM']),\n ]\n if (missing.length) {\n /*\n * An operator who chose a provider this process does not have is told\n * so as an ERROR: that is not a deployment without mail, it is mail\n * somebody set up going nowhere. See `mail-providers.ts`.\n */\n const problem = mailProviderProblem(provider)\n if (problem) {\n console.error(`${label} not sent — ${problem}`)\n return { sent: false, reason: 'unconfigured', detail: problem }\n }\n console.warn(`${label} skipped — set ${missing.join(' and ')} to deliver mail`)\n return { sent: false, reason: 'unconfigured' }\n }\n\n let 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 OUTBOUND PHISHING SCREEN (AGL-3356).\n *\n * Asked for every message a SITE sends whose identity came through\n * `hostSendingIdentity` — which stamps the workspace on it — so one check\n * covers every tenant sender, first-party or marketplace, without any of\n * them calling it. See `outbound-screen-gate.ts`.\n *\n * Ahead of the preflight and every other gate: a message that must not\n * leave is decided before anything is spent on who receives it.\n */\n const screenRefusal = await askOutboundScreen(options, label)\n if (screenRefusal) return screenRefusal\n\n /*\n * THE DELIVERABILITY PREFLIGHT (AGL-3328).\n *\n * Asked before every other gate, because its refusal is the most final: a\n * recipient whose domain takes no mail is not a recipient this message or\n * any other can reach, and spending the marketing gate's reads or the\n * governor's hourly budget deciding more about them would be spending it\n * on a bounce. A recipient behind a gateway that refused this sending\n * domain twice is held — for bulk mail only; the purpose decides that,\n * and the preflight is told it.\n *\n * A multi-recipient message drops the refused and held recipients and goes\n * to the rest: one colleague's dead address must not stop the others'\n * notification.\n */\n const sendingAddress = bareSenderAddress(from)\n const preflight = await askDeliverabilityPreflight(\n {\n recipients: to.map((address) => address.toLowerCase()),\n purpose: emailSendPurpose(options),\n sendingDomain: sendingAddress ? sendingAddress.slice(sendingAddress.lastIndexOf('@') + 1) : null,\n sendingSource: options.sendingIdentity?.source ?? 'platform',\n context: options.context,\n hostId: options.marketing?.hostId ?? null,\n ...(options.accountBanExempt ? { accountBanExempt: true } : {}),\n },\n label,\n )\n if (preflight && (preflight.refused?.length || preflight.held?.length)) {\n const stopped = new Set(\n [...(preflight.refused ?? []), ...(preflight.held ?? [])].map((entry) =>\n String(entry?.email ?? '').toLowerCase(),\n ),\n )\n const remaining = to.filter((address) => !stopped.has(address.toLowerCase()))\n if (!remaining.length) {\n const refused = preflight.refused?.[0]\n const held = preflight.held?.[0]\n const detail = refused?.reason ?? held?.reason ?? 'The recipient cannot receive this message.'\n console.warn(`${label} not sent — ${detail}`)\n return { sent: false, reason: refused ? 'undeliverable' : 'gateway-held', detail }\n }\n console.warn(\n `${label} — ${to.length - remaining.length} of ${to.length} recipients ` +\n 'dropped by the deliverability preflight',\n )\n to = remaining\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 consentHostIds: options.marketing.consentHostIds,\n consentAwaitsConfirmation: options.marketing.consentAwaitsConfirmation,\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 // 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 the provider has\n // nothing to rewrite for click tracking — see `text-email-html.ts`. The\n // caller always wins: this can only fill a gap, never override a\n // designed template.\n const body = html || renderTextEmailHtml(text ?? '', options.subject)\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 ships\n // and a merchant-authored header is never silently replaced.\n const headers = {\n ...unsubscribeHeaders(oneClickUrl || unsubscribeUrl),\n ...(options.headers ?? {}),\n }\n // The caller's tags plus the `context` tag (AGL-2407). Caller-first so a\n // sender that stamps its own `context` keeps it: a tag list with two\n // entries of one name is not a shape worth discovering in production,\n // and the explicit one is the more specific.\n const callerTags = options.tags ?? []\n const tags = [\n ...callerTags,\n ...(callerTags.some((tag) => tag?.name === 'context')\n ? []\n : contextTag(options.context)),\n ]\n\n const outcome = await provider.send(\n {\n from,\n to,\n subject: options.subject,\n ...(text ? { text } : {}),\n ...(body ? { html: body } : {}),\n ...(Object.keys(headers).length ? { headers } : {}),\n ...(tags.length ? { tags } : {}),\n ...(options.replyTo ? { replyTo: options.replyTo } : {}),\n },\n options.context,\n )\n\n if (!outcome.accepted) {\n // `strictNullChecks` is off repo-wide, so the union does not narrow on\n // its boolean discriminant; the cast says what the branch already knows.\n const refusal = outcome as Extract<MailProviderSendResult, { accepted: false }>\n const detail = String(refusal.detail ?? '')\n /*\n * A REQUEST TO SLOW DOWN IS NOT A STATEMENT ABOUT THIS RECIPIENT, so it\n * does not report 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 (refusal.rateLimited) {\n const retryAtMs = refusal.retryAtMs ?? providerRetryAtMs(null)\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 ...(refusal.status !== undefined ? { status: refusal.status } : {}),\n retryAtMs,\n detail: detail.slice(0, 500),\n }\n }\n console.error(`${label} failed`, refusal.status, detail)\n return {\n sent: false,\n reason: 'rejected',\n ...(refusal.status !== undefined ? { status: refusal.status } : {}),\n detail: detail.slice(0, 500),\n }\n }\n\n return {\n sent: true,\n id: (outcome as Extract<MailProviderSendResult, { accepted: true }>).id ?? null,\n }\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","EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS","getEmailDeliverabilityPreflight","bareSenderAddress","screenTenantMessage","providerRetryAtMs","mailProvider","mailProviderProblem","contextTag","context","value","String","trim","replace","slice","name","rateLimitedRetryAtMs","result","failure","reason","retryAtMs","Number","isFinite","sendFailureReason","sent","isDeferrableSendResult","emailSendPurpose","options","headers","priority","askDeliverabilityPreflight","request","label","preflight","timer","Promise","race","resolve","setTimeout","console","warn","unref","error","clearTimeout","messageFromName","given","fromName","identity","sendingIdentity","siteName","undefined","brandDefault","brandFromName","askOutboundScreen","workspace","audience","hostId","refusal","subject","fromAddress","from","replyTo","bodies","text","html","owed","Boolean","owedFor","releasedReviewId","detail","getEmailConfig","provider","id","missingSettings","process","env","USAGE_EMAIL_FROM","isEmailConfigured","length","applyFromName","angle","match","address","includes","normalizeRecipients","to","list","Array","isArray","map","filter","sendEmail","configuredFrom","identityRefusal","message","code","resolvedFrom","missing","problem","join","screenRefusal","sendingAddress","recipients","toLowerCase","purpose","sendingDomain","lastIndexOf","sendingSource","source","marketing","accountBanExempt","refused","held","stopped","Set","entry","email","remaining","has","unsubscribeUrl","oneClickUrl","gate","verdict","siteBase","capped","topicId","consentHostIds","consentAwaitsConfirmation","allowed","pooledRefusal","governor","count","Date","now","used","ceiling","body","callerTags","tags","some","tag","outcome","send","Object","keys","accepted","rateLimited","Math","max","round","status"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,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;AACzB,SACEC,yCAAyC,EACzCC,+BAA+B,QAG1B,4BAAwB;AAC/B,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,iBAAiB,QAAqC,qBAAiB;AACh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;QAC9D;IACF;AACF;AAEA,eAAe6E,UAAS"}
|
|
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 send seam. Every outbound application email in Aglyn goes through\n * here — invites, receipts, usage summaries, campaigns, staff alerts — and\n * everything that decides whether, as whom and to whom a message leaves is\n * decided here. The provider that then carries it is chosen by\n * `mail-providers.ts` and only carries it.\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'\nimport {\n EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS,\n getEmailDeliverabilityPreflight,\n type EmailDeliverabilityPreflightVerdict,\n type EmailSendPurpose,\n} from './email-deliverability'\nimport { bareSenderAddress } from './email-delivery-events'\nimport { screenTenantMessage } from './outbound-screen-gate'\nimport { providerRetryAtMs, type MailProviderSendResult } from './mail-provider'\nimport { mailProvider, mailProviderProblem } from './mail-providers'\n\n/**\n * A delivery tag: attribution the provider hands back on every delivery\n * event for the message, which is how a bounce finds its sender (AGL-268).\n */\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 the provider'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 * Blind copies (AGL-3699): addresses that receive the same message without\n * appearing on it — a review platform's invitation inbox copied on an order\n * email, for one. Never a second customer: a blind copy is not screened by\n * the deliverability preflight or the marketing gate, which ask about the\n * `to` recipients, so a marketing send refuses any.\n */\n bcc?: 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 * A SITE's mail leaves under the site's own name instead (AGL-3442): an\n * identity from `hostSendingIdentity` carries it, and it takes the place of\n * the org's branding default. A name of the caller's own, such as the\n * person writing a CRM email, still wins. See {@link messageFromName}.\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 * Delivers to an address whose account is BANNED (AGL-3420). A banned\n * account is sent nothing after its ban notice, by any sender; the lock\n * and lift notices themselves are the only mail that states this, and no\n * other sender may.\n */\n accountBanExempt?: boolean\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 `context` TAG on every send —\n * 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 * What the RECIPIENT did that makes this message owed to them (AGL-3356):\n * `order` — a receipt, a gift card, a shipping notice for something they\n * bought; `booking` — a confirmation, reminder or change to something they\n * booked; `account` — a password reset or sign-in link they asked for.\n *\n * The outbound phishing screen's SOFT rules never hold an owed message; a\n * lookalike link still does, because a receipt that links to a brand's\n * disguise is the disguise. Omitted — the default, and the one a forgotten\n * caller gets — the message is treated as merchant-authored and every\n * tier applies. A MARKETING message is never owed, whatever it declares.\n */\n owedFor?: 'order' | 'booking' | 'account'\n /**\n * A review row that the caller's own screen held and staff RELEASED for\n * exactly this content — a campaign put back on the clock, an automation\n * step whose hold was dismissed. The send seam's screen honors it only\n * after confirming, through the installed gate, that it is a release for\n * this site; naming a row is not a way past the screen.\n */\n releasedReviewId?: string | null\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 * Providers restrict tag values — to ASCII letters, digits, `_` and `-` at\n * the strictest — and one that rejects a value fails 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 the provider was asked 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 * The provider 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). The\n * provider asks for a slower pace when requests arrive faster than it\n * accepts them, and `status` is its answer (429 over HTTP) 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 /**\n * The recipient's domain takes no mail — no MX and no address record, or\n * an RFC 7505 null MX — so the message would only have bounced\n * (AGL-3328). Refused for every purpose, transactional included, before\n * the provider was called; the address is suppressed with a reason of its\n * own. Terminal: the preflight answers the same until the domain's DNS\n * changes, which it re-reads daily.\n */\n | 'undeliverable'\n /**\n * A BULK or cold message whose recipient sits behind a mail gateway that\n * refused this sending domain twice in thirty days and delivered nothing\n * (AGL-3328). Terminal for this message rather than deferrable: the hold\n * lifts when the gateway delivers again or the refusals age out, which is\n * not something a sweep's next beat can wait out. Mail the recipient asked\n * for is never held.\n */\n | 'gateway-held'\n /**\n * The site or workspace this message belongs to is under a full lockdown\n * (AGL-3356), carried in on its sending identity. Terminal for this\n * message: a sweep that holds work across a suspension skips the host\n * before it gets here, so a caller that reaches this refusal is one with\n * no way to come back, and retrying would only ask the same question.\n */\n | 'suspended'\n /**\n * The outbound phishing screen held this message for staff review, or\n * staff already rejected a message carrying the same signals from this\n * site (AGL-3356). Nothing was attempted. Terminal for this message:\n * `detail` names the `HS-…` reference, and once staff release the review\n * the site's next message carrying the same signals sends.\n */\n | 'held-for-review'\n\nexport type SendEmailResult =\n | { sent: true; id: string | null }\n | {\n sent: false\n reason: SendEmailFailureReason\n /** HTTP status, when the provider answered over HTTP. */\n status?: number\n /** The provider's error text 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 * 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\n/**\n * Who a message is for, as the deliverability preflight reads it\n * (AGL-3328): `bulk` for anything a control may already refuse — marketing\n * by either of its two marks, a campaign, a resumable sweep — and\n * `transactional` for the rest, which a gateway hold never touches.\n *\n * Derived from what a sender already declares, for the reason\n * `isMarketingMessage` is: a label callers had to remember would be\n * forgotten by the one that matters, and the permissive answer is the one a\n * forgotten caller gets.\n */\nexport function emailSendPurpose(\n options: Pick<SendEmailOptions, 'priority' | 'context' | 'headers'> & { marketing?: unknown },\n): EmailSendPurpose {\n if (isMarketingMessage(options)) return 'bulk'\n if (options.headers?.['List-Unsubscribe']) return 'bulk'\n return isRefusablePriority(resolveSendPriority(options.context, options.priority))\n ? 'bulk'\n : 'transactional'\n}\n\n/** The preflight's answer, or `null` when none is installed, it failed or it ran out of time. */\nasync function askDeliverabilityPreflight(\n request: Parameters<NonNullable<ReturnType<typeof getEmailDeliverabilityPreflight>>>[0],\n label: string,\n): Promise<EmailDeliverabilityPreflightVerdict | null> {\n const preflight = getEmailDeliverabilityPreflight()\n if (!preflight) return null\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n preflight(request),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n console.warn(`${label} deliverability preflight timed out — allowing`)\n resolve(null)\n }, EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS)\n ;(timer as { unref?: () => void })?.unref?.()\n }),\n ])\n } catch (error) {\n // Fails OPEN, the governor's posture: an outage on the control must not\n // become an outage on the mail.\n console.error(`${label} deliverability preflight failed — allowing`, error)\n return null\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\n/**\n * The display name a message leaves under (AGL-3442).\n *\n * A site's mail goes out under the site's own name — the business name its\n * emails render as `{{host.businessName}}`, else its display name, else the\n * org's branding default — which `hostSendingIdentity` resolves with the\n * address from the host and org documents it already reads. That is decided\n * here rather than at each sender because every site sender passes the org's\n * branding default as `fromName`, and to a visitor that is the platform's or\n * the agency's name rather than the business they dealt with. So the default\n * is replaced, and only the default: a name of the caller's own, such as the\n * person writing a CRM email, is still the name the message leaves under.\n *\n * Mail on any other identity — the platform's own, or a campaign's, which\n * resolves its identity without a host stamp and records the name its\n * composer chose — keeps the caller's `fromName` unchanged.\n */\nexport function messageFromName(\n options: Pick<SendEmailOptions, 'fromName' | 'sendingIdentity'>,\n): string | undefined {\n const given = String(options.fromName ?? '').trim()\n const identity = options.sendingIdentity\n const siteName = String(identity?.fromName ?? '').trim()\n if (!siteName) return given || undefined\n const brandDefault = String(identity?.brandFromName ?? '').trim()\n return given && given !== brandDefault ? given : siteName\n}\n\n/**\n * The send seam's half of the outbound phishing screen (AGL-3356): every\n * message a SITE sends whose identity carries the workspace\n * `hostSendingIdentity` stamped, through {@link screenTenantMessage} — the\n * pure screen, its tiers, and the installed review store. `null` when the\n * message may go; fails open, as that function documents.\n */\nexport async function askOutboundScreen(\n options: SendEmailOptions,\n label = 'email',\n): Promise<SendEmailResult | null> {\n const workspace = options.sendingIdentity?.workspace\n if (options.audience !== 'tenant' || !workspace?.hostId) return null\n const refusal = await screenTenantMessage(\n {\n workspace,\n subject: options.subject,\n // The name the message actually leaves under, so a site named after\n // somebody else's brand is screened on the `From:` line it would send.\n fromName: messageFromName(options) ?? null,\n // The resolved address, never anything the caller passed: the only\n // `From:` this message can leave on (AGL-3362).\n fromAddress: options.sendingIdentity?.from ?? null,\n replyTo: options.replyTo ?? null,\n bodies: [options.text, options.html],\n // A marketing message is never owed, whatever it declares.\n owed: Boolean(options.owedFor) && !isMarketingMessage(options),\n context: options.context ?? null,\n releasedReviewId: options.releasedReviewId ?? null,\n },\n label,\n )\n if (!refusal) return null\n console.warn(`${label} not sent — ${refusal.detail}`)\n return { sent: false, reason: 'held-for-review', detail: refusal.detail }\n}\n\nexport interface EmailConfig {\n /** The id of the provider mail is handed to — see `mail-providers.ts`. */\n provider: string\n /** Settings that provider still needs before it can send; empty when it can. */\n missingSettings: string[]\n /** The platform's own sender, `USAGE_EMAIL_FROM`. */\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 const provider = mailProvider()\n return {\n provider: provider.id,\n missingSettings: provider.missingSettings(),\n from: process.env.USAGE_EMAIL_FROM || undefined,\n }\n}\n\n/**\n * True when the provider has its settings and `USAGE_EMAIL_FROM` is 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 { missingSettings, from } = getEmailConfig()\n return !missingSettings.length && Boolean(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/**\n * Sends one email through the deployment's mail provider.\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 mail provider.\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n const provider = mailProvider()\n const configuredFrom = process.env.USAGE_EMAIL_FROM || undefined\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 provider/`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 // A suspension is not a DNS state, and the merchant reading the\n // failure has nothing to finish — so it is named for what it is.\n reason:\n identityRefusal.code === 'workspace-suspended'\n ? 'suspended'\n : '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 messageFromName(options),\n )\n\n const missing = [\n ...provider.missingSettings(),\n ...(from ? [] : ['USAGE_EMAIL_FROM']),\n ]\n if (missing.length) {\n /*\n * An operator who chose a provider this process does not have is told\n * so as an ERROR: that is not a deployment without mail, it is mail\n * somebody set up going nowhere. See `mail-providers.ts`.\n */\n const problem = mailProviderProblem(provider)\n if (problem) {\n console.error(`${label} not sent — ${problem}`)\n return { sent: false, reason: 'unconfigured', detail: problem }\n }\n console.warn(`${label} skipped — set ${missing.join(' and ')} to deliver mail`)\n return { sent: false, reason: 'unconfigured' }\n }\n\n let 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 OUTBOUND PHISHING SCREEN (AGL-3356).\n *\n * Asked for every message a SITE sends whose identity came through\n * `hostSendingIdentity` — which stamps the workspace on it — so one check\n * covers every tenant sender, first-party or marketplace, without any of\n * them calling it. See `outbound-screen-gate.ts`.\n *\n * Ahead of the preflight and every other gate: a message that must not\n * leave is decided before anything is spent on who receives it.\n */\n const screenRefusal = await askOutboundScreen(options, label)\n if (screenRefusal) return screenRefusal\n\n /*\n * THE DELIVERABILITY PREFLIGHT (AGL-3328).\n *\n * Asked before every other gate, because its refusal is the most final: a\n * recipient whose domain takes no mail is not a recipient this message or\n * any other can reach, and spending the marketing gate's reads or the\n * governor's hourly budget deciding more about them would be spending it\n * on a bounce. A recipient behind a gateway that refused this sending\n * domain twice is held — for bulk mail only; the purpose decides that,\n * and the preflight is told it.\n *\n * A multi-recipient message drops the refused and held recipients and goes\n * to the rest: one colleague's dead address must not stop the others'\n * notification.\n */\n const sendingAddress = bareSenderAddress(from)\n const preflight = await askDeliverabilityPreflight(\n {\n recipients: to.map((address) => address.toLowerCase()),\n purpose: emailSendPurpose(options),\n sendingDomain: sendingAddress ? sendingAddress.slice(sendingAddress.lastIndexOf('@') + 1) : null,\n sendingSource: options.sendingIdentity?.source ?? 'platform',\n context: options.context,\n hostId: options.marketing?.hostId ?? null,\n ...(options.accountBanExempt ? { accountBanExempt: true } : {}),\n },\n label,\n )\n if (preflight && (preflight.refused?.length || preflight.held?.length)) {\n const stopped = new Set(\n [...(preflight.refused ?? []), ...(preflight.held ?? [])].map((entry) =>\n String(entry?.email ?? '').toLowerCase(),\n ),\n )\n const remaining = to.filter((address) => !stopped.has(address.toLowerCase()))\n if (!remaining.length) {\n const refused = preflight.refused?.[0]\n const held = preflight.held?.[0]\n const detail = refused?.reason ?? held?.reason ?? 'The recipient cannot receive this message.'\n console.warn(`${label} not sent — ${detail}`)\n return { sent: false, reason: refused ? 'undeliverable' : 'gateway-held', detail }\n }\n console.warn(\n `${label} — ${to.length - remaining.length} of ${to.length} recipients ` +\n 'dropped by the deliverability preflight',\n )\n to = remaining\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 (normalizeRecipients(options.bcc ?? []).length) {\n // A blind copy of a marketing send is mail the gate never asked about.\n console.error(`${label} refused — a marketing send carries no blind copies`)\n return {\n sent: false,\n reason: 'no-recipient',\n detail: 'A marketing send carries no blind copies.',\n }\n }\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 consentHostIds: options.marketing.consentHostIds,\n consentAwaitsConfirmation: options.marketing.consentAwaitsConfirmation,\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 // Blind copies, de-duplicated against the visible recipients: an address\n // on both would receive the message twice.\n const visible = new Set(to.map((address) => address.toLowerCase()))\n const bcc = [\n ...new Set(\n normalizeRecipients(options.bcc ?? []).filter(\n (address) => !visible.has(address.toLowerCase()),\n ),\n ),\n ]\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 + bcc.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 // 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 the provider has\n // nothing to rewrite for click tracking — see `text-email-html.ts`. The\n // caller always wins: this can only fill a gap, never override a\n // designed template.\n const body = html || renderTextEmailHtml(text ?? '', options.subject)\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 ships\n // and a merchant-authored header is never silently replaced.\n const headers = {\n ...unsubscribeHeaders(oneClickUrl || unsubscribeUrl),\n ...(options.headers ?? {}),\n }\n // The caller's tags plus the `context` tag (AGL-2407). Caller-first so a\n // sender that stamps its own `context` keeps it: a tag list with two\n // entries of one name is not a shape worth discovering in production,\n // and the explicit one is the more specific.\n const callerTags = options.tags ?? []\n const tags = [\n ...callerTags,\n ...(callerTags.some((tag) => tag?.name === 'context')\n ? []\n : contextTag(options.context)),\n ]\n\n const outcome = await provider.send(\n {\n from,\n to,\n subject: options.subject,\n ...(text ? { text } : {}),\n ...(body ? { html: body } : {}),\n ...(Object.keys(headers).length ? { headers } : {}),\n ...(tags.length ? { tags } : {}),\n ...(options.replyTo ? { replyTo: options.replyTo } : {}),\n ...(bcc.length ? { bcc } : {}),\n },\n options.context,\n )\n\n if (!outcome.accepted) {\n // `strictNullChecks` is off repo-wide, so the union does not narrow on\n // its boolean discriminant; the cast says what the branch already knows.\n const refusal = outcome as Extract<MailProviderSendResult, { accepted: false }>\n const detail = String(refusal.detail ?? '')\n /*\n * A REQUEST TO SLOW DOWN IS NOT A STATEMENT ABOUT THIS RECIPIENT, so it\n * does not report 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 (refusal.rateLimited) {\n const retryAtMs = refusal.retryAtMs ?? providerRetryAtMs(null)\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 ...(refusal.status !== undefined ? { status: refusal.status } : {}),\n retryAtMs,\n detail: detail.slice(0, 500),\n }\n }\n console.error(`${label} failed`, refusal.status, detail)\n return {\n sent: false,\n reason: 'rejected',\n ...(refusal.status !== undefined ? { status: refusal.status } : {}),\n detail: detail.slice(0, 500),\n }\n }\n\n return {\n sent: true,\n id: (outcome as Extract<MailProviderSendResult, { accepted: true }>).id ?? null,\n }\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","EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS","getEmailDeliverabilityPreflight","bareSenderAddress","screenTenantMessage","providerRetryAtMs","mailProvider","mailProviderProblem","contextTag","context","value","String","trim","replace","slice","name","rateLimitedRetryAtMs","result","failure","reason","retryAtMs","Number","isFinite","sendFailureReason","sent","isDeferrableSendResult","emailSendPurpose","options","headers","priority","askDeliverabilityPreflight","request","label","preflight","timer","Promise","race","resolve","setTimeout","console","warn","unref","error","clearTimeout","messageFromName","given","fromName","identity","sendingIdentity","siteName","undefined","brandDefault","brandFromName","askOutboundScreen","workspace","audience","hostId","refusal","subject","fromAddress","from","replyTo","bodies","text","html","owed","Boolean","owedFor","releasedReviewId","detail","getEmailConfig","provider","id","missingSettings","process","env","USAGE_EMAIL_FROM","isEmailConfigured","length","applyFromName","angle","match","address","includes","normalizeRecipients","to","list","Array","isArray","map","filter","sendEmail","configuredFrom","identityRefusal","message","code","resolvedFrom","missing","problem","join","screenRefusal","sendingAddress","recipients","toLowerCase","purpose","sendingDomain","lastIndexOf","sendingSource","source","marketing","accountBanExempt","refused","held","stopped","Set","entry","email","remaining","has","unsubscribeUrl","oneClickUrl","bcc","gate","verdict","siteBase","capped","topicId","consentHostIds","consentAwaitsConfirmation","allowed","pooledRefusal","visible","governor","count","Date","now","used","ceiling","body","callerTags","tags","some","tag","outcome","send","Object","keys","accepted","rateLimited","Math","max","round","status"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,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;AACzB,SACEC,yCAAyC,EACzCC,+BAA+B,QAG1B,4BAAwB;AAC/B,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,iBAAiB,QAAqC,qBAAiB;AAChF,SAASC,YAAY,EAAEC,mBAAmB,QAAQ,sBAAkB;AAuKpE;;;;;;;;;;;;;;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,GAAGV,MAAM,OAAO,CAAC,EAAEyB,QAAQ+F,MAAM,EAAEnF;YACjD,OAAO;gBACL7C,MAAM;gBACNL,QAAQ;eACJsC,QAAQ+F,MAAM,KAAKtG,YAAY;gBAAEsG,QAAQ/F,QAAQ+F,MAAM;YAAC,IAAI,CAAC;gBACjEnF,QAAQA,OAAOvD,KAAK,CAAC,GAAG;;QAE5B;QAEA,OAAO;YACLU,MAAM;YACNgD,EAAE,GAAE,cAAA,AAACuE,QAAgEvE,EAAE,YAAnE,cAAuE;QAC7E;IACF,EAAE,OAAO9B,OAAO;;QACdH,QAAQG,KAAK,CAAC,GAAGV,MAAM,OAAO,CAAC,EAAEU;QACjC,OAAO;YACLlB,MAAM;YACNL,QAAQ;YACRkD,QAAQ1D,gBAAQ+B,yBAAD,AAACA,MAAiBoD,OAAO,oBAAIpD,OAAO5B,KAAK,CAAC,GAAG;QAC9D;IACF;AACF;AAEA,eAAe6E,UAAS"}
|
|
@@ -29,6 +29,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
29
29
|
* and `@nx/enforce-module-boundaries` refuses the edge. Same defaults, so a
|
|
30
30
|
* deployment that configures nothing sees exactly what it saw before.
|
|
31
31
|
*/ const SAMPLE_CONSOLE_ORIGIN = (process.env.NEXT_PUBLIC_CONSOLE_URL || '').trim().replace(/\/+$/, '') || 'https://app.aglyn.com';
|
|
32
|
+
/**
|
|
33
|
+
* The docs origin the getting-started emails' docs-link samples build on
|
|
34
|
+
* (AGL-3692), read the way the console's `DOCS_BASE_URL` reads it. Only a
|
|
35
|
+
* preview and test-send sample: the real send fills those links from the
|
|
36
|
+
* console's own docs origin.
|
|
37
|
+
*/ const SAMPLE_DOCS_ORIGIN = (process.env.NEXT_PUBLIC_DOCS_ORIGIN || process.env.NEXT_PUBLIC_AGLYN_DOCS_URL || '').trim().replace(/\/+$/, '') || 'https://docs.aglyn.com';
|
|
32
38
|
/**
|
|
33
39
|
* Mirrors `PLATFORM_SUPPORT_URL`'s precedence, including the step that makes
|
|
34
40
|
* the operator identity sufficient on its own: a configured support URL, else
|
|
@@ -51,6 +57,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
51
57
|
import { BRAND } from "@aglyn/shared-data-enums/aglyn";
|
|
52
58
|
import { EMAIL_NODE_ROOT_ID } from "./email-render.js";
|
|
53
59
|
import { RISK_NOTICE_SYSTEM_EMAIL_TEMPLATES } from "./risk-notice-emails.js";
|
|
60
|
+
import { retentionSystemEmailTemplates } from "./retention-emails.js";
|
|
54
61
|
/**
|
|
55
62
|
* Every system email Aglyn sends.
|
|
56
63
|
*
|
|
@@ -1500,9 +1507,12 @@ const BASE_SYSTEM_EMAIL_TEMPLATES = [
|
|
|
1500
1507
|
* footer it is.
|
|
1501
1508
|
*/ export const SYSTEM_EMAIL_TEMPLATES = // The risk notices (AGL-3368) are generated from their own catalog, one key
|
|
1502
1509
|
// per kind, so they live in `risk-notice-emails.ts` beside it.
|
|
1510
|
+
// The getting-started emails (AGL-3692) likewise live beside their own
|
|
1511
|
+
// notes on which preference governs them, in `retention-emails.ts`.
|
|
1503
1512
|
[
|
|
1504
1513
|
...BASE_SYSTEM_EMAIL_TEMPLATES,
|
|
1505
|
-
...RISK_NOTICE_SYSTEM_EMAIL_TEMPLATES
|
|
1514
|
+
...RISK_NOTICE_SYSTEM_EMAIL_TEMPLATES,
|
|
1515
|
+
...retentionSystemEmailTemplates(SAMPLE_CONSOLE_ORIGIN, SAMPLE_DOCS_ORIGIN)
|
|
1506
1516
|
].map((entry)=>_extends({}, entry, {
|
|
1507
1517
|
mergeTokens: [
|
|
1508
1518
|
...entry.mergeTokens,
|