@email-kit/cli 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/dist/cli.js +654 -40
- package/dist/docs/guide/checks-and-ci.md +158 -0
- package/dist/docs/guide/components.md +426 -0
- package/dist/docs/guide/formatting.md +77 -0
- package/dist/docs/guide/messages.md +147 -0
- package/dist/docs/guide/sending.md +242 -0
- package/dist/docs/guide/templates.md +269 -0
- package/dist/docs/guide/theme.md +212 -0
- package/dist/docs/reference/checks.md +876 -0
- package/dist/docs/reference/cli.md +214 -0
- package/dist/docs/reference/configuration.md +115 -0
- package/dist/docs/reference/errors.md +264 -0
- package/dist/docs/reference/mustache-core.md +340 -0
- package/dist/skill/email-kit/SKILL.md +326 -0
- package/package.json +4 -4
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
<!-- Generated from docs/guide/messages.md for AI coding agents: run `pnpm --filter @email-kit/cli test -u` after changing the docs. -->
|
|
2
|
+
|
|
3
|
+
# Messages and locales
|
|
4
|
+
|
|
5
|
+
Every word an email shows lives in message files, one per template and locale, beside the
|
|
6
|
+
template: `order-shipped/messages.en.json`, `order-shipped/messages.de.json`. Each is a flat
|
|
7
|
+
object of keys and [ICU messages](https://unicode-org.github.io/icu/userguide/format_parse/messages/).
|
|
8
|
+
Templates are compiled once per locale, from that locale's file.
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
order-shipped/
|
|
12
|
+
template.tsx
|
|
13
|
+
messages.en.json
|
|
14
|
+
messages.de.json
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Messages
|
|
18
|
+
|
|
19
|
+
`t(key, params)` looks a message up in the locale being compiled:
|
|
20
|
+
|
|
21
|
+
```json
|
|
22
|
+
{
|
|
23
|
+
"heading": "Thanks, {name}!",
|
|
24
|
+
"items": "{count, plural, one {# item} other {# items}}"
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
<Heading>{t("heading", { name: data.customerName })}</Heading>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Every locale needs every key the template uses, and `t()` must pass exactly the parameters the
|
|
33
|
+
message uses: a missing key, a missing parameter or an unused one fails the compile.
|
|
34
|
+
|
|
35
|
+
A parameter can be text, a number, a data field, a sender value, or another message:
|
|
36
|
+
`t("footer", { product: sender.productName })`. `subject` and `preheader` get `t` too:
|
|
37
|
+
`subject: (data, t) => t("subject", { order: data.orderNumber })`.
|
|
38
|
+
|
|
39
|
+
Keys in a message file that no template uses are reported by `check` (`i18n.unused-keys`).
|
|
40
|
+
|
|
41
|
+
### Typed t()
|
|
42
|
+
|
|
43
|
+
`email-kit compile` writes `_generated/messages.d.ts` from the default locale's messages. With it in
|
|
44
|
+
your TypeScript project, `t()` knows each template's keys and parameters: a misspelt key, a
|
|
45
|
+
missing parameter or a string passed to a plural is an editor error. Until the first compile,
|
|
46
|
+
`t()` is untyped.
|
|
47
|
+
|
|
48
|
+
### Plurals
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{ "expiry": "It expires in {minutes, plural, one {# minute} other {# minutes}}." }
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
<Text>{t("expiry", { minutes: data.minutes })}</Text>
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A plural takes a number field (or a literal number). Its category is chosen at send time with the
|
|
59
|
+
locale's CLDR plural rules, which the generated module carries. `#` prints the number as digits,
|
|
60
|
+
without locale formatting.
|
|
61
|
+
|
|
62
|
+
The message must give every category the locale uses, so no number falls through: `one` and
|
|
63
|
+
`other` in English and German, `zero`, `one`, `two`, `few`, `many` and `other` in Arabic. A
|
|
64
|
+
category the locale never uses is an error too; English has no `zero`, so write `=0` for exactly
|
|
65
|
+
zero. `=N` cases match exact whole numbers before the categories:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
{ "trial": "{days, plural, =1 {Your trial ends tomorrow.} one {Your trial ends in # day.} other {Your trial ends in # days.}}" }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`other` is always required, and plural offsets aren't supported. See
|
|
72
|
+
[`invalid-plural`](../reference/errors.md#invalid-plural).
|
|
73
|
+
|
|
74
|
+
### Selects
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{ "shipping": "Sent with {carrier, select, dhl {DHL} ups {UPS} other {our courier}}." }
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A select takes a field with fixed values, such as `z.enum(["dhl", "ups", "other"])`. Each case
|
|
81
|
+
must be one of its values, and `other` is required. A free string field is refused
|
|
82
|
+
([`invalid-select`](../reference/errors.md#invalid-select)).
|
|
83
|
+
|
|
84
|
+
### What messages can't do
|
|
85
|
+
|
|
86
|
+
Only plain `{name}` arguments, `plural` and `select` are supported. `{amount, number}`,
|
|
87
|
+
`{date, date}` and the like fail the compile ([`unsupported-message`](../reference/errors.md#unsupported-message)):
|
|
88
|
+
pass the value formatted by your backend as a string instead. See
|
|
89
|
+
[Formatting dates, money and numbers](formatting.md).
|
|
90
|
+
|
|
91
|
+
ICU quoting applies: `'{'` is a literal brace and `''` is an apostrophe. An apostrophe on its own,
|
|
92
|
+
as in "You're", needs no quoting.
|
|
93
|
+
|
|
94
|
+
## Locales
|
|
95
|
+
|
|
96
|
+
The config lists the locales to compile:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
locales: {
|
|
100
|
+
default: "en",
|
|
101
|
+
list: ["en", "de", "pt-BR"],
|
|
102
|
+
fallback: { pt: "pt-BR" },
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Field | Default | |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| `default` | `"en"` | The locale `render()` falls back to. It's first in the output |
|
|
109
|
+
| `list` | only the default | Every locale to compile. It must include the default |
|
|
110
|
+
| `fallback` | `{}` | Where a requested locale goes when no compiled locale matches it, before CLDR's parents. `{ pt: "pt-BR" }` sends `pt` and `pt-AO` to Brazilian Portuguese. Each key must not be compiled; each value must be |
|
|
111
|
+
| `pseudo` | `false` | Also compile and ship the [pseudo-locales](#pseudo-locales) |
|
|
112
|
+
|
|
113
|
+
Tags must be canonical BCP 47: `en`, `pt-BR`, `zh-Hant`, not `en_US` or `pt-br`.
|
|
114
|
+
|
|
115
|
+
### Adding a locale
|
|
116
|
+
|
|
117
|
+
1. Add it to `locales.list`.
|
|
118
|
+
2. Add a `messages.<locale>.json` with every key to each template's folder. The compile names
|
|
119
|
+
each missing file and key ([`missing-message`](../reference/errors.md#missing-message)).
|
|
120
|
+
3. Compile.
|
|
121
|
+
|
|
122
|
+
`email-kit new` writes a message file for every locale in the config, each with the same starter
|
|
123
|
+
copy for translators to replace.
|
|
124
|
+
|
|
125
|
+
### Choosing a locale at send time
|
|
126
|
+
|
|
127
|
+
`render(data, { locale })` takes any BCP 47 tag, in any case, with `-` or `_`. When no compiled
|
|
128
|
+
locale matches, it tries your `fallback` map and CLDR's parent locales, dropping subtags as it
|
|
129
|
+
goes (`de-AT` to `de`, `es-AR` to `es-419` to `es`), and ends at the default locale.
|
|
130
|
+
`meta.locale` says which locale was used. See [Rendering and sending](sending.md#locales).
|
|
131
|
+
|
|
132
|
+
### Right-to-left languages
|
|
133
|
+
|
|
134
|
+
A locale whose language is written right to left (Arabic, Hebrew, Persian, Urdu and a few others)
|
|
135
|
+
gets `dir="rtl"`, and the components align to match.
|
|
136
|
+
|
|
137
|
+
### Pseudo-locales
|
|
138
|
+
|
|
139
|
+
Two pseudo-locales are generated from the default locale's messages, for testing layout without
|
|
140
|
+
translations:
|
|
141
|
+
|
|
142
|
+
- `en-XA`: accented, bracketed and padded up to three times longer, to show truncation and
|
|
143
|
+
overflow;
|
|
144
|
+
- `ar-XB`: wrapped in right-to-left overrides, to show mirroring problems.
|
|
145
|
+
|
|
146
|
+
`email-kit check` builds both every time and runs the checks on them. To ship them in the module,
|
|
147
|
+
for QA on staging, set `locales.pseudo: true`, or a list such as `["en-XA"]`.
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
<!-- Generated from docs/guide/sending.md for AI coding agents: run `pnpm --filter @email-kit/cli test -u` after changing the docs. -->
|
|
2
|
+
|
|
3
|
+
# Rendering and sending
|
|
4
|
+
|
|
5
|
+
`email-kit compile` writes one module, `<out>/index.ts` (or `index.mjs` with `index.d.mts`), that
|
|
6
|
+
your server imports. It holds your templates, already parsed, with their types, and renders them
|
|
7
|
+
with [`@email-kit/runtime`](https://github.com/email-kit/email-kit/blob/main/packages/runtime/README.md): the only email-kit package your app
|
|
8
|
+
needs when it runs, so it's a `dependency` while everything else is a devDependency. The runtime
|
|
9
|
+
has no dependencies, and the module imports only the parts of it your templates use (about 1.5 KB
|
|
10
|
+
to 3 KB, minified and gzipped). email-kit doesn't send email; you hand what `render()` returns to
|
|
11
|
+
whatever sends your mail.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { EmailRenderError, emails } from "@/email-kit"
|
|
15
|
+
|
|
16
|
+
const email = emails.orderShipped.render(
|
|
17
|
+
{
|
|
18
|
+
name: "Ada",
|
|
19
|
+
orderNumber: "A-1042",
|
|
20
|
+
carrier: "dhl",
|
|
21
|
+
trackingUrl: "https://track.example.com/A-1042",
|
|
22
|
+
deliveryDate: "3 November 2026",
|
|
23
|
+
itemCount: 2,
|
|
24
|
+
items: [
|
|
25
|
+
{ name: "Tea", qty: 1 },
|
|
26
|
+
{ name: "Cake", qty: 1 },
|
|
27
|
+
],
|
|
28
|
+
express: false,
|
|
29
|
+
},
|
|
30
|
+
{ locale: "en-GB" },
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
email.subject // "Order A-1042 has shipped"
|
|
34
|
+
email.html // the HTML part
|
|
35
|
+
email.text // the plain-text part
|
|
36
|
+
email.meta // { id: "order-shipped", locale: "en", purpose: "transactional" }
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## What the module exports
|
|
40
|
+
|
|
41
|
+
| Export | |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `emails` | Every template, by the camelCase form of its id: `order-shipped` is `emails.orderShipped`. Only when the config has no [runtime sender values](#runtime-sender-values) |
|
|
44
|
+
| `createEmails(context)` | Builds the same object with the values that differ by environment. Always exported |
|
|
45
|
+
| `locales` | The compiled locales, the default first |
|
|
46
|
+
| `EmailRenderError` | The error `render()` and `createEmails()` throw. See [Errors](#errors) |
|
|
47
|
+
|
|
48
|
+
And these types:
|
|
49
|
+
|
|
50
|
+
| Type | |
|
|
51
|
+
|---|---|
|
|
52
|
+
| `OrderShippedData` (one per template) | The data `render()` takes, from the schema. A [`formatted`](templates.md#field-markers) field carries a comment saying how to format it |
|
|
53
|
+
| `TemplateId`, `Locale`, `Purpose` | Unions of the template ids, the compiled locales and the purposes |
|
|
54
|
+
| `Emails`, `EmailTemplate<Id, Data, Locale>` | The `emails` object and one entry of it |
|
|
55
|
+
| `RenderOptions`, `RenderedEmail<Id>`, `EmailParts` | `render()`'s options and result |
|
|
56
|
+
| `EmailContext` | What `createEmails()` takes |
|
|
57
|
+
| `DataIssue` | `{ path, message }`: one value that doesn't match the schema |
|
|
58
|
+
|
|
59
|
+
## Each email
|
|
60
|
+
|
|
61
|
+
| Member | |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `render(data, options?)` | Validates the data, picks the locale and fills the templates. Returns a `RenderedEmail` |
|
|
64
|
+
| `validate(data)` | Checks data against the schema without rendering. Returns a list of `DataIssue`s, empty when the data is valid. Not there with `validate: false`, which leaves the validator out of your bundle |
|
|
65
|
+
| `meta` | `{ id, purpose, locales }` |
|
|
66
|
+
|
|
67
|
+
`render()` returns:
|
|
68
|
+
|
|
69
|
+
| Field | |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `subject` | The subject line |
|
|
72
|
+
| `preheader` | The inbox preview text. It's already in `html` (hidden, at the top) and at the start of `text`, so you don't send it separately |
|
|
73
|
+
| `html` | The HTML part: a complete document |
|
|
74
|
+
| `text` | The plain-text part |
|
|
75
|
+
| `meta` | `{ id, locale, purpose }`, where `locale` is the compiled locale that was used |
|
|
76
|
+
|
|
77
|
+
Send `html` and `text` together, as a `multipart/alternative` message with `subject`.
|
|
78
|
+
|
|
79
|
+
### What render() does
|
|
80
|
+
|
|
81
|
+
1. Validates the data against the template's schema, unless the config sets `validate: false`.
|
|
82
|
+
2. Resolves the requested locale to a compiled one (see [Locales](#locales)).
|
|
83
|
+
3. Copies the data onto the schema: keys the schema doesn't declare are dropped, and missing
|
|
84
|
+
optional keys become `null`, so they count as missing.
|
|
85
|
+
4. Fills the templates. Values are HTML-escaped (`&`, `<`, `>`, `"`, `'`) in `html`, and inserted
|
|
86
|
+
as they are in `text` and `subject`.
|
|
87
|
+
5. Refuses a subject that contains a line break, which would let data inject mail headers.
|
|
88
|
+
|
|
89
|
+
## Data validation
|
|
90
|
+
|
|
91
|
+
`render()` checks the data against the schema before rendering: types, required and nullable
|
|
92
|
+
fields, enum values, length and range limits, patterns, and `https://` for [`url`](templates.md#field-markers)
|
|
93
|
+
fields. Bad data throws an `EmailRenderError` with the code `invalid-data`, and every problem with
|
|
94
|
+
its path:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
The data for "order-shipped" doesn't match its schema:
|
|
98
|
+
trackingUrl: must be an https URL, got "http://x.example"
|
|
99
|
+
itemCount: expected a number, got "2"
|
|
100
|
+
items[0].name: must be at least 1 character
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`error.issues` has the same problems as a list:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
try {
|
|
107
|
+
const email = emails.orderShipped.render(data)
|
|
108
|
+
// send it
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof EmailRenderError && error.code === "invalid-data") {
|
|
111
|
+
console.error(error.issues) // [{ path: "itemCount", message: 'expected a number, got "2"' }, …]
|
|
112
|
+
}
|
|
113
|
+
throw error
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Use `validate(data)` to check data before queueing it, or when it arrives from a queue or webhook:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const issues = emails.orderShipped.validate(payload)
|
|
121
|
+
if (issues.length > 0) return Response.json({ issues }, { status: 400 })
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The generated types catch most mistakes in TypeScript; validation is for data whose type the
|
|
125
|
+
compiler can't see. With `validate: false` in the config, the module doesn't import the validator:
|
|
126
|
+
`render()` skips it, there's no `validate()`, and bad data either throws an `EmailRenderError`
|
|
127
|
+
from the renderer (such as `missing-value`) or renders as given.
|
|
128
|
+
|
|
129
|
+
## Locales
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
emails.orderShipped.render(data, { locale: "de-AT" }).meta.locale // "de"
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`locale` takes any BCP 47 tag, in any case, with `-` or `_`. When no compiled locale matches, the
|
|
136
|
+
module tries your `locales.fallback` map and CLDR's parent locales, dropping subtags as it goes
|
|
137
|
+
(`de-AT` to `de`, `es-AR` to `es-419` to `es`), and ends at the default locale. Without `locale`,
|
|
138
|
+
it renders the default. `meta.locale` says which locale was used.
|
|
139
|
+
|
|
140
|
+
Pass the same locale you used to format dates and amounts for the recipient (see
|
|
141
|
+
[Formatting dates, money and numbers](formatting.md)).
|
|
142
|
+
|
|
143
|
+
## Runtime sender values
|
|
144
|
+
|
|
145
|
+
A sender value set to `{ runtime: true }` in the config is passed by your backend, once:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// email-kit.config.ts
|
|
149
|
+
sender: { productName: "Acme", siteUrl: { runtime: true } }
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
// at startup
|
|
154
|
+
import { createEmails } from "@/email-kit"
|
|
155
|
+
|
|
156
|
+
export const emails = createEmails({ siteUrl: process.env.SITE_URL ?? "" })
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The module then exports `createEmails()` but no ready-made `emails`, so you can't forget the
|
|
160
|
+
values. `createEmails()` throws an `EmailRenderError` with the code `missing-context` if a runtime
|
|
161
|
+
key is missing or empty, and `invalid-context` if `siteUrl`, `helpUrl` or `privacyUrl` isn't an
|
|
162
|
+
`https://` URL or `supportEmail` isn't an email address: the rules the config applies to values set
|
|
163
|
+
there. Data passed to `render()` can't override them. Call `createEmails()` once and reuse the result.
|
|
164
|
+
|
|
165
|
+
## Per-template modules
|
|
166
|
+
|
|
167
|
+
With `perTemplateEntries: true` in the config, the compiler also writes `<out>/<id>/index.ts`
|
|
168
|
+
(`index.mjs` and `index.d.mts` with `module: "mjs"`): a module with the same API and only that one
|
|
169
|
+
email, for a function that sends one kind of email and should bundle nothing else. Import it by its
|
|
170
|
+
path in the output folder:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import { emails } from "./email-kit/_generated/order-shipped/index.ts"
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Errors
|
|
177
|
+
|
|
178
|
+
`EmailRenderError` has a `code`, a `message` and, for `invalid-data`, `issues`:
|
|
179
|
+
|
|
180
|
+
| Code | When |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `invalid-data` | The data doesn't match the schema |
|
|
183
|
+
| `missing-context` | `createEmails()` lacks a runtime sender value, or it's empty |
|
|
184
|
+
| `invalid-context` | A URL sender value passed to `createEmails()` isn't `https://`, or `supportEmail` isn't an email address |
|
|
185
|
+
| `subject-line-break` | The rendered subject contains CR or LF, usually from user data. Strip line breaks before rendering |
|
|
186
|
+
| `missing-value`, `non-scalar-value`, `invalid-number` | A value can't fill its placeholder (spec [§10](../reference/mustache-core.md#10-errors)). With validation on, data that passes it doesn't cause these |
|
|
187
|
+
| `incompatible-module` | The installed `@email-kit/runtime` is a different version from the CLI that compiled the module. Install the same version and run `email-kit compile` |
|
|
188
|
+
|
|
189
|
+
See the [error reference](../reference/errors.md#at-send-time).
|
|
190
|
+
|
|
191
|
+
## Sending
|
|
192
|
+
|
|
193
|
+
email-kit has no integration with mail providers: pass the parts to the library or API you
|
|
194
|
+
already use. With [Nodemailer](https://nodemailer.com/) over SMTP:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import nodemailer from "nodemailer"
|
|
198
|
+
|
|
199
|
+
import { emails, type OrderShippedData } from "@/email-kit"
|
|
200
|
+
|
|
201
|
+
const transport = nodemailer.createTransport({
|
|
202
|
+
host: process.env.SMTP_HOST,
|
|
203
|
+
port: 587,
|
|
204
|
+
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD },
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
export async function sendOrderShipped(to: string, data: OrderShippedData, locale: string) {
|
|
208
|
+
const { subject, html, text } = emails.orderShipped.render(data, { locale })
|
|
209
|
+
await transport.sendMail({ from: "Acme <orders@acme.example>", to, subject, html, text })
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Or with an HTTP API, such as Resend's, using `fetch`:
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
const { subject, html, text } = emails.orderShipped.render(data, { locale })
|
|
217
|
+
|
|
218
|
+
const response = await fetch("https://api.resend.com/emails", {
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers: {
|
|
221
|
+
Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
|
|
222
|
+
"Content-Type": "application/json",
|
|
223
|
+
},
|
|
224
|
+
body: JSON.stringify({ from: "Acme <orders@acme.example>", to, subject, html, text }),
|
|
225
|
+
})
|
|
226
|
+
if (!response.ok) throw new Error(`Sending failed: ${response.status}`)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Other providers' APIs take the same three parts under their own field names; check your
|
|
230
|
+
provider's reference.
|
|
231
|
+
|
|
232
|
+
## Other backends
|
|
233
|
+
|
|
234
|
+
With `contract: true` in the config, the output folder also holds each email as files:
|
|
235
|
+
`<id>/<locale>.html` and `.txt` with `{{placeholders}}`, `<id>/schema.json` (JSON Schema 2020-12)
|
|
236
|
+
and `manifest.json` with the subjects, preheaders and hashes.
|
|
237
|
+
|
|
238
|
+
They're written in [mustache-core](../reference/mustache-core.md), a small subset of Mustache. A
|
|
239
|
+
backend in another language can render them with a renderer that follows the spec, including the
|
|
240
|
+
data preparation for plurals and selects (§15) and the locale resolution (§16). email-kit only
|
|
241
|
+
ships the JavaScript renderer, `@email-kit/runtime`; the
|
|
242
|
+
[conformance suite](https://github.com/email-kit/email-kit/blob/main/conformance/mustache-core/README.md) is there to test others.
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
<!-- Generated from docs/guide/templates.md for AI coding agents: run `pnpm --filter @email-kit/cli test -u` after changing the docs. -->
|
|
2
|
+
|
|
3
|
+
# Templates
|
|
4
|
+
|
|
5
|
+
Each template is a folder in the email-kit folder (`root`), named by its id: `order-shipped/`
|
|
6
|
+
holds `template.tsx`, whose default export is `defineEmail({ … })`, and its messages, one
|
|
7
|
+
`messages.<locale>.json` per locale. The `id` in `defineEmail()` must match the folder's name.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
src/email-kit/
|
|
11
|
+
order-shipped/
|
|
12
|
+
template.tsx
|
|
13
|
+
messages.en.json
|
|
14
|
+
messages.de.json
|
|
15
|
+
_shared/ components the templates import; folders starting with _ are never templates
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
For a step-by-step walkthrough, see [Your first email](https://email-kit.dev/guide/first-email). A template file looks
|
|
19
|
+
like this:
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
/** @jsxImportSource @email-kit/core */
|
|
23
|
+
import { Button, Footer, Heading, Text } from "@email-kit/components"
|
|
24
|
+
import { defineEmail, url } from "@email-kit/core"
|
|
25
|
+
import { z } from "zod"
|
|
26
|
+
|
|
27
|
+
export default defineEmail({
|
|
28
|
+
id: "password-reset",
|
|
29
|
+
purpose: "transactional",
|
|
30
|
+
schema: z.object({ name: z.string().min(1), resetUrl: z.string().meta(url) }),
|
|
31
|
+
subject: (data, t) => t("subject"),
|
|
32
|
+
preheader: (data, t) => t("preheader"),
|
|
33
|
+
fixtures: { default: { name: "Ada", resetUrl: "https://example.com/reset/abc" } },
|
|
34
|
+
component: ({ data, t, sender }) => (
|
|
35
|
+
<>
|
|
36
|
+
<Heading>{t("heading", { name: data.name })}</Heading>
|
|
37
|
+
<Text>{t("body")}</Text>
|
|
38
|
+
<Button href={data.resetUrl}>{t("cta")}</Button>
|
|
39
|
+
<Footer reason={t("footer", { product: sender.productName })} sender={sender.productName} />
|
|
40
|
+
</>
|
|
41
|
+
),
|
|
42
|
+
})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The first line, `/** @jsxImportSource @email-kit/core */`, tells TypeScript and your editor which
|
|
46
|
+
JSX types the file uses, so templates type-check in a project whose JSX is set up for React or
|
|
47
|
+
Hono. The compiler always uses email-kit's JSX, with or without it.
|
|
48
|
+
|
|
49
|
+
You can leave it out when your `tsconfig.json` sets `"jsxImportSource": "@email-kit/core"`.
|
|
50
|
+
`init` sets it for you when the project has no JSX of its own, and `email-kit new` writes the line
|
|
51
|
+
only when the tsconfig doesn't set it. `check` warns about a template or component that needs the
|
|
52
|
+
line and lacks it ([`source.jsx-pragma`](../reference/checks.md#sourcejsx-pragma)).
|
|
53
|
+
|
|
54
|
+
## How templates run
|
|
55
|
+
|
|
56
|
+
Templates run once per locale, when you compile, never when you send. At that point `data` holds
|
|
57
|
+
placeholders, not values: `{data.name}` becomes `{{name}}` in the output, and the generated module
|
|
58
|
+
fills it at send time.
|
|
59
|
+
|
|
60
|
+
So a template can place data but can't compute with it. Arithmetic, string methods, template
|
|
61
|
+
literals and `.map()` on a data field fail the compile with
|
|
62
|
+
[`placeholder-misuse`](../reference/errors.md#placeholder-misuse). Compute the value in your backend and pass
|
|
63
|
+
it as a field of its own, and use `<Each>` for lists.
|
|
64
|
+
|
|
65
|
+
Conditions that don't depend on data are plain JavaScript, decided when the template compiles:
|
|
66
|
+
|
|
67
|
+
```tsx
|
|
68
|
+
{showSurvey && <Text>{t("survey")}</Text>}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`style` values are fixed at compile time too; choose between fixed styles with `<If>` and
|
|
72
|
+
`<Unless>`.
|
|
73
|
+
|
|
74
|
+
## defineEmail
|
|
75
|
+
|
|
76
|
+
| Field | Type | Required | What it is |
|
|
77
|
+
|---|---|---|---|
|
|
78
|
+
| `id` | `string` | yes | Lowercase words joined by hyphens, such as `order-shipped`. It's the name of the template's folder, and becomes `emails.orderShipped` and the type `OrderShippedData`. Don't rename an id that has shipped: backends call it by name |
|
|
79
|
+
| `purpose` | `"transactional"`, `"marketing"` or `"consent-request"` | yes | The legal purpose. It's recorded in `render()`'s `meta` (and the manifest, with `contract: true`), and the compile fails without it (`legal.purpose-declared`). `marketing` and `consent-request` emails must show a postal address (`legal.postal-address`); the marketing footer parts (unsubscribe) don't exist yet |
|
|
80
|
+
| `schema` | a Zod 4, Valibot or ArkType 2 schema | yes | The data the email takes. `data`, `fixtures` and the generated types come from it |
|
|
81
|
+
| `subject` | `(data, t, sender) => …` | yes | The subject line: text only, one line |
|
|
82
|
+
| `preheader` | `(data, t, sender) => …` | no | The inbox preview text after the subject: one line. Without it `check` warns (`preheader.length`) |
|
|
83
|
+
| `fixtures` | `{ [name]: data }` | yes | Named sample data. Each one must match the schema, and there must be at least one |
|
|
84
|
+
| `component` | `({ data, t, locale, sender }) => …` | yes | The body |
|
|
85
|
+
|
|
86
|
+
The component's props:
|
|
87
|
+
|
|
88
|
+
| Prop | What it is |
|
|
89
|
+
|---|---|
|
|
90
|
+
| `data` | The data, as placeholders typed from the schema |
|
|
91
|
+
| `t` | Looks up a message in the locale being compiled. See [Messages and locales](messages.md) |
|
|
92
|
+
| `locale` | The locale being compiled, such as `"de"` |
|
|
93
|
+
| `sender` | Values from the config, such as `sender.productName`. See [Sender values](#sender-values) |
|
|
94
|
+
|
|
95
|
+
You don't add `<html>`, `<head>` or a page container: the compiler writes the document around the
|
|
96
|
+
body and centres it in a container of the theme's width (600px by default).
|
|
97
|
+
|
|
98
|
+
## Schemas
|
|
99
|
+
|
|
100
|
+
The schema describes the data `render()` takes. Three libraries are supported:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// Zod 4
|
|
104
|
+
import { z } from "zod"
|
|
105
|
+
z.object({ name: z.string().min(1), resetUrl: z.string().meta(url) })
|
|
106
|
+
|
|
107
|
+
// Valibot, with @valibot/to-json-schema installed as a devDependency
|
|
108
|
+
import * as v from "valibot"
|
|
109
|
+
v.object({ name: v.pipe(v.string(), v.minLength(1)), resetUrl: v.pipe(v.string(), v.metadata(url)) })
|
|
110
|
+
|
|
111
|
+
// ArkType 2
|
|
112
|
+
import { type } from "arktype"
|
|
113
|
+
type({ name: "string > 0", resetUrl: type.string.configure(url) })
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
email-kit converts the schema to JSON Schema (written as `schema.json` with `contract: true`, and
|
|
117
|
+
into the module's data types either way). It must stay within
|
|
118
|
+
a portable subset that backends in other languages can also represent, or the compile fails with
|
|
119
|
+
[`schema-not-portable`](../reference/errors.md#schema-not-portable), naming the field:
|
|
120
|
+
|
|
121
|
+
- strings (optionally an enum), numbers, integers, booleans, arrays and objects, each optionally
|
|
122
|
+
nullable or optional;
|
|
123
|
+
- the constraints `minLength`, `maxLength`, `pattern`, `minimum`, `maximum`, `exclusiveMinimum`,
|
|
124
|
+
`exclusiveMaximum`, `multipleOf`, `minItems` and `maxItems`;
|
|
125
|
+
- no unions, records, tuples, `Date`, `bigint`, `any`, defaults or transforms.
|
|
126
|
+
|
|
127
|
+
Dates and amounts arrive as strings your backend has formatted (see
|
|
128
|
+
[Formatting dates, money and numbers](formatting.md)). Field names are letters, digits
|
|
129
|
+
and `_`.
|
|
130
|
+
|
|
131
|
+
Constraints matter beyond validation. `check` renders each template with generated data as well
|
|
132
|
+
as your fixtures: an empty variant (optional fields left out, strings at their minimum length), a
|
|
133
|
+
long one (long strings, 25 items per list unless `maxItems` says fewer) and a hostile one (markup,
|
|
134
|
+
quotes and braces). A required name without `.min(1)` renders as "Thanks, !" in the empty variant,
|
|
135
|
+
which `copy.placeholder-fallbacks` reports; a list without a maximum can push the long variant
|
|
136
|
+
past Gmail's clipping size (`size.gmail`).
|
|
137
|
+
|
|
138
|
+
With ArkType, `configure()` accepts the markers as they are: `@email-kit/core` declares its
|
|
139
|
+
metadata key on ArkType's global `ArkEnv`, so no declaration of your own is needed.
|
|
140
|
+
|
|
141
|
+
## Field markers
|
|
142
|
+
|
|
143
|
+
Markers are schema metadata from `@email-kit/core`. They reach the generated module, and with
|
|
144
|
+
`contract: true` they're written into `schema.json` under `"x-email-kit"`, so they survive into
|
|
145
|
+
every backend.
|
|
146
|
+
|
|
147
|
+
| Marker | Zod | Means |
|
|
148
|
+
|---|---|---|
|
|
149
|
+
| `url` | `z.string().meta(url)` | A URL. Only `url` fields may start an `href` or `src` (`link.url-fields`), and `render()` refuses a value that isn't an `https://` URL |
|
|
150
|
+
| `secret` | `z.string().meta(secret)` | A code or token. `check` fails if it appears in the subject or preheader (`subject.no-secret`) |
|
|
151
|
+
| `secretUrl` | `z.string().meta(secretUrl)` | Both: a URL that carries a token, such as a magic link |
|
|
152
|
+
| `formatted(kind)` | `z.string().meta(formatted("money"))` | A value your backend formats for the recipient. `kind` is `date`, `time`, `date-time`, `money`, `number` or `percent`. It adds a comment to the generated data type saying how to format it |
|
|
153
|
+
|
|
154
|
+
With Valibot, use `v.pipe(v.string(), v.metadata(url))`; with ArkType,
|
|
155
|
+
`type.string.configure(url)`.
|
|
156
|
+
|
|
157
|
+
A literal URL in a template (`href="https://help.example.com"`) must start with `https://`,
|
|
158
|
+
`mailto:` or `tel:`.
|
|
159
|
+
|
|
160
|
+
## Fixtures
|
|
161
|
+
|
|
162
|
+
Fixtures are named sample data. `check` renders every one, and the compile fails with
|
|
163
|
+
[`invalid-fixture`](../reference/errors.md#invalid-fixture) if one doesn't match the schema. The first
|
|
164
|
+
fixture is the base for the generated variants. Add fixtures for the cases that change the email,
|
|
165
|
+
such as an optional field left out or a count of one.
|
|
166
|
+
|
|
167
|
+
Fixtures can live in a JSON file:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import fixtures from "../fixtures/receipt.json" with { type: "json" }
|
|
171
|
+
|
|
172
|
+
defineEmail({ /* … */ fixtures })
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Control flow
|
|
176
|
+
|
|
177
|
+
`If`, `Unless` and `Each` choose content at send time, from a data field. They come from
|
|
178
|
+
`@email-kit/core`.
|
|
179
|
+
|
|
180
|
+
```tsx
|
|
181
|
+
<If when={data.express}>
|
|
182
|
+
<Text>{t("express")}</Text>
|
|
183
|
+
</If>
|
|
184
|
+
|
|
185
|
+
<Unless when={data.express}>
|
|
186
|
+
<Text>{t("standard")}</Text>
|
|
187
|
+
</Unless>
|
|
188
|
+
|
|
189
|
+
<If when={data.giftMessage}>
|
|
190
|
+
{(message) => <Text>{t("gift", { message })}</Text>}
|
|
191
|
+
</If>
|
|
192
|
+
|
|
193
|
+
<Each of={data.items}>
|
|
194
|
+
{(item) => <ListItem>{item.name} × {item.qty}</ListItem>}
|
|
195
|
+
</Each>
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
| Component | Props | Renders |
|
|
199
|
+
|---|---|---|
|
|
200
|
+
| `If` | `when`: an optional or nullable field that isn't a list, or a boolean field; `children`: content, or a function that receives the field | Its content once, when the field is present (or `true`) |
|
|
201
|
+
| `Unless` | `when`: an optional, nullable, boolean or list field; `children` | Its content when the field is missing (or `false`, or an empty list) |
|
|
202
|
+
| `Each` | `of`: a list field, optional or not; `children`: a function that receives the item | Its content once per item, and nothing for an empty or missing list |
|
|
203
|
+
|
|
204
|
+
With a function child, `If` passes the field as a required value, so it can go where a required
|
|
205
|
+
one is expected, such as a `t()` parameter.
|
|
206
|
+
|
|
207
|
+
`If` doesn't take a list, since a list section repeats its content per item
|
|
208
|
+
([`list-condition`](../reference/errors.md#list-condition)). Use `<Each>` for the items and `<Unless>` for
|
|
209
|
+
the empty case. When content around the items, such as a heading or a `<List>`, should only show
|
|
210
|
+
when there are items, wrap the list in an optional object and test that:
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
// schema: team: z.object({ name: z.string(), members: z.array(…).min(1) }).optional()
|
|
214
|
+
<If when={data.team}>
|
|
215
|
+
{(team) => (
|
|
216
|
+
<List>
|
|
217
|
+
<Each of={team.members}>{(member) => <ListItem>{member.name}</ListItem>}</Each>
|
|
218
|
+
</List>
|
|
219
|
+
)}
|
|
220
|
+
</If>
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
"Missing" follows the [placeholder language](../reference/mustache-core.md#7-sections-and-truthiness):
|
|
224
|
+
a missing value, `null`, `false`, `0`, `""` and `[]` all count as missing. An optional number
|
|
225
|
+
that may be 0 needs a boolean of its own if 0 should show.
|
|
226
|
+
|
|
227
|
+
`If`, `Unless` and `Each` need a field from `data`; a condition known at compile time is plain
|
|
228
|
+
JavaScript ([`static-condition`](../reference/errors.md#static-condition)).
|
|
229
|
+
|
|
230
|
+
`Conditional` is for content one kind of output needs and another doesn't. `when` is `htmlOnly`
|
|
231
|
+
(the HTML part), `textOnly` (the plain-text part), `mso` (only classic Outlook on Windows) or
|
|
232
|
+
`notMso` (every other client). The components already use it; you rarely need it in a template.
|
|
233
|
+
|
|
234
|
+
## Sender values
|
|
235
|
+
|
|
236
|
+
`sender` holds facts about the sender that templates show: the product name, the postal
|
|
237
|
+
address, the help URL. They're set once, in the config:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
sender: {
|
|
241
|
+
productName: "Acme",
|
|
242
|
+
legalName: "Acme Ltd",
|
|
243
|
+
postalAddress: "1 High Street, London",
|
|
244
|
+
helpUrl: "https://help.acme.example",
|
|
245
|
+
privacyUrl: "https://acme.example/privacy",
|
|
246
|
+
siteUrl: { runtime: true },
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The keys are `productName`, `name`, `legalName`, `postalAddress`, `privacyUrl`, `helpUrl`,
|
|
251
|
+
`supportEmail` and `siteUrl`. A template that reads a key the config doesn't set fails the compile
|
|
252
|
+
([`sender-value-missing`](../reference/errors.md#sender-value-missing)).
|
|
253
|
+
|
|
254
|
+
There are two kinds:
|
|
255
|
+
|
|
256
|
+
- **A string is a compile-time constant.** It's written into the output as text, like the copy.
|
|
257
|
+
- **`{ runtime: true }` means your backend passes it at send time.** It renders as a placeholder,
|
|
258
|
+
and the generated module exports `createEmails({ siteUrl })` instead of a ready `emails` object.
|
|
259
|
+
Use it for values that differ between environments, such as the site URL on staging and
|
|
260
|
+
production. See [createEmails](sending.md#runtime-sender-values).
|
|
261
|
+
|
|
262
|
+
Data passed to `render()` can't override a sender value.
|
|
263
|
+
|
|
264
|
+
## Your own components
|
|
265
|
+
|
|
266
|
+
A component is a function that returns JSX. Put it in a folder whose name starts with `_`, such as
|
|
267
|
+
`_shared/`, and import it with a relative path (`../_shared/Card`). Start the file with the same `@jsxImportSource` comment
|
|
268
|
+
when your templates need it. See
|
|
269
|
+
[Components](components.md#your-own-components).
|