patramail 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PatraMail contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ # PatraMail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ PatraMail generates responsive HTML and plain text for transactional emails from
4
+ one JavaScript object. It runs on Node.js 18+ using CommonJS and zero runtime
5
+ dependencies. Pass the output to your existing email transport.
6
+
7
+ ```sh
8
+ npm install patramail
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```js
14
+ const PatraMail = require('patramail');
15
+
16
+ const mailGenerator = new PatraMail({
17
+ theme: 'default',
18
+ product: {
19
+ name: 'Acme',
20
+ link: 'https://acme.test',
21
+ },
22
+ });
23
+
24
+ const email = {
25
+ body: {
26
+ name: 'Jane',
27
+ intro: 'Welcome to Acme! Your account is ready.',
28
+ action: {
29
+ instructions: 'Confirm your email address to get started.',
30
+ button: {
31
+ color: '#1746a2',
32
+ text: 'Confirm your account',
33
+ link: 'https://acme.test/confirm?token=example',
34
+ },
35
+ },
36
+ outro: 'If you have questions, reply to this email.',
37
+ },
38
+ };
39
+
40
+ const emailBody = mailGenerator.generate(email);
41
+ const emailText = mailGenerator.generatePlaintext(email);
42
+
43
+ require('node:fs').writeFileSync('preview.html', emailBody, 'utf8');
44
+ ```
45
+
46
+ Open `preview.html` in a browser, or pass `emailBody` and `emailText` to your
47
+ email transport.
48
+
49
+ ![Password-reset email preview showing the heading, reset button, and footer](docs/password-reset.png)
50
+
51
+ ## Build a custom email
52
+
53
+ Pass your own `body` to `generate()`. You can set the heading, write
54
+ multiple paragraphs, add one or more buttons, and include footer links.
55
+ Use a theme object to set your brand color and other styling.
56
+
57
+ ```js
58
+ const PatraMail = require('patramail');
59
+ const mailer = new PatraMail({
60
+ theme: { brand: '#30564b', radius: '8px' },
61
+ product: { name: 'Acme', link: 'https://acme.test' },
62
+ });
63
+
64
+ const email = {
65
+ subject: 'Your monthly statement is ready',
66
+ preheader: 'Review your statement and billing settings.',
67
+ body: {
68
+ title: 'Your statement is ready',
69
+ intro: [
70
+ 'Your monthly statement is available.',
71
+ 'You can view or download it in your account.',
72
+ ],
73
+ action: [
74
+ {
75
+ button: {
76
+ text: 'View statement',
77
+ link: 'https://acme.test/billing/statement',
78
+ },
79
+ },
80
+ { button: { text: 'Manage billing', link: 'https://acme.test/billing' } },
81
+ ],
82
+ outro: 'Reply to this email if you have questions.',
83
+ },
84
+ footer: {
85
+ links: [{ text: 'Contact support', link: 'mailto:help@acme.test' }],
86
+ },
87
+ };
88
+
89
+ const html = mailer.generate(email);
90
+ const text = mailer.generatePlaintext(email);
91
+ ```
92
+
93
+ See the [Mailgen-style API](docs/api.md#mailgen-style-usage),
94
+ [input schema](docs/input-schema.md), and [theme options](docs/themes.md).
95
+
96
+ ## Account and event templates
97
+
98
+ Use `templates.passwordReset`, `templates.emailVerification`, or
99
+ `templates.dashboardWelcome` for common account emails. Each accepts the
100
+ action URL from your application and generates matching HTML and text.
101
+ See the [account template example](docs/api.md#account-templates).
102
+
103
+ Choose from invitation, registration confirmation, reminder, event update,
104
+ cancellation, and follow-up templates. Each supplies event copy, a color
105
+ palette, and an optional action button. See the
106
+ [event template guide](docs/events.md) for a complete example.
107
+
108
+ Use `const { PatraMail } = require('patramail')` when you want the
109
+ combined `{ html, text, subject, preheader }` result in one call.
110
+ See the [API reference](docs/api.md).
111
+
112
+ ## Send with Nodemailer
113
+
114
+ Install Nodemailer in your application with `npm install nodemailer`. Copy the
115
+ quick start into an async function, then use the generated HTML and text with your SMTP settings.
116
+
117
+ ```js
118
+ const nodemailer = require('nodemailer');
119
+ const transport = nodemailer.createTransport(process.env.SMTP_URL);
120
+ await transport.sendMail({
121
+ from: process.env.MAIL_FROM,
122
+ to: process.env.MAIL_TO,
123
+ subject: 'Confirm your Acme account',
124
+ html: emailBody,
125
+ text: emailText,
126
+ });
127
+ ```
128
+
129
+ Set `SMTP_URL` to your provider's SMTP URL and set `MAIL_FROM` and `MAIL_TO`
130
+ to your sender and recipient addresses.
131
+
132
+ ## Examples and reference
133
+
134
+ - [Mailgen-style quick start](examples/mailgen-style/index.js) writes a local HTML preview and prints the plain-text version.
135
+ - [Password reset](examples/password-reset.js) and [receipt](examples/receipt.js) print HTML when run with Node.
136
+ - [Nodemailer example](examples/with-nodemailer.js) emits a complete MIME message to stdout with Nodemailer installed. Set `SMTP_URL`, `MAIL_FROM`, and `MAIL_TO` to send it using your SMTP provider.
137
+ - `npm run preview` in this repository generates the example HTML files under `preview/`.
138
+ - [API reference](docs/api.md), [input schema](docs/input-schema.md), and [themes](docs/themes.md).
139
+
140
+ ## Email-client compatibility
141
+
142
+ Chrome previews verified desktop light and dark layouts and a 375px receipt
143
+ with a horizontally scrolling table. The browser preview is useful for layout
144
+ checks. Inbox verification is still pending for Gmail, Outlook desktop and web,
145
+ Apple Mail, and a mobile email client.
146
+
147
+ - Classic Outlook may display square corners and use the inline fallback colors.
148
+ Dark-mode recoloring varies by client. [Can I email dark mode results](https://www.caniemail.com/features/css-at-media-prefers-color-scheme/)
149
+ - Some clients may ignore the receipt's scrolling wrapper or clip a wide table.
150
+ Keep transactional tables narrow when targeting those clients. [Can I email overflow results](https://www.caniemail.com/features/css-overflow/)
151
+
152
+ For a transport smoke test, [Ethereal](https://ethereal.email/) catches messages
153
+ in a free SMTP sandbox. For an inbox check, send to accounts you control or use
154
+ a service that renders the supported clients.
155
+
156
+ ## Development
157
+
158
+ Run `npm ci`, `npm test`, and `npm run lint`. When changing the generated
159
+ markup intentionally, run `UPDATE_SNAPSHOTS=1 npm test` and review the
160
+ resulting diffs in `test/snapshots/`.
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "patramail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Generate transactional email HTML and plain text from structured input",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "test": "node --test test/*.test.js",
8
+ "lint": "eslint .",
9
+ "format": "prettier --write .",
10
+ "preview": "node scripts/preview.js"
11
+ },
12
+ "license": "MIT",
13
+ "type": "commonjs",
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "files": [
18
+ "src"
19
+ ],
20
+ "devDependencies": {
21
+ "eslint": "8.57.1",
22
+ "prettier": "3.8.5"
23
+ }
24
+ }
@@ -0,0 +1,72 @@
1
+ 'use strict';
2
+
3
+ const { safeUrl } = require('./escape');
4
+ const { isRecord } = require('./validate');
5
+
6
+ const copy = {
7
+ passwordReset: {
8
+ title: 'Reset your password',
9
+ preheader: 'Use this link to choose a new password.',
10
+ intro:
11
+ 'We received a request to reset your password. Use the button below to choose a new one.',
12
+ buttonText: 'Reset password',
13
+ outro: 'If you didn’t request a password reset, you can ignore this email.',
14
+ },
15
+ emailVerification: {
16
+ title: 'Verify your email address',
17
+ preheader: 'Confirm this email address to finish setting up your account.',
18
+ intro: 'Please confirm that this email address belongs to you.',
19
+ buttonText: 'Verify email address',
20
+ outro: 'If you didn’t create an account, you can ignore this email.',
21
+ },
22
+ dashboardWelcome: {
23
+ title: 'Your account is ready',
24
+ preheader: 'Open your dashboard to get started.',
25
+ intro:
26
+ 'Welcome aboard. Your dashboard is where you can get started and manage your account.',
27
+ buttonText: 'Go to dashboard',
28
+ },
29
+ };
30
+
31
+ function accountTemplate(preset, options) {
32
+ if (!isRecord(options))
33
+ throw new TypeError('account template options must be an object');
34
+ const {
35
+ link,
36
+ recipient,
37
+ subject = preset.title,
38
+ preheader = preset.preheader,
39
+ intro = preset.intro,
40
+ outro = preset.outro,
41
+ buttonText = preset.buttonText,
42
+ } = options;
43
+ if (!safeUrl(link, true)) {
44
+ throw new TypeError(
45
+ 'account template link must be an absolute HTTP(S) URL',
46
+ );
47
+ }
48
+ if (recipient !== undefined && typeof recipient !== 'string') {
49
+ throw new TypeError('account template recipient must be a string');
50
+ }
51
+
52
+ const paragraphs = recipient
53
+ ? [`Hi ${recipient},`, ...[intro].flat()]
54
+ : intro;
55
+ return {
56
+ subject,
57
+ preheader,
58
+ body: {
59
+ greeting: preset.title,
60
+ intro: paragraphs,
61
+ actions: [{ button: { text: buttonText, link } }],
62
+ outro,
63
+ },
64
+ };
65
+ }
66
+
67
+ module.exports = Object.fromEntries(
68
+ Object.entries(copy).map(([name, preset]) => [
69
+ name,
70
+ (options) => accountTemplate(preset, options),
71
+ ]),
72
+ );
package/src/escape.js ADDED
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+
3
+ const entities = {
4
+ '&': '&',
5
+ '<': '&lt;',
6
+ '>': '&gt;',
7
+ '"': '&quot;',
8
+ "'": '&#39;',
9
+ };
10
+
11
+ function escape(value) {
12
+ return String(value ?? '').replace(
13
+ /[&<>"']/g,
14
+ (character) => entities[character],
15
+ );
16
+ }
17
+
18
+ function safeUrl(value, image = false) {
19
+ if (typeof value !== 'string' || /[\s\u0000-\u001f\u007f]/u.test(value)) {
20
+ return '';
21
+ }
22
+
23
+ const url = parseUrl(value);
24
+ if (!url) return '';
25
+ if (url.protocol === 'https:' || url.protocol === 'http:') {
26
+ return /^https?:\/\/[^/\\?#]+/i.test(value) &&
27
+ !value.includes('\\') &&
28
+ url.hostname
29
+ ? value
30
+ : '';
31
+ }
32
+ return !image &&
33
+ (url.protocol === 'mailto:' || url.protocol === 'tel:') &&
34
+ url.pathname
35
+ ? value
36
+ : '';
37
+ }
38
+
39
+ function parseUrl(value) {
40
+ try {
41
+ return new URL(value);
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ module.exports = { escape, safeUrl };
package/src/events.js ADDED
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ const styles = Object.freeze({
4
+ invitation: {
5
+ label: 'Invitation',
6
+ accent: '#52406e',
7
+ darkAccent: '#c9b8e7',
8
+ subject: (name) => `You're invited to ${name}`,
9
+ intro:
10
+ 'Join us for the event below. Please let us know if you can make it.',
11
+ button: 'RSVP',
12
+ },
13
+ confirmation: {
14
+ label: 'Confirmed',
15
+ accent: '#285747',
16
+ darkAccent: '#a6cbbb',
17
+ subject: (name) => `You're registered for ${name}`,
18
+ intro:
19
+ 'Your registration is confirmed. Keep these details handy for the day.',
20
+ button: 'View registration',
21
+ },
22
+ reminder: {
23
+ label: 'Reminder',
24
+ accent: '#69471e',
25
+ darkAccent: '#dec08e',
26
+ subject: (name) => `Coming up: ${name}`,
27
+ intro: 'A quick reminder to check the details before the event.',
28
+ button: 'View event details',
29
+ },
30
+ update: {
31
+ label: 'Event update',
32
+ accent: '#365677',
33
+ darkAccent: '#adc8e5',
34
+ subject: (name) => `Updated details for ${name}`,
35
+ intro:
36
+ 'The event details have changed. Please review the latest information below.',
37
+ button: 'View updated details',
38
+ },
39
+ cancellation: {
40
+ label: 'Canceled',
41
+ accent: '#813c47',
42
+ darkAccent: '#e4abb4',
43
+ subject: (name) => `${name} has been canceled`,
44
+ intro: 'This event has been canceled. Thank you for your understanding.',
45
+ button: 'Get more information',
46
+ },
47
+ followUp: {
48
+ label: 'After the event',
49
+ accent: '#285b62',
50
+ darkAccent: '#a6cdd0',
51
+ subject: (name) => `Thank you for joining ${name}`,
52
+ intro:
53
+ 'Thanks for spending time with us. We appreciate you being part of the event.',
54
+ button: 'View event resources',
55
+ },
56
+ });
57
+
58
+ function eventTemplate(kind, options) {
59
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
60
+ throw new TypeError('event options must be an object');
61
+ }
62
+ const {
63
+ name,
64
+ recipient,
65
+ date,
66
+ location,
67
+ link,
68
+ buttonText,
69
+ intro,
70
+ outro,
71
+ subject,
72
+ preheader,
73
+ footer,
74
+ } = options;
75
+ if (typeof name !== 'string' || !name.trim()) {
76
+ throw new TypeError('event name must be a non-empty string');
77
+ }
78
+ if (buttonText !== undefined && link === undefined) {
79
+ throw new TypeError('event buttonText requires a link');
80
+ }
81
+ const preset = styles[kind];
82
+ return {
83
+ subject: subject === undefined ? preset.subject(name) : subject,
84
+ preheader: preheader === undefined ? preset.intro : preheader,
85
+ body: {
86
+ name: recipient,
87
+ intro: intro === undefined ? preset.intro : intro,
88
+ event: { kind, title: name, date, location },
89
+ actions:
90
+ link === undefined
91
+ ? undefined
92
+ : [
93
+ {
94
+ button: {
95
+ text: buttonText === undefined ? preset.button : buttonText,
96
+ link,
97
+ },
98
+ },
99
+ ],
100
+ outro,
101
+ },
102
+ footer,
103
+ };
104
+ }
105
+
106
+ const templates = Object.freeze(
107
+ Object.fromEntries(
108
+ Object.keys(styles).map((kind) => [
109
+ kind,
110
+ (options) => eventTemplate(kind, options),
111
+ ]),
112
+ ),
113
+ );
114
+
115
+ function eventTheme(theme, kind, mode) {
116
+ if (mode === 'custom') {
117
+ return { ...theme, eventSurface: theme.card, eventRule: '#8b8277' };
118
+ }
119
+
120
+ const { accent, darkAccent } = styles[kind];
121
+ const dark = mode === 'dark';
122
+ return {
123
+ ...theme,
124
+ bg: dark ? '#171819' : '#eeeae4',
125
+ card: dark ? '#222325' : '#fffefa',
126
+ heading: dark ? '#f5f2ed' : '#211e1b',
127
+ text: dark ? '#dedad4' : '#403b35',
128
+ brand: dark ? darkAccent : accent,
129
+ radius: '8px',
130
+ eventSurface: dark ? '#292a2c' : '#f7f3ec',
131
+ eventRule: dark ? '#55514e' : '#d8cfc3',
132
+ };
133
+ }
134
+
135
+ module.exports = { styles, templates, eventTheme };
package/src/i18n/en.js ADDED
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.freeze({
4
+ greeting: 'Hi',
5
+ title: 'Email',
6
+ table: 'Details',
7
+ });
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ const en = require('./en');
4
+ const locales = new Map([['en', en]]);
5
+
6
+ function label(lang, key) {
7
+ return (
8
+ locales.get(lang)?.[key] ??
9
+ locales.get(lang.split('-')[0])?.[key] ??
10
+ en[key]
11
+ );
12
+ }
13
+
14
+ module.exports = label;
package/src/index.js ADDED
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ const render = require('./render');
4
+ const { templates: eventTemplates } = require('./events');
5
+ const accountTemplates = require('./account-templates');
6
+ const text = require('./text');
7
+ const { escape } = require('./escape');
8
+ const { themes, resolveTheme } = require('./themes');
9
+ const { validate, isRecord } = require('./validate');
10
+
11
+ class PatraMail {
12
+ constructor(options = {}) {
13
+ if (!isRecord(options)) throw new TypeError('options must be an object');
14
+ if (options.product !== undefined && !isRecord(options.product)) {
15
+ throw new TypeError('options.product must be an object');
16
+ }
17
+ if (options.lang !== undefined && typeof options.lang !== 'string') {
18
+ throw new TypeError('options.lang must be a language tag');
19
+ }
20
+ this.lang = Intl.getCanonicalLocales(options.lang ?? 'en')[0];
21
+ this.product = Object.freeze({ ...options.product });
22
+ this.theme = resolveTheme(options.theme);
23
+ }
24
+
25
+ validate(email) {
26
+ return validate(email, this.product);
27
+ }
28
+
29
+ #prepare(email) {
30
+ const result = this.validate(email);
31
+ if (!result.valid) throw new TypeError(result.errors.join('\n'));
32
+ if (result.warnings.length) {
33
+ process.emitWarning(result.warnings.join('\n'), {
34
+ code: 'PATRAMAIL_INPUT',
35
+ });
36
+ }
37
+ return { ...email, product: { ...this.product, ...email.product } };
38
+ }
39
+
40
+ generate(email) {
41
+ const input = this.#prepare(email);
42
+ return {
43
+ html: render(input, this.theme, this.lang),
44
+ text: text(input, this.lang),
45
+ subject: input.subject,
46
+ preheader: input.preheader,
47
+ };
48
+ }
49
+
50
+ generateHtml(email) {
51
+ return render(this.#prepare(email), this.theme, this.lang);
52
+ }
53
+
54
+ generatePlainText(email) {
55
+ return text(this.#prepare(email), this.lang);
56
+ }
57
+ }
58
+
59
+ const Mailgen = require('./mailgen')(PatraMail);
60
+
61
+ module.exports = Mailgen;
62
+ module.exports.PatraMail = PatraMail;
63
+ module.exports.escape = escape;
64
+ module.exports.themes = themes;
65
+ module.exports.templates = Object.freeze({
66
+ ...eventTemplates,
67
+ ...accountTemplates,
68
+ });
69
+ module.exports.Mailgen = Mailgen;
package/src/mailgen.js ADDED
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ const { isRecord } = require('./validate');
4
+
5
+ function toPatraMail(email) {
6
+ if (!isRecord(email) || !isRecord(email.body)) return email;
7
+ const { action, actions, title, greeting, name, signature, ...rest } =
8
+ email.body;
9
+ const hideGreeting = greeting === false;
10
+ const normalizedActions =
11
+ action === undefined || Array.isArray(action) ? action : [action];
12
+ return {
13
+ ...email,
14
+ body: {
15
+ ...rest,
16
+ greeting: hideGreeting ? undefined : (title ?? greeting),
17
+ name: hideGreeting || title !== undefined ? undefined : name,
18
+ signature: signature === false ? undefined : signature,
19
+ actions: actions === undefined ? normalizedActions : actions,
20
+ },
21
+ };
22
+ }
23
+
24
+ module.exports = (PatraMail) =>
25
+ class Mailgen {
26
+ #mailer;
27
+
28
+ constructor(options) {
29
+ this.#mailer = new PatraMail(options);
30
+ }
31
+
32
+ generate(email) {
33
+ return this.generateHtml(email);
34
+ }
35
+
36
+ generatePlaintext(email) {
37
+ return this.generatePlainText(email);
38
+ }
39
+
40
+ generateHtml(email) {
41
+ return this.#mailer.generateHtml(toPatraMail(email));
42
+ }
43
+
44
+ generatePlainText(email) {
45
+ return this.#mailer.generatePlainText(toPatraMail(email));
46
+ }
47
+
48
+ validate(email) {
49
+ return this.#mailer.validate(toPatraMail(email));
50
+ }
51
+ };
package/src/render.js ADDED
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ const { escape } = require('./escape');
4
+ const header = require('./sections/header');
5
+ const event = require('./sections/event');
6
+ const { eventTheme } = require('./events');
7
+ const body = require('./sections/body');
8
+ const footer = require('./sections/footer');
9
+ const label = require('./i18n');
10
+
11
+ const { themes, buttonText } = require('./themes');
12
+
13
+ module.exports = function render(email, selectedTheme, lang) {
14
+ const automaticDark = selectedTheme === themes.default;
15
+ const explicitDark = selectedTheme === themes.dark;
16
+ const eventData = email.body?.event;
17
+ const mode = automaticDark ? 'light' : explicitDark ? 'dark' : 'custom';
18
+ const theme = eventData
19
+ ? eventTheme(selectedTheme, eventData.kind, mode)
20
+ : selectedTheme;
21
+ const dark = eventData
22
+ ? eventTheme(themes.dark, eventData.kind, 'dark')
23
+ : themes.dark;
24
+ const scheme = automaticDark ? 'light dark' : explicitDark ? 'dark' : 'light';
25
+ const eventMobile = eventData
26
+ ? `
27
+ .pm-event-inset { padding-left: 22px !important; padding-right: 22px !important; }
28
+ .pm-event-hero { padding-top: 22px !important; padding-bottom: 22px !important; }
29
+ .pm-event-title { font-size: 36px !important; }
30
+ .pm-event-detail { display: block !important; width: 100% !important; padding: 0 0 8px !important; }`
31
+ : '';
32
+ const eventDark = eventData
33
+ ? `
34
+ .pm-event-hero { background-color: ${dark.eventSurface} !important; border-color: ${dark.eventRule} !important; color: ${dark.text} !important; }
35
+ .pm-event-details, .pm-event-footer { border-color: ${dark.eventRule} !important; }`
36
+ : '';
37
+ const darkStyles = automaticDark
38
+ ? `
39
+ @media (prefers-color-scheme: dark) {
40
+ .pm-bg { background-color: ${dark.bg} !important; }
41
+ .pm-card { background-color: ${dark.card} !important; color: ${dark.text} !important; }
42
+ .pm-heading { color: ${dark.heading} !important; }
43
+ .pm-brand { color: ${dark.brand} !important; }
44
+ .pm-button { background-color: ${dark.brand} !important; }
45
+ .pm-button-link { color: ${buttonText(dark.brand)} !important; }${eventDark}
46
+ }`
47
+ : '';
48
+ const preheader = email.preheader
49
+ ? `<div aria-hidden="true" style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all;">${escape(email.preheader)}</div>`
50
+ : '';
51
+ const product = email.product ?? {};
52
+ const rows =
53
+ header(product, theme, Boolean(eventData)) +
54
+ event(eventData, theme) +
55
+ body(
56
+ email.body ?? {},
57
+ { ...theme, buttonText: buttonText(theme.brand) },
58
+ lang,
59
+ ) +
60
+ footer(email.footer ?? {}, product, theme, Boolean(eventData));
61
+ const card = rows
62
+ ? `<!--[if mso]><table role="presentation" width="600" align="center" cellspacing="0" cellpadding="0" border="0"><tr><td><![endif]-->
63
+ <table role="presentation" class="pm-card" align="center" width="600" cellspacing="0" cellpadding="0" border="0" bgcolor="${theme.card}" style="width:100%;max-width:600px;table-layout:fixed;background-color:${theme.card};color:${theme.text};border-radius:${theme.radius};font-family:${theme.font};font-size:16px;line-height:1.5;">
64
+ ${rows}
65
+ </table>
66
+ <!--[if mso]></td></tr></table><![endif]-->`
67
+ : '';
68
+
69
+ return `<!doctype html>
70
+ <html lang="${escape(lang)}">
71
+ <head>
72
+ <meta charset="utf-8">
73
+ <meta name="viewport" content="width=device-width, initial-scale=1">
74
+ <meta name="color-scheme" content="${scheme}">
75
+ <meta name="supported-color-schemes" content="${scheme}">
76
+ <title>${escape(email.subject ?? (product.name || label(lang, 'title')))}</title>
77
+ <style>
78
+ @media only screen and (max-width: 620px) {
79
+ .pm-card { width: 100% !important; }
80
+ .pm-outer { padding: 12px !important; }
81
+ .pm-table-scroll { overflow-x: auto !important; }
82
+ .pm-data-table { min-width: 400px !important; }${eventMobile}
83
+ }${darkStyles}
84
+ </style>
85
+ </head>
86
+ <body class="pm-bg" style="margin:0;padding:0;background-color:${theme.bg};">
87
+ ${preheader}
88
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="${theme.bg}" class="pm-bg" style="background-color:${theme.bg};">
89
+ <tr><td align="center" class="pm-outer" style="padding:24px;">
90
+ ${card}
91
+ </td></tr>
92
+ </table>
93
+ </body>
94
+ </html>
95
+ `;
96
+ };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ const { escape, safeUrl } = require('../escape');
4
+ const { buttonText } = require('../themes');
5
+
6
+ module.exports = function actions(items, theme) {
7
+ return items
8
+ .map(({ instructions, button }) => {
9
+ const link = safeUrl(button?.link);
10
+ const instruction = instructions
11
+ ? `<p style="margin:0 0 12px;">${escape(instructions)}</p>`
12
+ : '';
13
+ const background = button?.color ?? theme.brand;
14
+ const foreground = button?.color
15
+ ? buttonText(background)
16
+ : theme.buttonText;
17
+ const cellClass = button?.color ? '' : ' class="pm-button"';
18
+ const linkClass = button?.color ? '' : ' class="pm-button-link"';
19
+ const control =
20
+ link && button.text
21
+ ? `<table role="presentation" cellspacing="0" cellpadding="0" border="0" style="margin:0 0 16px;"><tr><td${cellClass} bgcolor="${background}" style="background-color:${background};border-radius:${theme.radius};mso-padding-alt:12px 22px;"><a${linkClass} href="${escape(link)}" style="display:inline-block;padding:12px 22px;color:${foreground};font-weight:bold;text-decoration:underline;mso-padding-alt:0;">${escape(button.text)}</a></td></tr></table>`
22
+ : '';
23
+
24
+ return instruction + control;
25
+ })
26
+ .join('');
27
+ };
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ const { escape } = require('../escape');
4
+ const actions = require('./actions');
5
+ const { table } = require('./table');
6
+ const label = require('../i18n');
7
+
8
+ const paragraph = (value) =>
9
+ value ? `<p style="margin:0 0 16px;">${escape(value)}</p>` : '';
10
+
11
+ module.exports = function body(data, theme, lang) {
12
+ const salutation = [
13
+ data.greeting ?? (data.name ? label(lang, 'greeting') : ''),
14
+ data.name,
15
+ ]
16
+ .filter(Boolean)
17
+ .join(' ');
18
+ const greeting = salutation
19
+ ? data.event
20
+ ? `<p class="pm-heading" style="margin:0 0 8px;color:${theme.heading};font-weight:bold;">${escape(salutation)}</p>`
21
+ : `<h1 class="pm-heading" style="margin:0 0 16px;color:${theme.heading};font-size:24px;line-height:1.3;">${escape(salutation)}</h1>`
22
+ : '';
23
+ const intro = [data.intro ?? []].flat().map(paragraph).join('');
24
+ const content =
25
+ greeting +
26
+ intro +
27
+ actions(data.actions ?? [], theme) +
28
+ table(data.table, theme, label(lang, 'table')) +
29
+ (data.unsafeHtml ?? '') +
30
+ [data.outro ?? []].flat().map(paragraph).join('') +
31
+ paragraph(data.signature);
32
+
33
+ const cell = data.event
34
+ ? 'class="pm-event-inset" style="padding:24px 32px 24px;overflow-wrap:anywhere;"'
35
+ : 'style="padding:24px 24px 8px;"';
36
+ return content ? `<tr><td ${cell}>${content}</td></tr>` : '';
37
+ };
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ const { escape } = require('../escape');
4
+ const { styles } = require('../events');
5
+
6
+ module.exports = function event(data, theme) {
7
+ if (!data) return '';
8
+
9
+ const { label } = styles[data.kind];
10
+ const entries = [
11
+ ['When', data.date],
12
+ ['Where', data.location],
13
+ ].filter(([, value]) => value);
14
+ const detail = ([label, value]) =>
15
+ `<td class="pm-event-detail" valign="top" width="${entries.length === 2 ? '50%' : '100%'}" style="padding:0 16px 0 0;overflow-wrap:anywhere;font-size:15px;line-height:1.5;">
16
+ <strong class="pm-heading" style="color:${theme.heading};">${label}</strong><br>${escape(value)}
17
+ </td>`;
18
+ const details = entries.length
19
+ ? `<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-top:20px;table-layout:fixed;">
20
+ <tr><td class="pm-event-details" style="padding-top:16px;border-top:1px solid ${theme.eventRule};">
21
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="table-layout:fixed;"><tr>${entries.map(detail).join('')}</tr></table>
22
+ </td></tr>
23
+ </table>`
24
+ : '';
25
+
26
+ return `<tr><td class="pm-event-hero pm-event-inset" bgcolor="${theme.eventSurface}" style="padding:28px 32px;border-top:1px solid ${theme.eventRule};border-bottom:1px solid ${theme.eventRule};background-color:${theme.eventSurface};color:${theme.text};overflow-wrap:anywhere;">
27
+ <p class="pm-brand" style="margin:0 0 10px;color:${theme.brand};font-size:12px;font-weight:bold;letter-spacing:1.2px;text-transform:uppercase;">${label}</p>
28
+ <h1 class="pm-event-title pm-heading" style="margin:0;color:${theme.heading};font-family:Georgia, Times New Roman, serif;font-size:44px;font-weight:normal;line-height:1.12;">${escape(data.title)}</h1>
29
+ ${details}
30
+ </td></tr>`;
31
+ };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const { escape, safeUrl } = require('../escape');
4
+
5
+ module.exports = function footer(data, product, theme, isEvent) {
6
+ const links = (data.links ?? []).flatMap(({ text, link }) => {
7
+ const url = safeUrl(link);
8
+ return text && url
9
+ ? [
10
+ `<a class="pm-brand" href="${escape(url)}" style="color:${theme.brand};text-decoration:underline;">${escape(text)}</a>`,
11
+ ]
12
+ : [];
13
+ });
14
+
15
+ const content = [
16
+ escape(data.text),
17
+ links.join(' &middot; '),
18
+ escape(data.address),
19
+ escape(product.copyright),
20
+ ]
21
+ .filter(Boolean)
22
+ .map((value) => `<p style="margin:0 0 8px;">${value}</p>`)
23
+ .join('');
24
+
25
+ const cell = isEvent
26
+ ? `class="pm-event-footer pm-event-inset" style="padding:16px 32px;border-top:1px solid ${theme.eventRule};font-size:13px;"`
27
+ : 'align="center" style="padding:16px 24px;font-size:13px;"';
28
+ return content ? `<tr><td ${cell}>${content}</td></tr>` : '';
29
+ };
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const { escape, safeUrl } = require('../escape');
4
+
5
+ module.exports = function header(product, theme, isEvent) {
6
+ const logo = safeUrl(product.logo, true);
7
+ const link = safeUrl(product.link);
8
+ const name = escape(product.name);
9
+ if (!logo && !name) return '';
10
+
11
+ const content = logo
12
+ ? `<img src="${escape(logo)}" alt="${name}" width="160" height="48" style="border:0;display:inline-block;width:160px;height:48px;object-fit:contain;">`
13
+ : name;
14
+ const color = isEvent ? theme.heading : theme.brand;
15
+ const colorClass = isEvent ? 'pm-heading' : 'pm-brand';
16
+ const brand = link
17
+ ? `<a class="${colorClass}" href="${escape(link)}" style="color:${color};text-decoration:underline;">${content}</a>`
18
+ : content;
19
+
20
+ if (isEvent) {
21
+ return `<tr><td class="pm-heading pm-event-inset" style="padding:16px 32px;color:${color};font-size:15px;font-weight:bold;overflow-wrap:anywhere;">${brand}</td></tr>`;
22
+ }
23
+
24
+ return `<tr><td class="pm-brand" align="center" style="padding:24px 24px 0;color:${theme.brand};font-size:24px;font-weight:bold;">${brand}</td></tr>`;
25
+ };
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ const { escape } = require('../escape');
4
+
5
+ const validWidth = (value) =>
6
+ typeof value === 'string' &&
7
+ /^(?:[1-9]\d?|100)%$|^[1-9]\d{0,2}px$/.test(value);
8
+
9
+ function columnNames(rows) {
10
+ return [...new Set(rows.flatMap(Object.keys))];
11
+ }
12
+
13
+ function table(data, theme, label) {
14
+ if (!data?.data?.length) return '';
15
+ const columns = columnNames(data.data);
16
+ if (!columns.length) return '';
17
+
18
+ const cellStyle =
19
+ 'padding:8px;border-bottom:1px solid currentColor;overflow-wrap:anywhere;';
20
+ const headers = columns.map((key) => {
21
+ const width = data.columns?.customWidth?.[key];
22
+ const size = validWidth(width) ? `width:${width};` : '';
23
+ return `<th scope="col" class="pm-heading" style="text-align:left;box-sizing:border-box;${cellStyle}${size}color:${theme.heading};">${escape(key)}</th>`;
24
+ });
25
+ const row = (values, total = false) =>
26
+ `<tr>${columns
27
+ .map((key, index) => {
28
+ const tag = total && index === 0 ? 'th' : 'td';
29
+ const scope = tag === 'th' ? ' scope="row"' : '';
30
+ const value = Object.hasOwn(values, key) ? values[key] : '';
31
+ const emphasis = total ? 'font-weight:bold;text-align:left;' : '';
32
+ return `<${tag}${scope} style="${cellStyle}${emphasis}">${escape(value)}</${tag}>`;
33
+ })
34
+ .join('')}</tr>`;
35
+
36
+ return `<div class="pm-table-scroll" role="region" aria-label="${escape(label)}" tabindex="0" style="max-width:100%;overflow-x:auto;margin:0 0 16px;"><table class="pm-data-table" width="100%" cellspacing="0" cellpadding="0" border="0" style="width:100%;table-layout:fixed;border-collapse:collapse;"><thead><tr>${headers.join('')}</tr></thead><tbody>${data.data.map((values) => row(values)).join('')}</tbody>${data.total ? `<tfoot>${row(data.total, true)}</tfoot>` : ''}</table></div>`;
37
+ }
38
+
39
+ module.exports = { table, columnNames, validWidth };
package/src/text.js ADDED
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ const { columnNames } = require('./sections/table');
4
+ const label = require('./i18n');
5
+ const { styles } = require('./events');
6
+
7
+ function tableLines(table) {
8
+ if (!table?.data?.length) return [];
9
+ const columns = columnNames(table.data);
10
+ const formatRow = (row) =>
11
+ columns
12
+ .filter((key) => Object.hasOwn(row, key))
13
+ .map((key) => `${key}: ${row[key]}`)
14
+ .join(' | ');
15
+
16
+ return [...table.data, ...(table.total ? [table.total] : [])]
17
+ .map(formatRow)
18
+ .filter(Boolean);
19
+ }
20
+
21
+ module.exports = function text(email, lang) {
22
+ const { product = {}, body = {}, footer = {} } = email;
23
+ const brand = [product.name, product.link].filter(Boolean).join(' — ');
24
+ const greeting = [
25
+ body.greeting ?? (body.name ? label(lang, 'greeting') : ''),
26
+ body.name,
27
+ ]
28
+ .filter(Boolean)
29
+ .join(' ');
30
+ const actions = (body.actions ?? []).map(({ instructions, button }) => {
31
+ const label = instructions || button?.text;
32
+ return button?.link
33
+ ? [label, button.link].filter(Boolean).join(': ')
34
+ : label;
35
+ });
36
+ const event = body.event;
37
+ const details = event
38
+ ? [
39
+ `${styles[event.kind].label}: ${event.title}`,
40
+ event.date && `When: ${event.date}`,
41
+ event.location && `Where: ${event.location}`,
42
+ ]
43
+ .filter(Boolean)
44
+ .join('\n')
45
+ : '';
46
+ const links = (footer.links ?? []).map(
47
+ ({ text, link }) => `${text}: ${link}`,
48
+ );
49
+
50
+ return [
51
+ brand,
52
+ greeting,
53
+ ...[body.intro ?? []].flat(),
54
+ details,
55
+ ...actions,
56
+ tableLines(body.table).join('\n'),
57
+ ...[body.outro ?? []].flat(),
58
+ body.signature,
59
+ footer.text,
60
+ links.join('\n'),
61
+ footer.address,
62
+ product.copyright,
63
+ ]
64
+ .filter(Boolean)
65
+ .join('\n\n');
66
+ };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.freeze({
4
+ ...require('./default'),
5
+ bg: '#111827',
6
+ card: '#1f2937',
7
+ text: '#f3f4f6',
8
+ heading: '#ffffff',
9
+ brand: '#9ec5ff',
10
+ });
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.freeze({
4
+ bg: '#f3f4f6',
5
+ card: '#ffffff',
6
+ text: '#212936',
7
+ heading: '#111827',
8
+ brand: '#1746a2',
9
+ font: 'Arial, Helvetica, sans-serif',
10
+ radius: '6px',
11
+ });
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ const themes = Object.freeze({
4
+ default: require('./default'),
5
+ dark: require('./dark'),
6
+ });
7
+
8
+ const validColor = (value) =>
9
+ typeof value === 'string' && /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value);
10
+
11
+ function resolveTheme(selection = 'default') {
12
+ if (typeof selection === 'string' && Object.hasOwn(themes, selection)) {
13
+ return themes[selection];
14
+ }
15
+ if (!selection || typeof selection !== 'object' || Array.isArray(selection)) {
16
+ throw new TypeError('theme must be "default", "dark", or a theme object');
17
+ }
18
+
19
+ const theme = { ...themes.default };
20
+ for (const key of Object.keys(theme)) {
21
+ if (Object.hasOwn(selection, key)) theme[key] = selection[key];
22
+ }
23
+
24
+ for (const key of ['bg', 'card', 'text', 'heading', 'brand']) {
25
+ if (!validColor(theme[key])) {
26
+ throw new TypeError(
27
+ `theme.${key} must be a three- or six-digit hex color`,
28
+ );
29
+ }
30
+ }
31
+ if (
32
+ typeof theme.font !== 'string' ||
33
+ !/^[a-z][a-z0-9-]*(?: [a-z0-9-]+)*(?: *, *[a-z][a-z0-9-]*(?: [a-z0-9-]+)*)*$/i.test(
34
+ theme.font,
35
+ )
36
+ ) {
37
+ throw new TypeError(
38
+ 'theme.font must be a comma-separated list of unquoted font names',
39
+ );
40
+ }
41
+ if (typeof theme.radius !== 'string' || !/^\d{1,3}px$/.test(theme.radius)) {
42
+ throw new TypeError(
43
+ 'theme.radius must be a pixel length from 0px to 999px',
44
+ );
45
+ }
46
+
47
+ return Object.freeze(theme);
48
+ }
49
+
50
+ function buttonText(brand) {
51
+ const hex = brand.slice(1);
52
+ const digits =
53
+ hex.length === 3 ? [...hex].map((digit) => digit.repeat(2)).join('') : hex;
54
+ const channels = digits.match(/../g).map((channel) => {
55
+ const value = parseInt(channel, 16) / 255;
56
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
57
+ });
58
+ const [red, green, blue] = channels;
59
+ const luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
60
+ return luminance > 0.1791287847 ? '#000000' : '#ffffff';
61
+ }
62
+
63
+ module.exports = { themes, resolveTheme, buttonText, validColor };
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ const { safeUrl } = require('./escape');
4
+ const { styles } = require('./events');
5
+ const { validColor } = require('./themes');
6
+ const { columnNames, validWidth } = require('./sections/table');
7
+
8
+ function isRecord(value) {
9
+ if (value === null || typeof value !== 'object') return false;
10
+ const prototype = Object.getPrototypeOf(value);
11
+ return prototype === Object.prototype || prototype === null;
12
+ }
13
+
14
+ function validate(email, defaults = {}) {
15
+ const errors = [];
16
+ const warnings = [];
17
+ const development = process.env.NODE_ENV !== 'production';
18
+
19
+ function object(value, path, keys) {
20
+ if (!isRecord(value)) {
21
+ errors.push(`${path} must be an object`);
22
+ return false;
23
+ }
24
+ if (development && keys) {
25
+ for (const key of Object.keys(value)) {
26
+ if (!keys.includes(key)) warnings.push(`Unknown field ${path}.${key}`);
27
+ }
28
+ }
29
+ return true;
30
+ }
31
+
32
+ function string(value, path, required = false) {
33
+ if (value === undefined && !required) return;
34
+ if (typeof value !== 'string' || (required && !value.trim())) {
35
+ errors.push(
36
+ `${path} must be ${required ? 'a non-empty string' : 'a string'}`,
37
+ );
38
+ }
39
+ }
40
+
41
+ function link(value, path, required = false, image = false) {
42
+ if (value === undefined && !required) return;
43
+ if (!safeUrl(value, image))
44
+ errors.push(
45
+ `${path} must be an absolute ${image ? 'HTTP(S)' : 'HTTP(S), mailto, or tel'} URL`,
46
+ );
47
+ }
48
+
49
+ function array(value, path, check) {
50
+ if (!Array.isArray(value)) {
51
+ errors.push(`${path} must be an array`);
52
+ return;
53
+ }
54
+ for (let index = 0; index < value.length; index += 1) {
55
+ check(value[index], `${path}[${index}]`);
56
+ }
57
+ }
58
+
59
+ function checkProduct(value, path) {
60
+ if (!object(value, path, ['name', 'link', 'logo', 'copyright'])) return;
61
+ string(value.name, `${path}.name`, Boolean(safeUrl(value.logo, true)));
62
+ string(value.copyright, `${path}.copyright`);
63
+ link(value.link, `${path}.link`);
64
+ link(value.logo, `${path}.logo`, false, true);
65
+ }
66
+
67
+ function checkLink(value, path, button = false) {
68
+ if (
69
+ !object(
70
+ value,
71
+ path,
72
+ button ? ['text', 'link', 'color'] : ['text', 'link'],
73
+ )
74
+ )
75
+ return;
76
+ if (button && value.color !== undefined && !validColor(value.color)) {
77
+ errors.push(`${path}.color must be a three- or six-digit hex color`);
78
+ }
79
+ string(value.text, `${path}.text`, true);
80
+ link(value.link, `${path}.link`, true);
81
+ }
82
+
83
+ function checkRow(value, path) {
84
+ if (!object(value, path)) return;
85
+ for (const [key, cell] of Object.entries(value)) {
86
+ if (typeof cell !== 'string' && !Number.isFinite(cell)) {
87
+ errors.push(`${path}.${key} must be a string or finite number`);
88
+ }
89
+ }
90
+ }
91
+
92
+ function checkTable(value, path) {
93
+ if (!object(value, path, ['data', 'columns', 'total'])) return;
94
+ array(value.data, `${path}.data`, checkRow);
95
+ const keys = columnNames(
96
+ Array.isArray(value.data) ? value.data.filter(isRecord) : [],
97
+ );
98
+ if (value.total !== undefined) {
99
+ checkRow(value.total, `${path}.total`);
100
+ if (!keys.length)
101
+ errors.push(
102
+ `${path}.total requires a data row with at least one column`,
103
+ );
104
+ if (development && isRecord(value.total)) {
105
+ for (const key of Object.keys(value.total)) {
106
+ if (!keys.includes(key))
107
+ warnings.push(`Unknown column ${path}.total.${key}`);
108
+ }
109
+ }
110
+ }
111
+ if (
112
+ value.columns !== undefined &&
113
+ object(value.columns, `${path}.columns`, ['customWidth']) &&
114
+ value.columns.customWidth !== undefined &&
115
+ object(value.columns.customWidth, `${path}.columns.customWidth`)
116
+ ) {
117
+ for (const [key, width] of Object.entries(value.columns.customWidth)) {
118
+ const field = `${path}.columns.customWidth.${key}`;
119
+ if (!validWidth(width))
120
+ errors.push(`${field} must be 1–100% or 1–999px`);
121
+ if (development && !keys.includes(key))
122
+ warnings.push(`Unknown column ${field}`);
123
+ }
124
+ }
125
+ }
126
+
127
+ function checkBody(value) {
128
+ if (
129
+ !object(value, 'email.body', [
130
+ 'greeting',
131
+ 'name',
132
+ 'intro',
133
+ 'event',
134
+ 'actions',
135
+ 'table',
136
+ 'unsafeHtml',
137
+ 'outro',
138
+ 'signature',
139
+ ])
140
+ )
141
+ return;
142
+ for (const key of ['greeting', 'name', 'signature', 'unsafeHtml']) {
143
+ string(value[key], `email.body.${key}`);
144
+ }
145
+ for (const field of ['intro', 'outro']) {
146
+ const path = `email.body.${field}`;
147
+ if (Array.isArray(value[field])) {
148
+ array(value[field], path, (line, itemPath) => {
149
+ if (typeof line !== 'string')
150
+ errors.push(`${itemPath} must be a string`);
151
+ });
152
+ } else {
153
+ string(value[field], path);
154
+ }
155
+ }
156
+ if (
157
+ value.event !== undefined &&
158
+ object(value.event, 'email.body.event', [
159
+ 'kind',
160
+ 'title',
161
+ 'date',
162
+ 'location',
163
+ ])
164
+ ) {
165
+ if (
166
+ typeof value.event.kind !== 'string' ||
167
+ !Object.hasOwn(styles, value.event.kind)
168
+ ) {
169
+ errors.push('email.body.event.kind must be a supported event template');
170
+ }
171
+ string(value.event.title, 'email.body.event.title', true);
172
+ string(value.event.date, 'email.body.event.date');
173
+ string(value.event.location, 'email.body.event.location');
174
+ }
175
+ if (value.actions !== undefined) {
176
+ array(value.actions, 'email.body.actions', (action, path) => {
177
+ if (!object(action, path, ['instructions', 'button'])) return;
178
+ string(action.instructions, `${path}.instructions`);
179
+ if (action.button !== undefined)
180
+ checkLink(action.button, `${path}.button`, true);
181
+ });
182
+ }
183
+ if (value.table !== undefined) checkTable(value.table, 'email.body.table');
184
+ }
185
+
186
+ if (
187
+ object(email, 'email', [
188
+ 'product',
189
+ 'subject',
190
+ 'preheader',
191
+ 'body',
192
+ 'footer',
193
+ ])
194
+ ) {
195
+ if (email.product === undefined || isRecord(email.product)) {
196
+ checkProduct({ ...defaults, ...email.product }, 'email.product');
197
+ } else {
198
+ object(email.product, 'email.product');
199
+ }
200
+ string(email.subject, 'email.subject');
201
+ if (typeof email.subject === 'string' && [...email.subject].length > 78) {
202
+ warnings.push('email.subject is longer than 78 characters');
203
+ }
204
+ string(email.preheader, 'email.preheader');
205
+ if (email.body !== undefined) checkBody(email.body);
206
+ if (
207
+ email.footer !== undefined &&
208
+ object(email.footer, 'email.footer', ['text', 'links', 'address'])
209
+ ) {
210
+ string(email.footer.text, 'email.footer.text');
211
+ string(email.footer.address, 'email.footer.address');
212
+ if (email.footer.links !== undefined)
213
+ array(email.footer.links, 'email.footer.links', checkLink);
214
+ }
215
+ }
216
+
217
+ return { valid: errors.length === 0, errors, warnings };
218
+ }
219
+
220
+ module.exports = { validate, isRecord };