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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +104 -0
  3. package/package.json +37 -0
  4. package/src/index.d.ts +37 -0
  5. package/src/index.js +46 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/email-delivery-events.d.ts +198 -0
  8. package/src/lib/email-delivery-events.js +310 -0
  9. package/src/lib/email-delivery-events.js.map +1 -0
  10. package/src/lib/email-health.d.ts +154 -0
  11. package/src/lib/email-health.js +264 -0
  12. package/src/lib/email-health.js.map +1 -0
  13. package/src/lib/email-media-src.d.ts +33 -0
  14. package/src/lib/email-media-src.js +113 -0
  15. package/src/lib/email-media-src.js.map +1 -0
  16. package/src/lib/email-merge.d.ts +31 -0
  17. package/src/lib/email-merge.js +36 -0
  18. package/src/lib/email-merge.js.map +1 -0
  19. package/src/lib/email-render.d.ts +114 -0
  20. package/src/lib/email-render.js +293 -0
  21. package/src/lib/email-render.js.map +1 -0
  22. package/src/lib/email-revenue-window.d.ts +55 -0
  23. package/src/lib/email-revenue-window.js +58 -0
  24. package/src/lib/email-revenue-window.js.map +1 -0
  25. package/src/lib/host-email-render.d.ts +99 -0
  26. package/src/lib/host-email-render.js +126 -0
  27. package/src/lib/host-email-render.js.map +1 -0
  28. package/src/lib/host-sender.d.ts +86 -0
  29. package/src/lib/host-sender.js +131 -0
  30. package/src/lib/host-sender.js.map +1 -0
  31. package/src/lib/marketing-send.d.ts +466 -0
  32. package/src/lib/marketing-send.js +459 -0
  33. package/src/lib/marketing-send.js.map +1 -0
  34. package/src/lib/platform-sending-domain.d.ts +362 -0
  35. package/src/lib/platform-sending-domain.js +697 -0
  36. package/src/lib/platform-sending-domain.js.map +1 -0
  37. package/src/lib/received-email.d.ts +86 -0
  38. package/src/lib/received-email.js +124 -0
  39. package/src/lib/received-email.js.map +1 -0
  40. package/src/lib/send-ceilings.d.ts +394 -0
  41. package/src/lib/send-ceilings.js +341 -0
  42. package/src/lib/send-ceilings.js.map +1 -0
  43. package/src/lib/send-email.d.ts +385 -0
  44. package/src/lib/send-email.js +586 -0
  45. package/src/lib/send-email.js.map +1 -0
  46. package/src/lib/send-rate.d.ts +298 -0
  47. package/src/lib/send-rate.js +310 -0
  48. package/src/lib/send-rate.js.map +1 -0
  49. package/src/lib/sender-reputation.d.ts +357 -0
  50. package/src/lib/sender-reputation.js +392 -0
  51. package/src/lib/sender-reputation.js.map +1 -0
  52. package/src/lib/sending-domain.d.ts +744 -0
  53. package/src/lib/sending-domain.js +798 -0
  54. package/src/lib/sending-domain.js.map +1 -0
  55. package/src/lib/sending-mailbox.d.ts +132 -0
  56. package/src/lib/sending-mailbox.js +192 -0
  57. package/src/lib/sending-mailbox.js.map +1 -0
  58. package/src/lib/stored-email-nodes.d.ts +38 -0
  59. package/src/lib/stored-email-nodes.js +78 -0
  60. package/src/lib/stored-email-nodes.js.map +1 -0
  61. package/src/lib/svix-signature.d.ts +38 -0
  62. package/src/lib/svix-signature.js +55 -0
  63. package/src/lib/svix-signature.js.map +1 -0
  64. package/src/lib/system-email-catalog.d.ts +170 -0
  65. package/src/lib/system-email-catalog.js +828 -0
  66. package/src/lib/system-email-catalog.js.map +1 -0
  67. package/src/lib/tenant-email-catalog.d.ts +78 -0
  68. package/src/lib/tenant-email-catalog.js +452 -0
  69. package/src/lib/tenant-email-catalog.js.map +1 -0
  70. package/src/lib/text-email-html.d.ts +32 -0
  71. package/src/lib/text-email-html.js +119 -0
  72. package/src/lib/text-email-html.js.map +1 -0
