@pithy-sh/email 0.1.1 → 0.1.3
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/dist/analytics.d.ts +19 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +13 -0
- package/dist/audit/actions.d.ts +45 -0
- package/dist/audit/actions.d.ts.map +1 -0
- package/dist/audit/actions.js +45 -0
- package/dist/bounce/classify.d.ts +38 -0
- package/dist/bounce/classify.d.ts.map +1 -0
- package/dist/bounce/classify.js +46 -0
- package/dist/bounce/handler.d.ts +32 -0
- package/dist/bounce/handler.d.ts.map +1 -0
- package/dist/bounce/handler.js +81 -0
- package/dist/capability.d.ts +158 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/capability.js +255 -0
- package/dist/crypto/signingKey.d.ts +36 -0
- package/dist/crypto/signingKey.d.ts.map +1 -0
- package/dist/crypto/signingKey.js +36 -0
- package/dist/crypto/token.d.ts +47 -0
- package/dist/crypto/token.d.ts.map +1 -0
- package/dist/crypto/token.js +99 -0
- package/dist/data/emailEvent.d.ts +28 -0
- package/dist/data/emailEvent.d.ts.map +1 -0
- package/dist/data/emailEvent.js +22 -0
- package/dist/data/emailJob.d.ts +76 -0
- package/dist/data/emailJob.d.ts.map +1 -0
- package/dist/data/emailJob.js +62 -0
- package/dist/data/emailSuppression.d.ts +23 -0
- package/dist/data/emailSuppression.d.ts.map +1 -0
- package/dist/data/emailSuppression.js +21 -0
- package/dist/data/enums.d.ts +76 -0
- package/dist/data/enums.d.ts.map +1 -0
- package/dist/data/enums.js +65 -0
- package/dist/data/tables.d.ts +114 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tables.js +30 -0
- package/dist/error/errors.d.ts +60 -0
- package/dist/error/errors.d.ts.map +1 -0
- package/dist/error/errors.js +82 -0
- package/dist/http/callbacks.d.ts +21 -0
- package/dist/http/callbacks.d.ts.map +1 -0
- package/dist/http/callbacks.js +110 -0
- package/dist/http/guards.d.ts +99 -0
- package/dist/http/guards.d.ts.map +1 -0
- package/dist/http/guards.js +144 -0
- package/dist/http/responses.d.ts +295 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +115 -0
- package/dist/http/routes.d.ts +71 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +292 -0
- package/dist/http/schemas.d.ts +90 -0
- package/dist/http/schemas.d.ts.map +1 -0
- package/dist/http/schemas.js +91 -0
- package/dist/http/view.d.ts +78 -0
- package/dist/http/view.d.ts.map +1 -0
- package/dist/http/view.js +130 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/jobs/read.d.ts +191 -0
- package/dist/jobs/read.d.ts.map +1 -0
- package/dist/jobs/read.js +143 -0
- package/dist/jobs/retry.d.ts +99 -0
- package/dist/jobs/retry.d.ts.map +1 -0
- package/dist/jobs/retry.js +67 -0
- package/dist/migrations/0001_init.d.ts +32 -0
- package/dist/migrations/0001_init.d.ts.map +1 -0
- package/dist/migrations/0001_init.js +60 -0
- package/dist/migrations/0001_suppressions.d.ts +10 -0
- package/dist/migrations/0001_suppressions.d.ts.map +1 -0
- package/dist/migrations/0001_suppressions.js +20 -0
- package/dist/provision/devDelivery.d.ts +32 -0
- package/dist/provision/devDelivery.d.ts.map +1 -0
- package/dist/provision/devDelivery.js +37 -0
- package/dist/provision/hostCatalogs.d.ts +10 -0
- package/dist/provision/hostCatalogs.d.ts.map +1 -0
- package/dist/provision/hostCatalogs.js +78 -0
- package/dist/provision/provisionEmail.d.ts +143 -0
- package/dist/provision/provisionEmail.d.ts.map +1 -0
- package/dist/provision/provisionEmail.js +118 -0
- package/dist/provision/resolveEmailConfig.d.ts +122 -0
- package/dist/provision/resolveEmailConfig.d.ts.map +1 -0
- package/dist/provision/resolveEmailConfig.js +124 -0
- package/dist/provision/settingsCheck.d.ts +40 -0
- package/dist/provision/settingsCheck.d.ts.map +1 -0
- package/dist/provision/settingsCheck.js +138 -0
- package/dist/send/batchIdentity.d.ts +42 -0
- package/dist/send/batchIdentity.d.ts.map +1 -0
- package/dist/send/batchIdentity.js +46 -0
- package/dist/send/enqueue.d.ts +216 -0
- package/dist/send/enqueue.d.ts.map +1 -0
- package/dist/send/enqueue.js +153 -0
- package/dist/send/errorMapping.d.ts +27 -0
- package/dist/send/errorMapping.d.ts.map +1 -0
- package/dist/send/errorMapping.js +52 -0
- package/dist/send/events.d.ts +15 -0
- package/dist/send/events.d.ts.map +1 -0
- package/dist/send/events.js +17 -0
- package/dist/send/fromComposition.d.ts +47 -0
- package/dist/send/fromComposition.d.ts.map +1 -0
- package/dist/send/fromComposition.js +53 -0
- package/dist/send/retryPolicy.d.ts +32 -0
- package/dist/send/retryPolicy.d.ts.map +1 -0
- package/dist/send/retryPolicy.js +39 -0
- package/dist/send/runSend.d.ts +106 -0
- package/dist/send/runSend.d.ts.map +1 -0
- package/dist/send/runSend.js +218 -0
- package/dist/send/sendAt.d.ts +6 -0
- package/dist/send/sendAt.d.ts.map +1 -0
- package/dist/send/sendAt.js +62 -0
- package/dist/send/sender.d.ts +42 -0
- package/dist/send/sender.d.ts.map +1 -0
- package/dist/send/sender.js +0 -0
- package/dist/send/senderBinding.d.ts +44 -0
- package/dist/send/senderBinding.d.ts.map +1 -0
- package/dist/send/senderBinding.js +21 -0
- package/dist/send/suppression.d.ts +93 -0
- package/dist/send/suppression.d.ts.map +1 -0
- package/dist/send/suppression.js +132 -0
- package/dist/templates/engine.d.ts +109 -0
- package/dist/templates/engine.d.ts.map +1 -0
- package/dist/templates/engine.js +258 -0
- package/dist/templates/messages.d.ts +94 -0
- package/dist/templates/messages.d.ts.map +1 -0
- package/dist/templates/messages.es.d.ts +29 -0
- package/dist/templates/messages.es.d.ts.map +1 -0
- package/dist/templates/messages.es.js +82 -0
- package/dist/templates/messages.js +266 -0
- package/dist/templates/partials.d.ts +5 -0
- package/dist/templates/partials.d.ts.map +1 -0
- package/dist/templates/partials.js +59 -0
- package/dist/templates/precompiled.generated.d.ts +266 -0
- package/dist/templates/precompiled.generated.d.ts.map +1 -0
- package/dist/templates/precompiled.generated.js +4039 -0
- package/dist/templates/registry.d.ts +118 -0
- package/dist/templates/registry.d.ts.map +1 -0
- package/dist/templates/registry.js +323 -0
- package/dist/templates/samples.d.ts +7 -0
- package/dist/templates/samples.d.ts.map +1 -0
- package/dist/templates/samples.js +98 -0
- package/dist/templates/severity.d.ts +40 -0
- package/dist/templates/severity.d.ts.map +1 -0
- package/dist/templates/severity.js +81 -0
- package/dist/templates/theme.d.ts +193 -0
- package/dist/templates/theme.d.ts.map +1 -0
- package/dist/templates/theme.js +168 -0
- package/dist/version.generated.d.ts +5 -0
- package/dist/version.generated.d.ts.map +1 -0
- package/dist/version.generated.js +7 -0
- package/dist/workflows/hostApp.d.ts +33 -0
- package/dist/workflows/hostApp.d.ts.map +1 -0
- package/dist/workflows/hostApp.js +19 -0
- package/dist/workflows/hostEnv.d.ts +129 -0
- package/dist/workflows/hostEnv.d.ts.map +1 -0
- package/dist/workflows/hostEnv.js +147 -0
- package/dist/workflows/instanceLiveness.d.ts +3 -0
- package/dist/workflows/instanceLiveness.d.ts.map +1 -0
- package/dist/workflows/instanceLiveness.js +37 -0
- package/dist/workflows/instances.d.ts +18 -0
- package/dist/workflows/instances.d.ts.map +1 -0
- package/dist/workflows/instances.js +0 -0
- package/dist/workflows/params.d.ts +23 -0
- package/dist/workflows/params.d.ts.map +1 -0
- package/dist/workflows/params.js +21 -0
- package/dist/workflows/scheduler.d.ts +82 -0
- package/dist/workflows/scheduler.d.ts.map +1 -0
- package/dist/workflows/scheduler.js +111 -0
- package/dist/workflows/sendBatch.d.ts +85 -0
- package/dist/workflows/sendBatch.d.ts.map +1 -0
- package/dist/workflows/sendBatch.js +50 -0
- package/dist/workflows/worker.d.ts +100 -0
- package/dist/workflows/worker.d.ts.map +1 -0
- package/dist/workflows/worker.js +117 -0
- package/package.json +22 -11
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { EmailInvalidPayloadError, EmailTemplateNotFoundError } from "../error/errors.js";
|
|
2
|
+
import { mintToken } from "../crypto/token.js";
|
|
3
|
+
import { emailTranslator, kitEmailLayers } from "./messages.js";
|
|
4
|
+
import { precompiledPartials, precompiledTemplates } from "./precompiled.generated.js";
|
|
5
|
+
import { severityColor, severityLabelKey } from "./severity.js";
|
|
6
|
+
import { templates } from "./registry.js";
|
|
7
|
+
import { widthPx } from "./theme.js";
|
|
8
|
+
import Handlebars from "handlebars";
|
|
9
|
+
//#region src/templates/engine.ts
|
|
10
|
+
/**
|
|
11
|
+
* The render engine. Templates are compiled **once at module load** — which in a Worker happens during
|
|
12
|
+
* isolate startup, where dynamic compilation is permitted — and cached, so a send never compiles or
|
|
13
|
+
* evals at request time (CLAUDE.md §Email: "precompiled, no runtime compile/eval"). Rendering is then
|
|
14
|
+
* pure string substitution.
|
|
15
|
+
*
|
|
16
|
+
* Tracking is applied here, not in the template: callback tokens are minted ahead of render (signing
|
|
17
|
+
* is async; Handlebars helpers are not) and the resulting URLs are placed into the render context.
|
|
18
|
+
* Click tracking rewrites the declared link locations; open tracking injects a pixel; and an **elective**
|
|
19
|
+
* template gets an unsubscribe link, which a marketing template additionally cannot render without.
|
|
20
|
+
*
|
|
21
|
+
* **A transactional template can never be given one.** The affordance is gated on the kind the template
|
|
22
|
+
* itself declares, so there is no argument a call site could pass to put an opt-out on a sign-in link —
|
|
23
|
+
* and `renderEmail` reports the URL it minted, so the send path sets `List-Unsubscribe` from what was
|
|
24
|
+
* actually rendered rather than from a second, drift-prone judgment of its own.
|
|
25
|
+
*/
|
|
26
|
+
/** The mount prefix of the callback routes. Tracking URLs are built against `${baseUrl}${CALLBACK_BASE}`. */
|
|
27
|
+
const CALLBACK_BASE = "/_pithy/email";
|
|
28
|
+
const hbs = Handlebars.create();
|
|
29
|
+
for (const [name, spec] of Object.entries(precompiledPartials)) hbs.registerPartial(name, hbs.template(spec));
|
|
30
|
+
hbs.registerHelper("severityColor", severityColor);
|
|
31
|
+
/**
|
|
32
|
+
* The English every render falls back to — and the whole render when nothing composed an i18n
|
|
33
|
+
* capability, which is the seam's zero-config behavior everywhere else in the kit.
|
|
34
|
+
*
|
|
35
|
+
* Module-level and shared, because it holds no request state: a translator over one fixed catalog is a
|
|
36
|
+
* pure lookup table. The per-job translators the send path builds are the ones that carry a locale, and
|
|
37
|
+
* they live and die with one render.
|
|
38
|
+
*/
|
|
39
|
+
const ENGLISH = emailTranslator("en", kitEmailLayers);
|
|
40
|
+
/** The key the render context carries its translator under. Read by the helpers, never by a template. */
|
|
41
|
+
const TRANSLATOR_KEY = "i18n";
|
|
42
|
+
/** Whether a value is a translator, structurally — the seam is an interface, so there is no class to test. */
|
|
43
|
+
function isTranslator(value) {
|
|
44
|
+
return typeof value?.t === "function";
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The translator this render is going through, or the kit's English.
|
|
48
|
+
*
|
|
49
|
+
* Read off `@root` rather than closed over, because the engine is built once per isolate and a
|
|
50
|
+
* translator belongs to one message. A module-level "current locale" would be the same hazard
|
|
51
|
+
* `z.config()` is banned repo-wide for: an isolate serves many recipients, and the one holding the
|
|
52
|
+
* locale would apply the last render's language to the next.
|
|
53
|
+
*/
|
|
54
|
+
function translatorOf(options) {
|
|
55
|
+
const held = (options.data?.root)?.[TRANSLATOR_KEY];
|
|
56
|
+
return isTranslator(held) ? held : ENGLISH;
|
|
57
|
+
}
|
|
58
|
+
/** The helper's `key=value` arguments as message parameters — scalars only, like every catalog value. */
|
|
59
|
+
function messageParams(hash) {
|
|
60
|
+
const params = {};
|
|
61
|
+
for (const [name, value] of Object.entries(hash ?? {})) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") params[name] = value;
|
|
62
|
+
return params;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* `{{t "email/magic_link.heading"}}` — one catalog message, with `key=value` interpolation.
|
|
66
|
+
*
|
|
67
|
+
* It returns a plain string and **never** a `SafeString`. That is the security constraint, not a style
|
|
68
|
+
* choice: the HTML body escapes what a mustache produces, so a catalog value — the kit's, or the one
|
|
69
|
+
* sentence an adopter overrode it with — is escaped on exactly the path a payload value is. `subject`
|
|
70
|
+
* and `text` are precompiled with `noEscape`, where nothing is escaped and nothing needs to be, which
|
|
71
|
+
* is why no catalog value in this kit carries markup and why `docs/I18N.md` says so to adopters.
|
|
72
|
+
*/
|
|
73
|
+
hbs.registerHelper("t", (key, options) => translatorOf(options).t(String(key), messageParams(options.hash)));
|
|
74
|
+
/**
|
|
75
|
+
* `{{tn "email/otp.expiry" count=expiresMinutes}}` — the plural form the count calls for.
|
|
76
|
+
*
|
|
77
|
+
* Separate from `t` because plural selection is the thing a second locale exposes: "It expires in 1
|
|
78
|
+
* minutes" was already wrong in English and unfixable without it, and Russian needs three forms where
|
|
79
|
+
* English needs two. The count is a hash argument rather than a positional one so that a payload field
|
|
80
|
+
* reaching a template through this helper is still visible to `engine.test.ts`'s check that every
|
|
81
|
+
* variable a template renders is declared on its payload schema.
|
|
82
|
+
*/
|
|
83
|
+
hbs.registerHelper("tn", (key, options) => {
|
|
84
|
+
const params = messageParams(options.hash);
|
|
85
|
+
return translatorOf(options).plural(String(key), Number(params.count ?? 0), params);
|
|
86
|
+
});
|
|
87
|
+
/** `{{severityLabel severity}}` — the level's word, in the reader's language. */
|
|
88
|
+
hbs.registerHelper("severityLabel", (severity, options) => translatorOf(options).t(severityLabelKey(severity)));
|
|
89
|
+
function delegate(key) {
|
|
90
|
+
const spec = precompiledTemplates[key];
|
|
91
|
+
if (!spec) throw new Error(`missing precompiled template spec '${key}' — run \`bun run precompile\``);
|
|
92
|
+
return hbs.template(spec);
|
|
93
|
+
}
|
|
94
|
+
const compiled = new Map(Object.values(templates).map((def) => [def.id, {
|
|
95
|
+
def,
|
|
96
|
+
subject: delegate(`${def.id}:subject`),
|
|
97
|
+
html: delegate(`${def.id}:html`),
|
|
98
|
+
text: delegate(`${def.id}:text`)
|
|
99
|
+
}]));
|
|
100
|
+
/** Look up a template by id, or throw `email/template_not_found`. */
|
|
101
|
+
function getTemplate(id) {
|
|
102
|
+
const found = compiled.get(id);
|
|
103
|
+
if (!found) throw new EmailTemplateNotFoundError({ detail: `no template registered with id '${id}'` });
|
|
104
|
+
return found.def;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The kind a template declares — the one answer to "may this message be refused".
|
|
108
|
+
*
|
|
109
|
+
* An id nobody registered is reported as `elective`, deliberately. It cannot be *proved* transactional,
|
|
110
|
+
* and the alternative reading would let a template deleted in a later release quietly reopen sending to
|
|
111
|
+
* addresses that opted out. Nothing is locked out by the choice: a job naming an unknown template fails
|
|
112
|
+
* at render moments later either way, so this only decides which of two failures gets reported.
|
|
113
|
+
*/
|
|
114
|
+
function templateKind(templateId) {
|
|
115
|
+
return compiled.get(templateId)?.def.kind ?? "elective";
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Whether this template's payload is dropped once the message is delivered.
|
|
119
|
+
*
|
|
120
|
+
* **Keyed on the category, not the kind.** The kind answers "may this be refused"; this question is
|
|
121
|
+
* "are these inputs a one-time credential". `testerNudge` is the template that proves they are
|
|
122
|
+
* different axes — it is *elective*, because somebody may say stop chasing me, and its payload carries
|
|
123
|
+
* an opt-in URL that authenticates a tester. Keying on the kind would have left exactly that one live.
|
|
124
|
+
*
|
|
125
|
+
* A transactional message is a reply to something one person just did, and its payload is that
|
|
126
|
+
* person's one-time input: a sign-in URL, a code, an invitation token. A marketing message's payload is
|
|
127
|
+
* copy authored for a batch, carrying no per-recipient credential and answering the real question
|
|
128
|
+
* "what did the forty thousand of them actually receive". So the category is the line, and it falls in
|
|
129
|
+
* the right place on every template in the registry.
|
|
130
|
+
*
|
|
131
|
+
* There is no per-template override, because no template needs one today and an escape hatch nobody
|
|
132
|
+
* uses is where the bug comes back. The day a marketing template carries a per-recipient credential,
|
|
133
|
+
* the override is the change to make — with a reason written beside it.
|
|
134
|
+
*
|
|
135
|
+
* An id nobody registered redacts, which is the safe direction and, like `templateKind`, decides
|
|
136
|
+
* nothing real: a job naming an unknown template fails at render and never reaches a delivery.
|
|
137
|
+
*/
|
|
138
|
+
function redactsPayloadOnDelivery(templateId) {
|
|
139
|
+
return compiled.get(templateId)?.def.category !== "marketing";
|
|
140
|
+
}
|
|
141
|
+
/** The registered template ids, for introspection and the CLI. */
|
|
142
|
+
function listTemplates() {
|
|
143
|
+
return Object.values(templates);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Validate a payload against its template and render just the subject line. Used at enqueue to fail
|
|
147
|
+
* fast on a bad payload and to store the job's subject without rendering the whole body. Throws
|
|
148
|
+
* `email/template_not_found` or `email/invalid_payload`.
|
|
149
|
+
*/
|
|
150
|
+
function renderSubject(templateId, payload, theme, translator = ENGLISH) {
|
|
151
|
+
const entry = compiled.get(templateId);
|
|
152
|
+
if (!entry) throw new EmailTemplateNotFoundError({ detail: `no template registered with id '${templateId}'` });
|
|
153
|
+
const parsed = entry.def.payload.safeParse(payload);
|
|
154
|
+
if (!parsed.success) {
|
|
155
|
+
const summary = parsed.error.issues.map((i) => `${i.path.join(".") || "<root>"}:${i.code}`).join(", ");
|
|
156
|
+
throw new EmailInvalidPayloadError({ detail: `template '${templateId}' payload invalid: ${summary}` });
|
|
157
|
+
}
|
|
158
|
+
return entry.subject(renderContext(parsed.data, entry, theme, translator)).trim();
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The render context: the parsed payload, the theme, and what the shell needs to be written in a
|
|
162
|
+
* language.
|
|
163
|
+
*
|
|
164
|
+
* One builder for both render sites, because the two used to assemble it separately and the *subject*
|
|
165
|
+
* is the field they were most able to disagree about — `renderSubject` runs at enqueue and `renderEmail`
|
|
166
|
+
* runs at send, and until the locale landed on the row there was nothing tying them to one language.
|
|
167
|
+
*/
|
|
168
|
+
function renderContext(payload, entry, theme, translator) {
|
|
169
|
+
return {
|
|
170
|
+
...payload,
|
|
171
|
+
theme,
|
|
172
|
+
layoutWidth: widthPx(entry.def.width),
|
|
173
|
+
lang: translator.catalogLocale,
|
|
174
|
+
dir: translator.direction,
|
|
175
|
+
[TRANSLATOR_KEY]: translator
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function trimTrailingSlash(value) {
|
|
179
|
+
return value.endsWith("/") ? value.slice(0, -1) : value;
|
|
180
|
+
}
|
|
181
|
+
/** Rewrite one declared link path (`"url"` or `"articles[].link"`) in the context through `makeUrl`. */
|
|
182
|
+
async function rewriteLink(context, path, label, makeUrl) {
|
|
183
|
+
const arrayMatch = path.split("[].");
|
|
184
|
+
if (arrayMatch.length === 2) {
|
|
185
|
+
const arrayKey = arrayMatch[0];
|
|
186
|
+
const field = arrayMatch[1];
|
|
187
|
+
if (!arrayKey || !field) return;
|
|
188
|
+
const items = context[arrayKey];
|
|
189
|
+
if (Array.isArray(items)) for (let i = 0; i < items.length; i += 1) {
|
|
190
|
+
const item = items[i];
|
|
191
|
+
if (item && typeof item[field] === "string") item[field] = await makeUrl(item[field], `${label}-${i}`);
|
|
192
|
+
}
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (typeof context[path] === "string") context[path] = await makeUrl(context[path], label);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Render a template to `{ subject, html, text }`. Validates the payload against the template's schema
|
|
199
|
+
* (throws `email/invalid_payload`), applies click/open tracking and — for an elective template — the
|
|
200
|
+
* unsubscribe link, then substitutes. A marketing template with no tracking context throws: it cannot
|
|
201
|
+
* render without an unsubscribe link.
|
|
202
|
+
*
|
|
203
|
+
* The opt-out rule is two-tier on purpose. Every elective template carries the link *when the engine can
|
|
204
|
+
* mint one*; a marketing template additionally *refuses to render* without it. Tying the hard refusal to
|
|
205
|
+
* the kind instead would mean a project that has not configured a link-signing key suddenly cannot send
|
|
206
|
+
* its testing-cohort nudges — a new outage, in a change whose whole subject is mail that fails silently.
|
|
207
|
+
*/
|
|
208
|
+
async function renderEmail(templateId, payload, theme, tracking, translator = ENGLISH) {
|
|
209
|
+
const entry = compiled.get(templateId);
|
|
210
|
+
if (!entry) throw new EmailTemplateNotFoundError({ detail: `no template registered with id '${templateId}'` });
|
|
211
|
+
const parsed = entry.def.payload.safeParse(payload);
|
|
212
|
+
if (!parsed.success) {
|
|
213
|
+
const summary = parsed.error.issues.map((i) => `${i.path.join(".") || "<root>"}:${i.code}`).join(", ");
|
|
214
|
+
throw new EmailInvalidPayloadError({ detail: `template '${templateId}' payload invalid: ${summary}` });
|
|
215
|
+
}
|
|
216
|
+
const isMarketing = entry.def.category === "marketing";
|
|
217
|
+
const isElective = entry.def.kind === "elective";
|
|
218
|
+
if (isMarketing && !tracking) throw new EmailInvalidPayloadError({
|
|
219
|
+
message: "Marketing emails require an unsubscribe link.",
|
|
220
|
+
detail: `template '${templateId}' is marketing but no signing/tracking context was provided`
|
|
221
|
+
});
|
|
222
|
+
const context = renderContext(parsed.data, entry, theme, translator);
|
|
223
|
+
let unsubscribeUrl;
|
|
224
|
+
if (tracking) {
|
|
225
|
+
const base = trimTrailingSlash(tracking.baseUrl) + CALLBACK_BASE;
|
|
226
|
+
const mint = (kind, extra) => mintToken({
|
|
227
|
+
kind,
|
|
228
|
+
jobId: tracking.jobId,
|
|
229
|
+
recipient: tracking.recipient,
|
|
230
|
+
campaignId: tracking.campaignId,
|
|
231
|
+
...extra
|
|
232
|
+
}, {
|
|
233
|
+
key: tracking.key,
|
|
234
|
+
kid: tracking.kid,
|
|
235
|
+
expiresAt: tracking.expiresAt
|
|
236
|
+
});
|
|
237
|
+
if (tracking.clickTracking) for (const link of entry.def.links) await rewriteLink(context, link.path, link.label, async (destination, label) => {
|
|
238
|
+
const token = await mint("click", {
|
|
239
|
+
destination,
|
|
240
|
+
linkLabel: label
|
|
241
|
+
});
|
|
242
|
+
return `${base}/c/${token}`;
|
|
243
|
+
});
|
|
244
|
+
if (tracking.openTracking) context.openPixelUrl = `${base}/o/${await mint("open", {})}.png`;
|
|
245
|
+
if (isElective) {
|
|
246
|
+
unsubscribeUrl = `${base}/u/${await mint("unsubscribe", {})}`;
|
|
247
|
+
context.unsubscribeUrl = unsubscribeUrl;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
subject: entry.subject(context).trim(),
|
|
252
|
+
html: entry.html(context),
|
|
253
|
+
text: entry.text(context),
|
|
254
|
+
...unsubscribeUrl ? { unsubscribeUrl } : {}
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
export { CALLBACK_BASE, getTemplate, listTemplates, redactsPayloadOnDelivery, renderEmail, renderSubject, templateKind };
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { type LocaleCatalogs, MessageCatalog } from "@pithy-sh/core/src/i18n/catalog";
|
|
2
|
+
import { type Translator } from "@pithy-sh/core/src/i18n/translator";
|
|
3
|
+
/**
|
|
4
|
+
* Every language this capability's own copy is written in.
|
|
5
|
+
*
|
|
6
|
+
* **Bundled, not stamped.** The send Worker is deployed with this map inside it, so adding a language
|
|
7
|
+
* to the kit costs an adopter a package upgrade and no configuration at all — which is the whole of
|
|
8
|
+
* #442. What still travels as a variable is the adopter's diff against this: usually nothing, and at
|
|
9
|
+
* most the sentences they changed.
|
|
10
|
+
*/
|
|
11
|
+
export declare const EMAIL_MESSAGES: LocaleCatalogs;
|
|
12
|
+
/**
|
|
13
|
+
* How the render engine finds words for a locale: the catalogs to walk, most-specific first.
|
|
14
|
+
*
|
|
15
|
+
* The same shape `@pithy-sh/i18n` already exposes as `layersFor`, so a composed project hands its own
|
|
16
|
+
* — adopter overrides, the kit's translation, every capability's English — straight through, and this
|
|
17
|
+
* package never imports that one. Absent, {@link kitEmailLayers} answers, which is what makes the i18n
|
|
18
|
+
* capability optional here exactly as it is everywhere else.
|
|
19
|
+
*/
|
|
20
|
+
export type EmailMessageLayers = (locale: string) => readonly (MessageCatalog | undefined)[];
|
|
21
|
+
/** The layers a project that composed no i18n capability walks: this package's own English, and nothing else. */
|
|
22
|
+
export declare const kitEmailLayers: EmailMessageLayers;
|
|
23
|
+
/**
|
|
24
|
+
* The layers behind a serialized catalog set — what the prebuilt email host worker uses.
|
|
25
|
+
*
|
|
26
|
+
* That worker is standalone: nothing composes capabilities inside it, so it cannot be handed a
|
|
27
|
+
* composed project's `layersFor`. It reads the catalogs as one JSON var instead, and this turns them
|
|
28
|
+
* into the same seam. English stays last, so a locale that translated nine sentences out of ten still
|
|
29
|
+
* renders the tenth rather than its key.
|
|
30
|
+
*/
|
|
31
|
+
/**
|
|
32
|
+
* The prefix every per-locale catalog variable carries on the email and testers hosts.
|
|
33
|
+
*
|
|
34
|
+
* **One variable per locale, not one variable holding every locale.** Cloudflare's 5 KB ceiling is per
|
|
35
|
+
* variable, and a Worker gets 64 of them on the free plan and 128 on paid — so a project shipping
|
|
36
|
+
* twenty languages has twenty 3 KB values, each comfortably inside the limit, rather than one 62 KB
|
|
37
|
+
* value that is refused outright.
|
|
38
|
+
*
|
|
39
|
+
* It was one variable at first, and the ceiling that produced was absurd on inspection: every language
|
|
40
|
+
* pack fits with 2 KB to spare, and the project still could not deploy a second one. Nothing about the
|
|
41
|
+
* data was near a limit — the limit was manufactured by concatenating packs that are read one at a
|
|
42
|
+
* time. The host renders one email, in one locale, from the job's row; it never needs the other
|
|
43
|
+
* nineteen. Splitting the transport is the whole fix, and the in-memory shape is unchanged.
|
|
44
|
+
*/
|
|
45
|
+
export declare const EMAIL_CATALOG_VAR_PREFIX = "EMAIL_MESSAGES_";
|
|
46
|
+
/**
|
|
47
|
+
* The variable name a locale's catalog travels under — `es-AR` becomes `EMAIL_MESSAGES_ES_AR`.
|
|
48
|
+
*
|
|
49
|
+
* Upper-cased with dashes as underscores, which is the shape a Worker variable name takes. The mapping
|
|
50
|
+
* is injective because `Locale` forbids `_` in a tag, so no two tags can collide on one name.
|
|
51
|
+
*/
|
|
52
|
+
export declare function emailCatalogVarName(locale: string): string;
|
|
53
|
+
/**
|
|
54
|
+
* The locale a variable name carries, or `null` when the name is not one of ours.
|
|
55
|
+
*
|
|
56
|
+
* **Canonicalized through `Intl`, not merely lower-cased.** A variable name has one case and a tag has
|
|
57
|
+
* three — `pt-BR`, `zh-Hant-TW`, `es-419` — so the name alone cannot say which. `Intl.Locale` restores
|
|
58
|
+
* it: `pt_br` reads back as `pt-BR`, script subtags title-cased and regions upper-cased, which is the
|
|
59
|
+
* spelling `catalogLayers` looks the catalog up under. Lower-cased instead, a `pt-BR` job would miss a
|
|
60
|
+
* `pt-br` catalog and silently render the kit's English.
|
|
61
|
+
*/
|
|
62
|
+
export declare function localeFromCatalogVar(name: string): string | null;
|
|
63
|
+
/**
|
|
64
|
+
* Every catalog this host was deployed with, collected off the raw env.
|
|
65
|
+
*
|
|
66
|
+
* **Read from the raw env rather than declared on `EmailHostEnv`**, because the variable *names* are
|
|
67
|
+
* the project's locales and a Zod object can only declare names known when it was written. The values
|
|
68
|
+
* are still validated — each one is parsed through `LocaleCatalogs`' own `MessageCatalog`, so a
|
|
69
|
+
* variable holding something that is not a catalog is a boot failure rather than a render failure.
|
|
70
|
+
*
|
|
71
|
+
* A locale whose value will not parse is skipped rather than fatal: the render falls through to the
|
|
72
|
+
* kit's English for that language and every other language still works. One unreadable variable
|
|
73
|
+
* should not stop a host from sending mail.
|
|
74
|
+
*/
|
|
75
|
+
export declare function catalogsFromEnv(env: Record<string, unknown>): LocaleCatalogs;
|
|
76
|
+
export declare function catalogLayers(catalogs: LocaleCatalogs): EmailMessageLayers;
|
|
77
|
+
/**
|
|
78
|
+
* The translator one email renders through.
|
|
79
|
+
*
|
|
80
|
+
* **Built per render from the job's own locale, never from the request's.** A send happens inside a
|
|
81
|
+
* Workflow hours or days after the enqueue, in a Worker with no request on it at all, so `c.var.t` —
|
|
82
|
+
* the seam every HTTP surface uses — does not exist at the moment that matters. The locale is on the
|
|
83
|
+
* row for exactly that reason, and this is what turns it back into words.
|
|
84
|
+
*
|
|
85
|
+
* **The two locales stay apart.** `catalogLocale` is the tag as stored — it is what the document
|
|
86
|
+
* declares itself as and what decides text direction — and `formattingLocale` is the same tag handed to
|
|
87
|
+
* `Intl`, so an Argentine reading Spanish still gets Argentine numbers and dates. Collapsing them is
|
|
88
|
+
* the bug `Translator` carries two fields to prevent. Which *catalog* answers a regional tag is
|
|
89
|
+
* {@link catalogLayers}'s question, not this one's.
|
|
90
|
+
*
|
|
91
|
+
* Both of them come from {@link renderLocale}, so a tag `Intl` refuses can reach neither.
|
|
92
|
+
*/
|
|
93
|
+
export declare function emailTranslator(locale: string | null | undefined, layersFor: EmailMessageLayers): Translator;
|
|
94
|
+
//# sourceMappingURL=messages.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/templates/messages.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,cAAc,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,EAAoC,KAAK,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAkIvG;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,EAAE,cAA+C,CAAC;AAE7E;;;;;;;GAOG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,SAAS,CAAC,cAAc,GAAG,SAAS,CAAC,EAAE,CAAC;AAE7F,iHAAiH;AACjH,eAAO,MAAM,cAAc,EAAE,kBAA+D,CAAC;AAsB7F;;;;;;;GAOG;AACH;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,wBAAwB,oBAAoB,CAAC;AAE1D;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAKhE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,cAAc,CAa5E;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,cAAc,GAAG,kBAAkB,CAa1E;AA2BD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,SAAS,EAAE,kBAAkB,GAAG,UAAU,CAG5G"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { MessageCatalog } from "@pithy-sh/core/src/i18n/catalog";
|
|
2
|
+
/**
|
|
3
|
+
* The kit-authored email copy, in Spanish.
|
|
4
|
+
*
|
|
5
|
+
* **Beside the English rather than in `@pithy-sh/i18n`, and that is the point of #442.** The send
|
|
6
|
+
* Workflow runs in its own Worker, deployed by `pithy email provision` with no request and no access
|
|
7
|
+
* to the adopter's config — so anything it does not *bundle* has to be stamped into it as a variable.
|
|
8
|
+
* Held in the translations package, the kit's own Spanish was static data traveling through a
|
|
9
|
+
* configuration channel every provision run, against a 5 KB per-variable ceiling. Held here, the host
|
|
10
|
+
* is built with it and the variable carries only what an adopter changed, which is usually nothing.
|
|
11
|
+
*
|
|
12
|
+
* It also puts this file where the domain rule already says it belongs: a capability may only declare
|
|
13
|
+
* keys under its own name, and `@pithy-sh/email` contributes `email/` in every language it has rather
|
|
14
|
+
* than English alone. `@pithy-sh/i18n` never imports a capability and no capability imports it —
|
|
15
|
+
* principle 4 holds in both directions, which a dependency edge for this data would have broken.
|
|
16
|
+
*
|
|
17
|
+
* Only the seven templates whose words the kit writes — `magicLink`, `otp`, `welcome`,
|
|
18
|
+
* `securityAlert`, `invite`, `passwordChanged`, `leadCapture` — plus the shell: the severity labels
|
|
19
|
+
* and the footer's unsubscribe link.
|
|
20
|
+
*
|
|
21
|
+
* The five templates whose words arrive as payload (`testerNudge`, `supportReply`,
|
|
22
|
+
* `operationalNotice`, `newsletter`, `marketingCampaign`) are the adopter's copy and are not here.
|
|
23
|
+
* **The shell follows the job's locale; a payload-carrying template is only as localized as the
|
|
24
|
+
* adopter's own copy** — a job at locale `es` renders the severity word from this catalog and the
|
|
25
|
+
* summary from the adopter's payload. That is the right behavior and it is a surprise unless stated,
|
|
26
|
+
* so `docs/I18N.md` states both halves.
|
|
27
|
+
*/
|
|
28
|
+
export declare const EMAIL_ES: MessageCatalog;
|
|
29
|
+
//# sourceMappingURL=messages.es.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages.es.d.ts","sourceRoot":"","sources":["../../src/templates/messages.es.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,QAAQ,EAAE,cA2EtB,CAAC"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//#region src/templates/messages.es.ts
|
|
2
|
+
/**
|
|
3
|
+
* The kit-authored email copy, in Spanish.
|
|
4
|
+
*
|
|
5
|
+
* **Beside the English rather than in `@pithy-sh/i18n`, and that is the point of #442.** The send
|
|
6
|
+
* Workflow runs in its own Worker, deployed by `pithy email provision` with no request and no access
|
|
7
|
+
* to the adopter's config — so anything it does not *bundle* has to be stamped into it as a variable.
|
|
8
|
+
* Held in the translations package, the kit's own Spanish was static data traveling through a
|
|
9
|
+
* configuration channel every provision run, against a 5 KB per-variable ceiling. Held here, the host
|
|
10
|
+
* is built with it and the variable carries only what an adopter changed, which is usually nothing.
|
|
11
|
+
*
|
|
12
|
+
* It also puts this file where the domain rule already says it belongs: a capability may only declare
|
|
13
|
+
* keys under its own name, and `@pithy-sh/email` contributes `email/` in every language it has rather
|
|
14
|
+
* than English alone. `@pithy-sh/i18n` never imports a capability and no capability imports it —
|
|
15
|
+
* principle 4 holds in both directions, which a dependency edge for this data would have broken.
|
|
16
|
+
*
|
|
17
|
+
* Only the seven templates whose words the kit writes — `magicLink`, `otp`, `welcome`,
|
|
18
|
+
* `securityAlert`, `invite`, `passwordChanged`, `leadCapture` — plus the shell: the severity labels
|
|
19
|
+
* and the footer's unsubscribe link.
|
|
20
|
+
*
|
|
21
|
+
* The five templates whose words arrive as payload (`testerNudge`, `supportReply`,
|
|
22
|
+
* `operationalNotice`, `newsletter`, `marketingCampaign`) are the adopter's copy and are not here.
|
|
23
|
+
* **The shell follows the job's locale; a payload-carrying template is only as localized as the
|
|
24
|
+
* adopter's own copy** — a job at locale `es` renders the severity word from this catalog and the
|
|
25
|
+
* summary from the adopter's payload. That is the right behavior and it is a surprise unless stated,
|
|
26
|
+
* so `docs/I18N.md` states both halves.
|
|
27
|
+
*/
|
|
28
|
+
const EMAIL_ES = {
|
|
29
|
+
"email/shell.greeting": "Hola:",
|
|
30
|
+
"email/shell.greeting_named": "Hola {name}:",
|
|
31
|
+
"email/shell.unsubscribe": "Cancelar la suscripción",
|
|
32
|
+
"email/severity.info": "Aviso",
|
|
33
|
+
"email/severity.warning": "Requiere acción",
|
|
34
|
+
"email/severity.critical": "Crítico",
|
|
35
|
+
"email/magic_link.subject": "Tu enlace de acceso",
|
|
36
|
+
"email/magic_link.heading": "Iniciar sesión",
|
|
37
|
+
"email/magic_link.instruction": "usa el botón de abajo para iniciar sesión.",
|
|
38
|
+
"email/magic_link.expiry.one": "Caduca en {count} minuto.",
|
|
39
|
+
"email/magic_link.expiry.other": "Caduca en {count} minutos.",
|
|
40
|
+
"email/magic_link.cta": "Iniciar sesión",
|
|
41
|
+
"email/magic_link.ignore": "Si no lo solicitaste, puedes ignorar este correo.",
|
|
42
|
+
"email/magic_link.text_instruction.one": "Usa este enlace para iniciar sesión (caduca en {count} minuto):",
|
|
43
|
+
"email/magic_link.text_instruction.other": "Usa este enlace para iniciar sesión (caduca en {count} minutos):",
|
|
44
|
+
"email/magic_link.text_ignore": "Si no lo solicitaste, ignora este correo.",
|
|
45
|
+
"email/otp.subject": "Tu código de verificación",
|
|
46
|
+
"email/otp.heading": "Tu código",
|
|
47
|
+
"email/otp.lead": "tu código de verificación es:",
|
|
48
|
+
"email/otp.expiry.one": "Caduca en {count} minuto.",
|
|
49
|
+
"email/otp.expiry.other": "Caduca en {count} minutos.",
|
|
50
|
+
"email/otp.text_body.one": "Tu código de verificación es {code}. Caduca en {count} minuto.",
|
|
51
|
+
"email/otp.text_body.other": "Tu código de verificación es {code}. Caduca en {count} minutos.",
|
|
52
|
+
"email/welcome.subject": "Te damos la bienvenida a {app}",
|
|
53
|
+
"email/welcome.heading": "Te damos la bienvenida a {app}",
|
|
54
|
+
"email/welcome.body": "Hola {name}: te damos la bienvenida a {app}. Nos alegra tenerte aquí.",
|
|
55
|
+
"email/welcome.text_body": "Te damos la bienvenida a {app}. Nos alegra tenerte aquí.",
|
|
56
|
+
"email/security_alert.subject": "Alerta de seguridad: {event}",
|
|
57
|
+
"email/security_alert.heading": "Alerta de seguridad",
|
|
58
|
+
"email/security_alert.body": "{event} el {when}.",
|
|
59
|
+
"email/security_alert.ip": "Dirección IP: {ip}.",
|
|
60
|
+
"email/security_alert.text_ip": "IP: {ip}.",
|
|
61
|
+
"email/security_alert.reassure": "Si fuiste tú, no hace falta hacer nada.",
|
|
62
|
+
"email/security_alert.cta": "Revisar la actividad",
|
|
63
|
+
"email/security_alert.text_action": "Si no fuiste tú, protege tu cuenta:",
|
|
64
|
+
"email/invite.subject": "{inviter} te ha invitado a {organization}",
|
|
65
|
+
"email/invite.heading": "Tienes una invitación",
|
|
66
|
+
"email/invite.body": "{inviter} te ha invitado a unirte a {organization} en {app}.",
|
|
67
|
+
"email/invite.cta": "Aceptar la invitación",
|
|
68
|
+
"email/invite.text_accept": "Aceptar:",
|
|
69
|
+
"email/password_changed.subject": "Tu contraseña ha cambiado",
|
|
70
|
+
"email/password_changed.heading": "Tu contraseña ha cambiado",
|
|
71
|
+
"email/password_changed.body": "las credenciales de tu cuenta cambiaron el {when}.",
|
|
72
|
+
"email/password_changed.warn": "Si no fuiste tú, contacta con soporte de inmediato.",
|
|
73
|
+
"email/password_changed.cta": "Contactar con soporte",
|
|
74
|
+
"email/password_changed.text_body": "Las credenciales de tu cuenta cambiaron el {when}. Si no fuiste tú, contacta con soporte:",
|
|
75
|
+
"email/lead_capture.subject": "Tu descarga: {asset}",
|
|
76
|
+
"email/lead_capture.heading": "Tu descarga está lista",
|
|
77
|
+
"email/lead_capture.ready": "Tu copia de {asset} ya está lista.",
|
|
78
|
+
"email/lead_capture.cta": "Descargar ahora",
|
|
79
|
+
"email/lead_capture.text_ready": "Tu copia de {asset} ya está lista:"
|
|
80
|
+
};
|
|
81
|
+
//#endregion
|
|
82
|
+
export { EMAIL_ES };
|