@@ -0,0 +1,459 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * MARKETING MAIL — the policy half.
18
+ *
19
+ * A message is MARKETING when a merchant's audience receives it because the
20
+ * merchant decided to mail them, rather than because the recipient just did
21
+ * something. Campaigns are the obvious case; so are a member post, an
22
+ * abandoned-cart reminder, a back-in-stock alert and a merchant-authored
23
+ * workflow email.
24
+ *
25
+ * ## The three things marketing mail owes, and where they were
26
+ *
27
+ * Before this module they were owed by every bulk sender and discharged by
28
+ * exactly one of them:
29
+ *
30
+ * 1. **An unsubscribe mechanism.** `List-Unsubscribe` plus
31
+ * `List-Unsubscribe-Post` is what Gmail's and Yahoo's bulk-sender rules
32
+ * ask for, and a visible link is what CAN-SPAM asks for. The campaign
33
+ * sender adds both; the shared `sendEmail` added neither, so four
34
+ * merchant-triggered bulk paths mailed people with no way out.
35
+ * 2. **A suppression check.** An address that hard-bounced or pressed
36
+ * "report spam" must not be mailed again. Those four paths consulted
37
+ * neither list.
38
+ * 3. **A ceiling on how much one person receives.** There was none at any
39
+ * scope, so a single recipient could take a campaign, a cart reminder, a
40
+ * restock alert, a member post and a workflow email in one day.
41
+ *
42
+ * All three are the same shape — a question asked once, per recipient, at the
43
+ * moment a marketing message is about to leave — so they are one seam rather
44
+ * than three, and `sendEmail` asks it whenever a caller declares
45
+ * {@link MarketingSendContext}.
46
+ *
47
+ * ## Why the gate is injected rather than imported
48
+ *
49
+ * The same split as the send-rate governor beside it. Answering the question
50
+ * needs Firestore: two suppression collections and a per-recipient counter.
51
+ * The durable half therefore lives in `@aglyn/tenant-data-admin`, which is
52
+ * the only layer that may hold the Admin SDK — this library is `scope:shared`
53
+ * and the dependency edge already runs the other way. So the gate reaches
54
+ * `sendEmail` through {@link setMarketingSendGate}.
55
+ *
56
+ * Nothing installed means UNGATED, not refused: a unit test, a preview build
57
+ * and a self-host that never installs one all keep sending. A control that
58
+ * turns its own absence into an outage is worse than the burst it guards.
59
+ *
60
+ * ## Why this file holds no crypto and mints no URL
61
+ *
62
+ * The unsubscribe URL is an HMAC over the recipient's address, and
63
+ * `node:crypto` cannot ride into a browser bundle — console components import
64
+ * this library's barrel. The gate returns the minted URL instead, from the
65
+ * server layer that already signs one.
66
+ */ /*
67
+ * `send-rate.ts` imports nothing, so this cannot be half of a cycle — which
68
+ * matters, because this module is imported by `send-email.ts` alongside that
69
+ * one and a cycle between the two would resolve differently under swc and
70
+ * jest.
71
+ */ import { escapeEmailHtml } from "./email-render.js";
72
+ import { resolveSendPriority } from "./send-rate.js";
73
+ /**
74
+ * Whether a message is MARKETING, derived from what it already carries.
75
+ *
76
+ * ## Nothing new to remember, on purpose
77
+ *
78
+ * The obvious design is a `kind: 'marketing' | 'transactional'` option on
79
+ * `sendEmail`. It is rejected for the reason the `from` override was deleted
80
+ * and the `context` tag was derived rather than threaded: twenty call sites
81
+ * cannot each be relied on to set a field, and the twenty-first is the one that
82
+ * does not. The consequence of forgetting here is a merchant's campaign leaving
83
+ * on the pooled identity that carries every other site's password resets — a
84
+ * failure nobody sees until the pool stops delivering.
85
+ *
86
+ * So the answer is read off two things a marketing send is ALREADY obliged to
87
+ * carry, neither of which is optional and neither of which was added for this:
88
+ *
89
+ * 1. **`marketing`** — the context object. A message that declares it gets the
90
+ * RFC 8058 header pair, the suppression check and the frequency cap, so a
91
+ * marketing sender cannot omit it and still be correct; it would be shipping
92
+ * mail with no unsubscribe link. Four of the five marketing senders in the
93
+ * tree take this arm.
94
+ * 2. **`priority === 'campaign'`** — which `resolveSendPriority` derives from
95
+ * `context: 'campaign'`. The campaign sender mints its own unsubscribe
96
+ * headers upstream and so passes no `marketing` context, but it is the one
97
+ * sender that cannot avoid this label: the hourly governor is allowed to
98
+ * refuse a campaign, and a campaign that hid from the priority would be
99
+ * hiding from that too.
100
+ *
101
+ * A sender would have to defeat BOTH — no unsubscribe context and no campaign
102
+ * priority — to reach the pool with promotional mail, and a message in that
103
+ * state is already broken in ways its author would notice.
104
+ *
105
+ * ## Polarity
106
+ *
107
+ * A message matching neither is transactional, which is the permissive answer,
108
+ * and that is deliberate — the same choice `resolveSendPriority` makes for the
109
+ * same reason. Enumerating what is RESTRICTED means a forgotten caller sends a
110
+ * receipt that goes out. Enumerating what is PERMITTED means a forgotten caller
111
+ * drops one, and a dropped password reset is the failure you learn about from a
112
+ * support ticket.
113
+ */ export function isMarketingMessage(options) {
114
+ var _ref;
115
+ if (options == null ? void 0 : options.marketing) return true;
116
+ // `context` is consulted only through the same rule the governor uses, so a
117
+ // context that stops meaning "campaign" cannot leave the two disagreeing.
118
+ return resolveSendPriority((_ref = options == null ? void 0 : options.context) != null ? _ref : undefined, (options == null ? void 0 : options.priority) || undefined) === 'campaign';
119
+ }
120
+ let installedGate = null;
121
+ /** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */ export function setMarketingSendGate(gate) {
122
+ installedGate = gate;
123
+ }
124
+ /** The installed gate, or null when nothing has been installed. */ export function getMarketingSendGate() {
125
+ return installedGate;
126
+ }
127
+ /** Test seam: forget any installed gate. */ export function resetMarketingSendGateForTests() {
128
+ installedGate = null;
129
+ }
130
+ /**
131
+ * The rolling window a frequency cap counts over. One day, because that is
132
+ * the unit a recipient experiences ("this shop mailed me four times today")
133
+ * and the unit every published vendor cap is expressed in.
134
+ */ export const MARKETING_FREQUENCY_WINDOW_MS = 86400000;
135
+ /**
136
+ * How many marketing messages one person may receive from one site inside the
137
+ * window, by default.
138
+ *
139
+ * **A runaway guard, not a marketing policy.** It is deliberately above what
140
+ * an ordinary merchant produces: the worst legitimate day is a campaign plus
141
+ * a cart reminder plus a restock alert plus a member post, which is four. Set
142
+ * lower and the first thing it would refuse is a real message somebody meant
143
+ * to send; set higher and it stops describing a ceiling at all. What it does
144
+ * remove is the unbounded case — a member post that mails 200 subscribers per
145
+ * click with no limit on clicks, and a workflow whose email step fires on
146
+ * every anonymous form submission.
147
+ *
148
+ * The same number for every plan. This is a deliverability control on a
149
+ * shared sending domain, so it protects every tenant from every other tenant
150
+ * and cannot be something one plan buys its way past.
151
+ */ export const MARKETING_FREQUENCY_DEFAULT_PER_WINDOW = 5;
152
+ /** Floor and ceiling on a configured cap — a typo guard, not a policy. */ export const MARKETING_FREQUENCY_MIN_PER_WINDOW = 1;
153
+ export const MARKETING_FREQUENCY_MAX_PER_WINDOW = 1000;
154
+ /**
155
+ * The live cap.
156
+ *
157
+ * Read from the environment so a self-host operator can set their own —
158
+ * `docs/design` states that every dependency is configurable — and read per
159
+ * call rather than captured at module load, matching `getEmailConfig`: these
160
+ * run in serverless handlers where the module may be evaluated during a build.
161
+ *
162
+ * An unparseable or out-of-range value falls back to the default rather than
163
+ * throwing or disabling the cap. A control that a typo can switch off is not
164
+ * a control.
165
+ */ export function marketingFrequencyCap() {
166
+ const raw = Number(process.env.AGLYN_EMAIL_MARKETING_CAP_PER_DAY);
167
+ if (!Number.isFinite(raw)) return MARKETING_FREQUENCY_DEFAULT_PER_WINDOW;
168
+ const whole = Math.floor(raw);
169
+ if (whole < MARKETING_FREQUENCY_MIN_PER_WINDOW || whole > MARKETING_FREQUENCY_MAX_PER_WINDOW) {
170
+ return MARKETING_FREQUENCY_DEFAULT_PER_WINDOW;
171
+ }
172
+ return whole;
173
+ }
174
+ /**
175
+ * Whether one more message fits, given what this person has already received.
176
+ *
177
+ * Pure, so the decision is testable without a Firestore harness — the same
178
+ * split `emailSendRateVerdict` makes for the platform hour.
179
+ *
180
+ * @param recentSendsAtMs every marketing send to this person from this site,
181
+ * newest or oldest first, in any order.
182
+ * @returns the verdict and the trimmed window, so the caller writes back only
183
+ * what still counts instead of growing the record forever.
184
+ */ export function marketingFrequencyVerdict(recentSendsAtMs, nowMs, cap = marketingFrequencyCap()) {
185
+ const floor = nowMs - MARKETING_FREQUENCY_WINDOW_MS;
186
+ const inWindow = recentSendsAtMs.filter((at)=>Number.isFinite(at) && at > floor && at <= nowMs).sort((a, b)=>a - b)// Keep the NEWEST when a record has somehow grown past the cap. The
187
+ // oldest entries are the ones about to leave the window anyway, so
188
+ // dropping them loses the least information about when this person is
189
+ // mailable again.
190
+ .slice(-Math.max(cap, MARKETING_FREQUENCY_MIN_PER_WINDOW));
191
+ return {
192
+ allowed: inWindow.length < cap,
193
+ used: inWindow.length,
194
+ cap,
195
+ inWindow
196
+ };
197
+ }
198
+ /*==========================================
199
+ * ENGAGEMENT-BASED SUNSETTING.
200
+ *
201
+ * Stop mailing an address that has gone quiet. The whole design fits in one
202
+ * sentence and three refusals it must never become.
203
+ *
204
+ * ## ⛔ It refuses a SEND. It never reduces a person.
205
+ *
206
+ * `over-limit.ts` states the rule for capacity and this is the same
207
+ * instrument pointed at attention rather than at count. A sunset does NOT
208
+ * unsubscribe anybody, does NOT remove them from a list, does NOT delete a
209
+ * contact and does NOT write a suppression. Every one of those would be a
210
+ * ceiling performing a deletion, and every one of them is irreversible in a
211
+ * way the condition that triggered it is not.
212
+ *
213
+ * ## It is reversible without anybody doing anything
214
+ *
215
+ * The only state is two timestamps: when this site first mailed this person,
216
+ * and when this person last engaged with our mail. A person who opens or
217
+ * clicks anything moves the second one, and the very next send finds them
218
+ * inside the window and mailable. Nothing has to be undone, because nothing
219
+ * was done.
220
+ *
221
+ * ## The three ways it could refuse somebody it should not, and the guards
222
+ *
223
+ * 1. **A brand-new subscriber has no engagement yet.** So the window is
224
+ * measured from when we STARTED mailing them, and somebody we have not
225
+ * been mailing for longer than the window is never refused, however
226
+ * little they have engaged.
227
+ * 2. **We might have no record at all.** An unknown `firstSentAtMs` refuses
228
+ * nobody. Missing evidence is not evidence of absence, and the reading
229
+ * that mails somebody once more is the recoverable one.
230
+ * 3. **A campaign is a reviewed act with its recipient count on screen.**
231
+ * Sunsetting yields to it exactly as the frequency ceiling does, through
232
+ * the same `capped` flag, so the number a merchant read before pressing
233
+ * Send stays true. It governs the automated paths, which fire with no
234
+ * human present.
235
+ *
236
+ * ## Opens are a weak signal and this leans on the broader one anyway
237
+ *
238
+ * The industry lesson is to sunset on clicks, because Apple's Mail Privacy
239
+ * Protection prefetches images and inflates opens. That argument is about
240
+ * choosing an audience. This is a refusal, and for a refusal the weaker,
241
+ * more generous signal is the correct one: counting an open as engagement
242
+ * refuses FEWER people. The audience rules
243
+ * (`DynamicListEngagement`) keep opens and clicks apart so a merchant
244
+ * segmenting on engagement can lean on clicks; this deliberately does not.
245
+ *=========================================*/ /** Floor and ceiling on a configured sunset window — a typo guard. */ export const MARKETING_SUNSET_MIN_DAYS = 30;
246
+ export const MARKETING_SUNSET_MAX_DAYS = 3650;
247
+ /**
248
+ * The window, in days, or 0 for OFF.
249
+ *
250
+ * **Off unless an operator turns it on**, and that default is the honest one:
251
+ * no compared vendor automates this, so a platform that silently stopped
252
+ * mailing a merchant's quiet subscribers would be doing something none of
253
+ * their previous tools did and none of their recipients asked for. The value
254
+ * is a number of days rather than a boolean because the only interesting
255
+ * question about a sunset is where it starts.
256
+ *
257
+ * Read per call rather than captured at module load, matching the frequency
258
+ * cap beside it: these run in serverless handlers where the module may be
259
+ * evaluated during a build.
260
+ *
261
+ * An unparseable or out-of-range value reads as OFF rather than falling back
262
+ * to a default. This is the opposite of {@link marketingFrequencyCap}'s
263
+ * handling and deliberately so — a typo there weakens a guard that is on by
264
+ * default, and a typo here would ENABLE a refusal nobody asked for.
265
+ */ export function marketingSunsetDays() {
266
+ const raw = Number(process.env.AGLYN_EMAIL_SUNSET_AFTER_DAYS);
267
+ if (!Number.isFinite(raw)) return 0;
268
+ const whole = Math.floor(raw);
269
+ if (whole < MARKETING_SUNSET_MIN_DAYS || whole > MARKETING_SUNSET_MAX_DAYS) {
270
+ return 0;
271
+ }
272
+ return whole;
273
+ }
274
+ /**
275
+ * Whether this person has gone quiet for longer than the window.
276
+ *
277
+ * Pure, so the decision is testable without a Firestore harness — the same
278
+ * split {@link marketingFrequencyVerdict} makes.
279
+ *
280
+ * @param days 0 disables the sunset entirely and this always allows.
281
+ */ export function marketingSunsetVerdict(facts, nowMs, days = marketingSunsetDays()) {
282
+ var _facts_firstSentAtMs, _facts_lastEngagedAtMs;
283
+ if (!days || days <= 0) {
284
+ return {
285
+ allowed: true,
286
+ days: 0,
287
+ quietForDays: null
288
+ };
289
+ }
290
+ const floor = nowMs - days * 86400000;
291
+ const first = Number((_facts_firstSentAtMs = facts.firstSentAtMs) != null ? _facts_firstSentAtMs : 0);
292
+ // Guard 1 and 2 together: no record, or a relationship younger than the
293
+ // window, allows. A person cannot have been quiet for longer than we have
294
+ // been mailing them.
295
+ if (!Number.isFinite(first) || first <= 0 || first >= floor) {
296
+ return {
297
+ allowed: true,
298
+ days,
299
+ quietForDays: null
300
+ };
301
+ }
302
+ const engaged = Number((_facts_lastEngagedAtMs = facts.lastEngagedAtMs) != null ? _facts_lastEngagedAtMs : 0);
303
+ if (Number.isFinite(engaged) && engaged > 0 && engaged >= floor) {
304
+ return {
305
+ allowed: true,
306
+ days,
307
+ quietForDays: null
308
+ };
309
+ }
310
+ const since = Number.isFinite(engaged) && engaged > 0 ? engaged : first;
311
+ return {
312
+ allowed: false,
313
+ days,
314
+ quietForDays: Math.floor((nowMs - since) / 86400000)
315
+ };
316
+ }
317
+ /** The default: no expressed preference, so only the platform ceiling binds. */ export const DEFAULT_MARKETING_CADENCE = 'all';
318
+ /**
319
+ * The minimum gap each choice asks for, in millis.
320
+ *
321
+ * Calendar-naive on purpose. "At most one a week" is a promise about pace,
322
+ * and honoring it as seven days from the last message is both what the words
323
+ * say and what a recipient can check; anchoring it to a calendar week would
324
+ * let two messages land on a Sunday and a Monday and still be "one a week".
325
+ */ export const MARKETING_CADENCE_INTERVAL_MS = {
326
+ all: 0,
327
+ daily: 86400000,
328
+ weekly: 7 * 86400000,
329
+ monthly: 30 * 86400000
330
+ };
331
+ /** How each choice reads, wherever one is named to a person or an operator. */ export const MARKETING_CADENCE_LABELS = {
332
+ all: 'As they come',
333
+ daily: 'At most one a day',
334
+ weekly: 'At most one a week',
335
+ monthly: 'At most one a month'
336
+ };
337
+ /**
338
+ * Coerces a stored or submitted value to a cadence.
339
+ *
340
+ * Everything unrecognized becomes {@link DEFAULT_MARKETING_CADENCE}. The
341
+ * direction matters and is the opposite of the consent policy's: a malformed
342
+ * consent value must not become a way to switch enforcement off, because its
343
+ * failure mode is mail to somebody who declined. A malformed cadence falling
344
+ * to `'monthly'` would withhold mail from everybody whose record got
345
+ * corrupted, and nobody asked for that either — so an unreadable preference
346
+ * reads as no preference, and the person keeps whatever the ceiling allows.
347
+ */ export function normalizeMarketingCadence(value) {
348
+ return value === 'daily' || value === 'weekly' || value === 'monthly' ? value : DEFAULT_MARKETING_CADENCE;
349
+ }
350
+ /**
351
+ * Whether enough time has passed for one more message at this pace.
352
+ *
353
+ * Pure, so the rule can be asserted without a Firestore harness — the same
354
+ * split {@link marketingFrequencyVerdict} makes.
355
+ *
356
+ * @param lastSentAtMs when this site last sent this person marketing mail, or
357
+ * `null` for somebody it has never mailed. Never mailed always allows:
358
+ * a cadence is a gap between messages and there is no first gap.
359
+ * @returns the verdict and, on a refusal, the instant the next message may go
360
+ * — so a caller that defers has something to defer UNTIL rather than
361
+ * a retry loop that discovers the answer by asking again.
362
+ */ export function marketingCadenceVerdict(cadence, lastSentAtMs, nowMs) {
363
+ var _MARKETING_CADENCE_INTERVAL_MS_cadence;
364
+ const interval = (_MARKETING_CADENCE_INTERVAL_MS_cadence = MARKETING_CADENCE_INTERVAL_MS[cadence]) != null ? _MARKETING_CADENCE_INTERVAL_MS_cadence : 0;
365
+ const last = Number(lastSentAtMs);
366
+ if (!interval || !Number.isFinite(last) || last <= 0) {
367
+ return {
368
+ allowed: true,
369
+ cadence,
370
+ nextAllowedAtMs: nowMs
371
+ };
372
+ }
373
+ const nextAllowedAtMs = last + interval;
374
+ /*
375
+ * A stored instant in the FUTURE allows rather than refusing until it
376
+ * passes. Clocks disagree across processes and a record written a few
377
+ * seconds ahead would otherwise hold a recipient's mail for a whole
378
+ * interval, which is a much larger error than the one it would prevent.
379
+ */ if (last > nowMs) return {
380
+ allowed: true,
381
+ cadence,
382
+ nextAllowedAtMs: nowMs
383
+ };
384
+ return {
385
+ allowed: nowMs >= nextAllowedAtMs,
386
+ cadence,
387
+ nextAllowedAtMs
388
+ };
389
+ }
390
+ /**
391
+ * The RFC 8058 header pair.
392
+ *
393
+ * Both or neither: `List-Unsubscribe` alone does not satisfy the bulk-sender
394
+ * rules, and `List-Unsubscribe-Post` without a URL to post to advertises a
395
+ * verb nothing serves.
396
+ */ export function unsubscribeHeaders(unsubscribeUrl) {
397
+ if (!unsubscribeUrl) return {};
398
+ return {
399
+ 'List-Unsubscribe': `<${unsubscribeUrl}>`,
400
+ 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click'
401
+ };
402
+ }
403
+ /**
404
+ * What the visible opt-out is CALLED, in every part of every message.
405
+ *
406
+ * The link opens the preference page, where leaving one stream is a choice
407
+ * alongside leaving all of them — and a footer that says only "Unsubscribe"
408
+ * is the only place a recipient would have learned that, so it never gets
409
+ * said. The word "unsubscribe" stays in the line because that is what a
410
+ * recipient scans a footer for.
411
+ *
412
+ * Named once and shared with `renderRecipientEmail`, which writes this same
413
+ * line into a campaign's text part: two spellings of one sentence is how the
414
+ * idempotency checks below come to append a second footer to a message that
415
+ * already had one.
416
+ */ export const UNSUBSCRIBE_FOOTER_LABEL = 'Choose which emails you get, or unsubscribe';
417
+ /**
418
+ * The visible opt-out, appended to the plain-text part.
419
+ *
420
+ * The headers are for the mailbox provider; this is for the person. CAN-SPAM
421
+ * asks for a mechanism the recipient can see and use, and a header is neither
422
+ * — most clients render no control for it at all unless the sender's domain
423
+ * reputation is high enough for the provider to offer one.
424
+ *
425
+ * Idempotent by URL: a body that already carries the link is returned
426
+ * untouched, so a sender that writes its own footer does not get two.
427
+ */ export function appendUnsubscribeText(text, unsubscribeUrl) {
428
+ if (!unsubscribeUrl || text && text.includes(unsubscribeUrl)) return text;
429
+ return `${text != null ? text : ''}\n\n—\n${UNSUBSCRIBE_FOOTER_LABEL}: ${unsubscribeUrl}`;
430
+ }
431
+ /**
432
+ * The same visible opt-out for the HTML part.
433
+ *
434
+ * Appended to whatever the sender produced rather than woven into it, because
435
+ * the HTML may be a merchant-designed template this module knows nothing
436
+ * about. A designed template that already renders `{{unsubscribeUrl}}`
437
+ * carries the URL, so the check below leaves it alone and the merchant's own
438
+ * placement wins.
439
+ *
440
+ * ⚠️ That check has to look for the ESCAPED URL as well. A signed opt-out
441
+ * link carries `&` between its query parameters, and a renderer putting it
442
+ * into an `href` escapes it — so `renderEmailHtml` emits `…&amp;sig=…` and a
443
+ * plain `includes` of the unescaped URL matches nothing. Every designed
444
+ * template in the product goes through that renderer, which means the
445
+ * merchants who DID place the token were the ones getting two footers.
446
+ *
447
+ * Styles are inline and literal because this is email HTML: mail clients
448
+ * strip `<style>` blocks and support no CSS variables, so a theme token
449
+ * cannot reach the wire.
450
+ */ export function appendUnsubscribeHtml(html, unsubscribeUrl) {
451
+ if (!unsubscribeUrl) return html;
452
+ if (html && (html.includes(unsubscribeUrl) || html.includes(escapeEmailHtml(unsubscribeUrl)))) {
453
+ return html;
454
+ }
455
+ const footer = '<div style="margin:24px auto 0;max-width:600px;padding:16px 24px;' + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto," + 'Helvetica,Arial,sans-serif;font-size:12px;line-height:1.5;' + 'color:#616161;text-align:center">' + `<a href="${escapeEmailHtml(unsubscribeUrl)}" style="color:#616161">` + `${UNSUBSCRIBE_FOOTER_LABEL}</a>` + '</div>';
456
+ return `${html != null ? html : ''}${footer}`;
457
+ }
458
+
459
+ //# sourceMappingURL=marketing-send.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/marketing-send.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 * MARKETING MAIL — the policy half.\n *\n * A message is MARKETING when a merchant's audience receives it because the\n * merchant decided to mail them, rather than because the recipient just did\n * something. Campaigns are the obvious case; so are a member post, an\n * abandoned-cart reminder, a back-in-stock alert and a merchant-authored\n * workflow email.\n *\n * ## The three things marketing mail owes, and where they were\n *\n * Before this module they were owed by every bulk sender and discharged by\n * exactly one of them:\n *\n * 1. **An unsubscribe mechanism.** `List-Unsubscribe` plus\n * `List-Unsubscribe-Post` is what Gmail's and Yahoo's bulk-sender rules\n * ask for, and a visible link is what CAN-SPAM asks for. The campaign\n * sender adds both; the shared `sendEmail` added neither, so four\n * merchant-triggered bulk paths mailed people with no way out.\n * 2. **A suppression check.** An address that hard-bounced or pressed\n * \"report spam\" must not be mailed again. Those four paths consulted\n * neither list.\n * 3. **A ceiling on how much one person receives.** There was none at any\n * scope, so a single recipient could take a campaign, a cart reminder, a\n * restock alert, a member post and a workflow email in one day.\n *\n * All three are the same shape — a question asked once, per recipient, at the\n * moment a marketing message is about to leave — so they are one seam rather\n * than three, and `sendEmail` asks it whenever a caller declares\n * {@link MarketingSendContext}.\n *\n * ## Why the gate is injected rather than imported\n *\n * The same split as the send-rate governor beside it. Answering the question\n * needs Firestore: two suppression collections and a per-recipient counter.\n * The durable half therefore lives in `@aglyn/tenant-data-admin`, which is\n * the only layer that may hold the Admin SDK — this library is `scope:shared`\n * and the dependency edge already runs the other way. So the gate reaches\n * `sendEmail` through {@link setMarketingSendGate}.\n *\n * Nothing installed means UNGATED, not refused: a unit test, a preview build\n * and a self-host that never installs one all keep sending. A control that\n * turns its own absence into an outage is worse than the burst it guards.\n *\n * ## Why this file holds no crypto and mints no URL\n *\n * The unsubscribe URL is an HMAC over the recipient's address, and\n * `node:crypto` cannot ride into a browser bundle — console components import\n * this library's barrel. The gate returns the minted URL instead, from the\n * server layer that already signs one.\n */\n\n/*\n * `send-rate.ts` imports nothing, so this cannot be half of a cycle — which\n * matters, because this module is imported by `send-email.ts` alongside that\n * one and a cycle between the two would resolve differently under swc and\n * jest.\n */\nimport { escapeEmailHtml } from './email-render'\nimport { resolveSendPriority, type EmailSendPriority } from './send-rate'\n\n/** What a marketing send declares about itself. */\nexport interface MarketingSendContext {\n /** The site whose audience this is. Both suppression lists key on it. */\n hostId: string\n /**\n * The site's public origin, for the unsubscribe link.\n *\n * The CALLER resolves it — through `hostPublicOrigin`, from the host\n * document — because the shared subdomain policy lives in the framework\n * library and neither this module nor the gate may import it. Empty when a\n * host has no custom domain and no subdomain, which is a site nobody can\n * reach; the send then carries no unsubscribe URL and says so in the logs\n * rather than minting a link that resolves to nothing.\n */\n siteBase: string\n /**\n * An unsubscribe URL the caller has already minted, and the campaign it\n * belongs to.\n *\n * The campaign sender builds its own, because the same URL has to reach the\n * designed template as an `{{unsubscribeUrl}}` merge value long before the\n * message is handed over. Supplied, it is used verbatim and nothing is\n * minted — one link per message, whoever made it.\n */\n unsubscribeUrl?: string\n /**\n * The `List-Unsubscribe` URL, when the caller minted its own pair.\n *\n * Separate from {@link unsubscribeUrl} because the two are read by\n * different readers. This one is POSTed by a mailbox provider with nobody\n * present, so it must name the route that writes on POST; the other is\n * clicked by a person, so it names the preference page. Absent, the header\n * falls back to `unsubscribeUrl` — which is right for a caller that minted\n * only one link, and wrong only for one that minted a page and did not say\n * so.\n */\n oneClickUrl?: string\n /**\n * Whether a frequency cap may refuse this message.\n *\n * `false` for a campaign. A campaign is a merchant's deliberate, reviewed\n * act with a recipient count on screen before they press Send; a cap that\n * silently removed people from it would make that number a lie, and a\n * one-shot send has nowhere to hold the remainder for later. So a campaign\n * COUNTS toward what a recipient has received — it is most of the load a\n * person feels — and yields the refusal to the automated paths, which fire\n * with no human present and are the ones that stack.\n *\n * Defaults to true: an unmarked caller is a machine.\n */\n capped?: boolean\n /**\n * The STREAM this message belongs to, so a recipient who left that stream\n * is not mailed it.\n *\n * ## Absent refuses nobody, and that is the whole safety property\n *\n * A topic opt-out governs marketing STREAMS — \"Promotions and offers\",\n * \"Newsletter\". It is not a thing anybody can untick off a receipt, a\n * password reset or a booking confirmation, and a gate that refused those\n * on a topic preference would be the failure mode this control is most\n * capable of causing. Two guards make that unreachable rather than\n * unlikely:\n *\n * 1. transactional mail declares no `marketing` context at all, so it\n * never reaches the gate; and\n * 2. a marketing caller that names no stream gets no topic refusal here.\n * `filterTopicSendable` already reads an empty topic that way — there\n * is no stream to have left — and this preserves it rather than\n * defaulting to one.\n *\n * So the check binds exactly the senders that declare what they are, which\n * is the same polarity `isMarketingMessage` chose: enumerate what is\n * restricted, and a forgotten caller sends rather than silently drops.\n *\n * ## Why the gate asks it at all, when the consent split does not\n *\n * The two used to travel together in `email-flow-gate.ts`, and they are not\n * the same kind of fact. The consent split is the ORG's policy over its own\n * audience, which is why it stays a caller-side question. A topic opt-out\n * is the RECIPIENT talking to the platform, recorded by the same preference\n * page that records their cadence and reached by the same\n * `List-Unsubscribe` link — so it belongs with the suppression and cadence\n * checks, at the one chokepoint every marketing message crosses.\n */\n topicId?: string\n}\n\n/** What the gate is asked, once per marketing message. */\nexport interface MarketingSendGateRequest {\n hostId: string\n siteBase: string\n /** The single recipient. A marketing message addresses exactly one person. */\n email: string\n /** The caller's `context` label, for the log line on a refusal. */\n context?: string\n /**\n * The stream this message belongs to, or absent for a message that belongs\n * to none. See {@link MarketingSendContext.topicId} — absent refuses\n * nobody.\n */\n topicId?: string\n /** Whether a frequency cap may refuse — see {@link MarketingSendContext}. */\n capped: boolean\n}\n\n/** Why a marketing message was not sent, or `null` when it may go. */\nexport type MarketingSendRefusal =\n /** On a suppression list: unsubscribed, hard-bounced, or a complaint. */\n | 'suppressed'\n /**\n * They have left the STREAM this message belongs to.\n *\n * Kept apart from `suppressed` even though both are terminal for this\n * message, because they describe different people: somebody on a\n * suppression list has left the site, and somebody here has left one of its\n * streams and still wants the others. A merchant reading why a send shrank\n * has a different thing to do about each, and only one of them is a list\n * that has to be rebuilt.\n *\n * NOT retryable — the condition clears when the person re-subscribes, not\n * when time passes.\n */\n | 'topic-unsubscribed'\n /** This person has already received their ceiling from this site. */\n | 'frequency-capped'\n /**\n * The RECIPIENT asked for less than this, and it has not been long enough.\n *\n * Kept apart from `frequency-capped` even though both are refusals about\n * pace, because they are refusals on behalf of different people: the\n * ceiling protects a shared sending domain from a merchant, and this\n * carries out a request the person on the other end made on the preference\n * page. Reporting them as one would make \"why did this not send\" answerable\n * only by guessing, and it is the merchant-facing half of a promise the\n * product made to a recipient.\n */\n | 'cadence-limited'\n /**\n * This site has been mailing this person for longer than the sunset window\n * and nothing in that window says they are still listening.\n *\n * NOT retryable by a sweep — the condition does not clear on a schedule,\n * it clears when the person engages. See {@link marketingSunsetVerdict}.\n */\n | 'unengaged'\n\nexport interface MarketingSendGateVerdict {\n allowed: boolean\n /** Set when `allowed` is false. */\n refusal?: MarketingSendRefusal\n /** Human-readable, for the log and the `detail` on the result. */\n detail?: string\n /**\n * The signed opt-out URL a PERSON clicks, when the gate could mint one.\n * Points at the preference page, where the stream this message belongs to\n * is one of the things they can stop instead of all of it. Absent leaves\n * the message without unsubscribe headers, which is a misconfiguration to\n * fix and not a reason to refuse mail.\n */\n unsubscribeUrl?: string\n /**\n * The same signature over the one-click route, for `List-Unsubscribe`.\n *\n * A mailbox provider POSTs that header with no human present and expects\n * the act to have happened when it reads the 200, so it must never name a\n * page of checkboxes somebody has to submit. Absent, the header falls back\n * to {@link unsubscribeUrl}.\n */\n oneClickUrl?: string\n}\n\n/**\n * Whether a message is MARKETING, derived from what it already carries.\n *\n * ## Nothing new to remember, on purpose\n *\n * The obvious design is a `kind: 'marketing' | 'transactional'` option on\n * `sendEmail`. It is rejected for the reason the `from` override was deleted\n * and the `context` tag was derived rather than threaded: twenty call sites\n * cannot each be relied on to set a field, and the twenty-first is the one that\n * does not. The consequence of forgetting here is a merchant's campaign leaving\n * on the pooled identity that carries every other site's password resets — a\n * failure nobody sees until the pool stops delivering.\n *\n * So the answer is read off two things a marketing send is ALREADY obliged to\n * carry, neither of which is optional and neither of which was added for this:\n *\n * 1. **`marketing`** — the context object. A message that declares it gets the\n * RFC 8058 header pair, the suppression check and the frequency cap, so a\n * marketing sender cannot omit it and still be correct; it would be shipping\n * mail with no unsubscribe link. Four of the five marketing senders in the\n * tree take this arm.\n * 2. **`priority === 'campaign'`** — which `resolveSendPriority` derives from\n * `context: 'campaign'`. The campaign sender mints its own unsubscribe\n * headers upstream and so passes no `marketing` context, but it is the one\n * sender that cannot avoid this label: the hourly governor is allowed to\n * refuse a campaign, and a campaign that hid from the priority would be\n * hiding from that too.\n *\n * A sender would have to defeat BOTH — no unsubscribe context and no campaign\n * priority — to reach the pool with promotional mail, and a message in that\n * state is already broken in ways its author would notice.\n *\n * ## Polarity\n *\n * A message matching neither is transactional, which is the permissive answer,\n * and that is deliberate — the same choice `resolveSendPriority` makes for the\n * same reason. Enumerating what is RESTRICTED means a forgotten caller sends a\n * receipt that goes out. Enumerating what is PERMITTED means a forgotten caller\n * drops one, and a dropped password reset is the failure you learn about from a\n * support ticket.\n */\nexport function isMarketingMessage(options: {\n marketing?: unknown\n priority?: string | null\n context?: string | null\n}): boolean {\n if (options?.marketing) return true\n // `context` is consulted only through the same rule the governor uses, so a\n // context that stops meaning \"campaign\" cannot leave the two disagreeing.\n return resolveSendPriority(\n options?.context ?? undefined,\n (options?.priority as EmailSendPriority) || undefined,\n ) === 'campaign'\n}\n\nexport type MarketingSendGate = (\n request: MarketingSendGateRequest,\n) => Promise<MarketingSendGateVerdict>\n\nlet installedGate: MarketingSendGate | null = null\n\n/** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */\nexport function setMarketingSendGate(gate: MarketingSendGate | null): void {\n installedGate = gate\n}\n\n/** The installed gate, or null when nothing has been installed. */\nexport function getMarketingSendGate(): MarketingSendGate | null {\n return installedGate\n}\n\n/** Test seam: forget any installed gate. */\nexport function resetMarketingSendGateForTests(): void {\n installedGate = null\n}\n\n/**\n * The rolling window a frequency cap counts over. One day, because that is\n * the unit a recipient experiences (\"this shop mailed me four times today\")\n * and the unit every published vendor cap is expressed in.\n */\nexport const MARKETING_FREQUENCY_WINDOW_MS = 86_400_000\n\n/**\n * How many marketing messages one person may receive from one site inside the\n * window, by default.\n *\n * **A runaway guard, not a marketing policy.** It is deliberately above what\n * an ordinary merchant produces: the worst legitimate day is a campaign plus\n * a cart reminder plus a restock alert plus a member post, which is four. Set\n * lower and the first thing it would refuse is a real message somebody meant\n * to send; set higher and it stops describing a ceiling at all. What it does\n * remove is the unbounded case — a member post that mails 200 subscribers per\n * click with no limit on clicks, and a workflow whose email step fires on\n * every anonymous form submission.\n *\n * The same number for every plan. This is a deliverability control on a\n * shared sending domain, so it protects every tenant from every other tenant\n * and cannot be something one plan buys its way past.\n */\nexport const MARKETING_FREQUENCY_DEFAULT_PER_WINDOW = 5\n\n/** Floor and ceiling on a configured cap — a typo guard, not a policy. */\nexport const MARKETING_FREQUENCY_MIN_PER_WINDOW = 1\nexport const MARKETING_FREQUENCY_MAX_PER_WINDOW = 1_000\n\n/**\n * The live cap.\n *\n * Read from the environment so a self-host operator can set their own —\n * `docs/design` states that every dependency is configurable — and read per\n * call rather than captured at module load, matching `getEmailConfig`: these\n * run in serverless handlers where the module may be evaluated during a build.\n *\n * An unparseable or out-of-range value falls back to the default rather than\n * throwing or disabling the cap. A control that a typo can switch off is not\n * a control.\n */\nexport function marketingFrequencyCap(): number {\n const raw = Number(process.env.AGLYN_EMAIL_MARKETING_CAP_PER_DAY)\n if (!Number.isFinite(raw)) return MARKETING_FREQUENCY_DEFAULT_PER_WINDOW\n const whole = Math.floor(raw)\n if (\n whole < MARKETING_FREQUENCY_MIN_PER_WINDOW ||\n whole > MARKETING_FREQUENCY_MAX_PER_WINDOW\n ) {\n return MARKETING_FREQUENCY_DEFAULT_PER_WINDOW\n }\n return whole\n}\n\n/**\n * Whether one more message fits, given what this person has already received.\n *\n * Pure, so the decision is testable without a Firestore harness — the same\n * split `emailSendRateVerdict` makes for the platform hour.\n *\n * @param recentSendsAtMs every marketing send to this person from this site,\n * newest or oldest first, in any order.\n * @returns the verdict and the trimmed window, so the caller writes back only\n * what still counts instead of growing the record forever.\n */\nexport function marketingFrequencyVerdict(\n recentSendsAtMs: readonly number[],\n nowMs: number,\n cap: number = marketingFrequencyCap(),\n): { allowed: boolean; used: number; cap: number; inWindow: number[] } {\n const floor = nowMs - MARKETING_FREQUENCY_WINDOW_MS\n const inWindow = recentSendsAtMs\n .filter((at) => Number.isFinite(at) && at > floor && at <= nowMs)\n .sort((a, b) => a - b)\n // Keep the NEWEST when a record has somehow grown past the cap. The\n // oldest entries are the ones about to leave the window anyway, so\n // dropping them loses the least information about when this person is\n // mailable again.\n .slice(-Math.max(cap, MARKETING_FREQUENCY_MIN_PER_WINDOW))\n return {\n allowed: inWindow.length < cap,\n used: inWindow.length,\n cap,\n inWindow,\n }\n}\n\n/*==========================================\n * ENGAGEMENT-BASED SUNSETTING.\n *\n * Stop mailing an address that has gone quiet. The whole design fits in one\n * sentence and three refusals it must never become.\n *\n * ## ⛔ It refuses a SEND. It never reduces a person.\n *\n * `over-limit.ts` states the rule for capacity and this is the same\n * instrument pointed at attention rather than at count. A sunset does NOT\n * unsubscribe anybody, does NOT remove them from a list, does NOT delete a\n * contact and does NOT write a suppression. Every one of those would be a\n * ceiling performing a deletion, and every one of them is irreversible in a\n * way the condition that triggered it is not.\n *\n * ## It is reversible without anybody doing anything\n *\n * The only state is two timestamps: when this site first mailed this person,\n * and when this person last engaged with our mail. A person who opens or\n * clicks anything moves the second one, and the very next send finds them\n * inside the window and mailable. Nothing has to be undone, because nothing\n * was done.\n *\n * ## The three ways it could refuse somebody it should not, and the guards\n *\n * 1. **A brand-new subscriber has no engagement yet.** So the window is\n * measured from when we STARTED mailing them, and somebody we have not\n * been mailing for longer than the window is never refused, however\n * little they have engaged.\n * 2. **We might have no record at all.** An unknown `firstSentAtMs` refuses\n * nobody. Missing evidence is not evidence of absence, and the reading\n * that mails somebody once more is the recoverable one.\n * 3. **A campaign is a reviewed act with its recipient count on screen.**\n * Sunsetting yields to it exactly as the frequency ceiling does, through\n * the same `capped` flag, so the number a merchant read before pressing\n * Send stays true. It governs the automated paths, which fire with no\n * human present.\n *\n * ## Opens are a weak signal and this leans on the broader one anyway\n *\n * The industry lesson is to sunset on clicks, because Apple's Mail Privacy\n * Protection prefetches images and inflates opens. That argument is about\n * choosing an audience. This is a refusal, and for a refusal the weaker,\n * more generous signal is the correct one: counting an open as engagement\n * refuses FEWER people. The audience rules\n * (`DynamicListEngagement`) keep opens and clicks apart so a merchant\n * segmenting on engagement can lean on clicks; this deliberately does not.\n *=========================================*/\n\n/** Floor and ceiling on a configured sunset window — a typo guard. */\nexport const MARKETING_SUNSET_MIN_DAYS = 30\nexport const MARKETING_SUNSET_MAX_DAYS = 3_650\n\n/**\n * The window, in days, or 0 for OFF.\n *\n * **Off unless an operator turns it on**, and that default is the honest one:\n * no compared vendor automates this, so a platform that silently stopped\n * mailing a merchant's quiet subscribers would be doing something none of\n * their previous tools did and none of their recipients asked for. The value\n * is a number of days rather than a boolean because the only interesting\n * question about a sunset is where it starts.\n *\n * Read per call rather than captured at module load, matching the frequency\n * cap beside it: these run in serverless handlers where the module may be\n * evaluated during a build.\n *\n * An unparseable or out-of-range value reads as OFF rather than falling back\n * to a default. This is the opposite of {@link marketingFrequencyCap}'s\n * handling and deliberately so — a typo there weakens a guard that is on by\n * default, and a typo here would ENABLE a refusal nobody asked for.\n */\nexport function marketingSunsetDays(): number {\n const raw = Number(process.env.AGLYN_EMAIL_SUNSET_AFTER_DAYS)\n if (!Number.isFinite(raw)) return 0\n const whole = Math.floor(raw)\n if (whole < MARKETING_SUNSET_MIN_DAYS || whole > MARKETING_SUNSET_MAX_DAYS) {\n return 0\n }\n return whole\n}\n\n/** What the sunset needs to know about one person. */\nexport interface MarketingSunsetFacts {\n /**\n * When this site first sent this person marketing mail, or null when we\n * have no record. Null never refuses.\n */\n firstSentAtMs: number | null\n /** When they last opened or clicked any of our mail, or null for never. */\n lastEngagedAtMs: number | null\n}\n\n/**\n * Whether this person has gone quiet for longer than the window.\n *\n * Pure, so the decision is testable without a Firestore harness — the same\n * split {@link marketingFrequencyVerdict} makes.\n *\n * @param days 0 disables the sunset entirely and this always allows.\n */\nexport function marketingSunsetVerdict(\n facts: MarketingSunsetFacts,\n nowMs: number,\n days: number = marketingSunsetDays(),\n): { allowed: boolean; days: number; quietForDays: number | null } {\n if (!days || days <= 0) {\n return { allowed: true, days: 0, quietForDays: null }\n }\n const floor = nowMs - days * 86_400_000\n const first = Number(facts.firstSentAtMs ?? 0)\n // Guard 1 and 2 together: no record, or a relationship younger than the\n // window, allows. A person cannot have been quiet for longer than we have\n // been mailing them.\n if (!Number.isFinite(first) || first <= 0 || first >= floor) {\n return { allowed: true, days, quietForDays: null }\n }\n const engaged = Number(facts.lastEngagedAtMs ?? 0)\n if (Number.isFinite(engaged) && engaged > 0 && engaged >= floor) {\n return { allowed: true, days, quietForDays: null }\n }\n const since = Number.isFinite(engaged) && engaged > 0 ? engaged : first\n return {\n allowed: false,\n days,\n quietForDays: Math.floor((nowMs - since) / 86_400_000),\n }\n}\n\n/**\n * HOW OFTEN THE RECIPIENT ASKED TO HEAR FROM THIS SITE.\n *\n * `docs/specs/email-competitive-gaps.md` G10 shipped its cap half and left\n * this one: unsubscribe was all-or-nothing plus, since topics, per-stream —\n * and a recipient who wanted the same mail LESS OFTEN still had only two\n * levers, one of which is the spam button. On a shared sending domain under\n * `p=reject` that button is charged to every other tenant, which is what\n * makes \"monthly\" a platform control wearing a courtesy's clothes.\n *\n * ## A minimum interval, not a second rolling window\n *\n * {@link marketingFrequencyVerdict} counts messages inside a day because the\n * thing it guards against is a burst. This guards against a DRIP, and the\n * question a drip asks is \"how long since the last one\" — one stored instant,\n * not a window that would have to be kept for a month to answer a monthly\n * choice. Two instruments, because they are two different questions.\n *\n * ## New values, so the vocabulary is chosen rather than inherited\n *\n * `'all'` is the default and the absence: a record with no cadence, and every\n * record written before this existed, means the person has expressed no\n * preference — which is not the same as having asked for everything, but is\n * the only reading that does not silently withhold mail from people who never\n * chose.\n */\nexport type MarketingCadence = 'all' | 'daily' | 'weekly' | 'monthly'\n\n/** The default: no expressed preference, so only the platform ceiling binds. */\nexport const DEFAULT_MARKETING_CADENCE: MarketingCadence = 'all'\n\n/**\n * The minimum gap each choice asks for, in millis.\n *\n * Calendar-naive on purpose. \"At most one a week\" is a promise about pace,\n * and honoring it as seven days from the last message is both what the words\n * say and what a recipient can check; anchoring it to a calendar week would\n * let two messages land on a Sunday and a Monday and still be \"one a week\".\n */\nexport const MARKETING_CADENCE_INTERVAL_MS: Record<MarketingCadence, number> = {\n all: 0,\n daily: 86_400_000,\n weekly: 7 * 86_400_000,\n monthly: 30 * 86_400_000,\n}\n\n/** How each choice reads, wherever one is named to a person or an operator. */\nexport const MARKETING_CADENCE_LABELS: Record<MarketingCadence, string> = {\n all: 'As they come',\n daily: 'At most one a day',\n weekly: 'At most one a week',\n monthly: 'At most one a month',\n}\n\n/**\n * Coerces a stored or submitted value to a cadence.\n *\n * Everything unrecognized becomes {@link DEFAULT_MARKETING_CADENCE}. The\n * direction matters and is the opposite of the consent policy's: a malformed\n * consent value must not become a way to switch enforcement off, because its\n * failure mode is mail to somebody who declined. A malformed cadence falling\n * to `'monthly'` would withhold mail from everybody whose record got\n * corrupted, and nobody asked for that either — so an unreadable preference\n * reads as no preference, and the person keeps whatever the ceiling allows.\n */\nexport function normalizeMarketingCadence(value: unknown): MarketingCadence {\n return value === 'daily' || value === 'weekly' || value === 'monthly'\n ? value\n : DEFAULT_MARKETING_CADENCE\n}\n\n/**\n * Whether enough time has passed for one more message at this pace.\n *\n * Pure, so the rule can be asserted without a Firestore harness — the same\n * split {@link marketingFrequencyVerdict} makes.\n *\n * @param lastSentAtMs when this site last sent this person marketing mail, or\n * `null` for somebody it has never mailed. Never mailed always allows:\n * a cadence is a gap between messages and there is no first gap.\n * @returns the verdict and, on a refusal, the instant the next message may go\n * — so a caller that defers has something to defer UNTIL rather than\n * a retry loop that discovers the answer by asking again.\n */\nexport function marketingCadenceVerdict(\n cadence: MarketingCadence,\n lastSentAtMs: number | null | undefined,\n nowMs: number,\n): { allowed: boolean; cadence: MarketingCadence; nextAllowedAtMs: number } {\n const interval = MARKETING_CADENCE_INTERVAL_MS[cadence] ?? 0\n const last = Number(lastSentAtMs)\n if (!interval || !Number.isFinite(last) || last <= 0) {\n return { allowed: true, cadence, nextAllowedAtMs: nowMs }\n }\n const nextAllowedAtMs = last + interval\n /*\n * A stored instant in the FUTURE allows rather than refusing until it\n * passes. Clocks disagree across processes and a record written a few\n * seconds ahead would otherwise hold a recipient's mail for a whole\n * interval, which is a much larger error than the one it would prevent.\n */\n if (last > nowMs) return { allowed: true, cadence, nextAllowedAtMs: nowMs }\n return { allowed: nowMs >= nextAllowedAtMs, cadence, nextAllowedAtMs }\n}\n\n/**\n * The RFC 8058 header pair.\n *\n * Both or neither: `List-Unsubscribe` alone does not satisfy the bulk-sender\n * rules, and `List-Unsubscribe-Post` without a URL to post to advertises a\n * verb nothing serves.\n */\nexport function unsubscribeHeaders(\n unsubscribeUrl: string,\n): Record<string, string> {\n if (!unsubscribeUrl) return {}\n return {\n 'List-Unsubscribe': `<${unsubscribeUrl}>`,\n 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',\n }\n}\n\n/**\n * What the visible opt-out is CALLED, in every part of every message.\n *\n * The link opens the preference page, where leaving one stream is a choice\n * alongside leaving all of them — and a footer that says only \"Unsubscribe\"\n * is the only place a recipient would have learned that, so it never gets\n * said. The word \"unsubscribe\" stays in the line because that is what a\n * recipient scans a footer for.\n *\n * Named once and shared with `renderRecipientEmail`, which writes this same\n * line into a campaign's text part: two spellings of one sentence is how the\n * idempotency checks below come to append a second footer to a message that\n * already had one.\n */\nexport const UNSUBSCRIBE_FOOTER_LABEL =\n 'Choose which emails you get, or unsubscribe'\n\n/**\n * The visible opt-out, appended to the plain-text part.\n *\n * The headers are for the mailbox provider; this is for the person. CAN-SPAM\n * asks for a mechanism the recipient can see and use, and a header is neither\n * — most clients render no control for it at all unless the sender's domain\n * reputation is high enough for the provider to offer one.\n *\n * Idempotent by URL: a body that already carries the link is returned\n * untouched, so a sender that writes its own footer does not get two.\n */\nexport function appendUnsubscribeText(\n text: string,\n unsubscribeUrl: string,\n): string {\n if (!unsubscribeUrl || (text && text.includes(unsubscribeUrl))) return text\n return `${text ?? ''}\\n\\n—\\n${UNSUBSCRIBE_FOOTER_LABEL}: ${unsubscribeUrl}`\n}\n\n/**\n * The same visible opt-out for the HTML part.\n *\n * Appended to whatever the sender produced rather than woven into it, because\n * the HTML may be a merchant-designed template this module knows nothing\n * about. A designed template that already renders `{{unsubscribeUrl}}`\n * carries the URL, so the check below leaves it alone and the merchant's own\n * placement wins.\n *\n * ⚠️ That check has to look for the ESCAPED URL as well. A signed opt-out\n * link carries `&` between its query parameters, and a renderer putting it\n * into an `href` escapes it — so `renderEmailHtml` emits `…&amp;sig=…` and a\n * plain `includes` of the unescaped URL matches nothing. Every designed\n * template in the product goes through that renderer, which means the\n * merchants who DID place the token were the ones getting two footers.\n *\n * Styles are inline and literal because this is email HTML: mail clients\n * strip `<style>` blocks and support no CSS variables, so a theme token\n * cannot reach the wire.\n */\nexport function appendUnsubscribeHtml(\n html: string,\n unsubscribeUrl: string,\n): string {\n if (!unsubscribeUrl) return html\n if (\n html &&\n (html.includes(unsubscribeUrl) ||\n html.includes(escapeEmailHtml(unsubscribeUrl)))\n ) {\n return html\n }\n const footer =\n '<div style=\"margin:24px auto 0;max-width:600px;padding:16px 24px;' +\n \"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,\" +\n 'Helvetica,Arial,sans-serif;font-size:12px;line-height:1.5;' +\n 'color:#616161;text-align:center\">' +\n `<a href=\"${escapeEmailHtml(unsubscribeUrl)}\" style=\"color:#616161\">` +\n `${UNSUBSCRIBE_FOOTER_LABEL}</a>` +\n '</div>'\n return `${html ?? ''}${footer}`\n}\n"],"names":["escapeEmailHtml","resolveSendPriority","isMarketingMessage","options","marketing","context","undefined","priority","installedGate","setMarketingSendGate","gate","getMarketingSendGate","resetMarketingSendGateForTests","MARKETING_FREQUENCY_WINDOW_MS","MARKETING_FREQUENCY_DEFAULT_PER_WINDOW","MARKETING_FREQUENCY_MIN_PER_WINDOW","MARKETING_FREQUENCY_MAX_PER_WINDOW","marketingFrequencyCap","raw","Number","process","env","AGLYN_EMAIL_MARKETING_CAP_PER_DAY","isFinite","whole","Math","floor","marketingFrequencyVerdict","recentSendsAtMs","nowMs","cap","inWindow","filter","at","sort","a","b","slice","max","allowed","length","used","MARKETING_SUNSET_MIN_DAYS","MARKETING_SUNSET_MAX_DAYS","marketingSunsetDays","AGLYN_EMAIL_SUNSET_AFTER_DAYS","marketingSunsetVerdict","facts","days","quietForDays","first","firstSentAtMs","engaged","lastEngagedAtMs","since","DEFAULT_MARKETING_CADENCE","MARKETING_CADENCE_INTERVAL_MS","all","daily","weekly","monthly","MARKETING_CADENCE_LABELS","normalizeMarketingCadence","value","marketingCadenceVerdict","cadence","lastSentAtMs","interval","last","nextAllowedAtMs","unsubscribeHeaders","unsubscribeUrl","UNSUBSCRIBE_FOOTER_LABEL","appendUnsubscribeText","text","includes","appendUnsubscribeHtml","html","footer"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED;;;;;CAKC,GACD,SAASA,eAAe,QAAQ,oBAAgB;AAChD,SAASC,mBAAmB,QAAgC,iBAAa;AA8KzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,OAAO,SAASC,mBAAmBC,OAIlC;;IACC,IAAIA,2BAAAA,QAASC,SAAS,EAA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