@email-kit/runtime 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +53 -2
- package/dist/context.d.ts +5 -0
- package/dist/context.js +31 -0
- package/dist/errors-B2PPlpPP.js +34 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +175 -0
- package/dist/locale.d.ts +18 -0
- package/dist/locale.js +54 -0
- package/dist/plural.d.ts +14 -0
- package/dist/plural.js +59 -0
- package/dist/shared-DpUIeN9b.js +23 -0
- package/dist/types-Rd7be9eo.d.ts +154 -0
- package/dist/validate.d.ts +4 -0
- package/dist/validate.js +125 -0
- package/package.json +81 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 email-kit 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,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @email-kit/runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Renders the emails [email-kit](https://github.com/email-kit/email-kit) compiles. It's the only
|
|
4
|
+
email-kit package your app needs when it runs, so it's a **dependency**; the CLI, `core` and
|
|
5
|
+
`components` are devDependencies.
|
|
6
|
+
|
|
7
|
+
> **1.0.** Stable for transactional email. See [what 1.0
|
|
8
|
+
> covers](https://github.com/email-kit/email-kit#status).
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @email-kit/runtime
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`email-kit init` adds it for you. You don't import it yourself: the module `email-kit compile`
|
|
15
|
+
writes does, and your app imports that module.
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { emails } from "@/email-kit"
|
|
19
|
+
|
|
20
|
+
const { subject, html, text } = emails.welcome.render({ name: "Ada" }, { locale: "de" })
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Small on purpose
|
|
24
|
+
|
|
25
|
+
The compiler parses every template and writes it into the generated module in a compact form, so
|
|
26
|
+
nothing is parsed when an email is sent. What's left to do at send time is here, and the optional
|
|
27
|
+
parts have their own entry points, which the generated module imports only when your templates
|
|
28
|
+
use them:
|
|
29
|
+
|
|
30
|
+
| Entry point | Imported when | Min + gzip |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| `@email-kit/runtime` | always: filling the templates, keeping only the schema's fields | about 1.4 KB |
|
|
33
|
+
| `@email-kit/runtime/validate` | `validate` is on (the default) | about 1.1 KB |
|
|
34
|
+
| `@email-kit/runtime/plural` | a message has `{n, plural, …}` or `{x, select, …}` | about 0.5 KB |
|
|
35
|
+
| `@email-kit/runtime/locale` | the project compiles more than one locale | about 0.5 KB |
|
|
36
|
+
| `@email-kit/runtime/context` | the config has sender values passed at send time | about 0.5 KB |
|
|
37
|
+
|
|
38
|
+
Everything together is about 3 KB. A test keeps each entry point under its budget.
|
|
39
|
+
|
|
40
|
+
It has no dependencies, doesn't use `fs`, and uses only web-standard APIs, so it runs in Node 22+,
|
|
41
|
+
Bun, Deno, Cloudflare Workers, AWS Lambda and Next.js server code.
|
|
42
|
+
|
|
43
|
+
## Errors
|
|
44
|
+
|
|
45
|
+
Rendering problems throw an `EmailRenderError` with a `code`, which the generated module
|
|
46
|
+
re-exports. See the [error reference](https://github.com/email-kit/email-kit/blob/main/docs/reference/errors.md#at-send-time).
|
|
47
|
+
|
|
48
|
+
## Versions
|
|
49
|
+
|
|
50
|
+
Install the same version as `@email-kit/cli`. The generated module records the format it was
|
|
51
|
+
compiled for, and the runtime refuses one it doesn't render (`incompatible-module`) rather than
|
|
52
|
+
rendering it wrong. `email-kit check` fails when the runtime is missing or a devDependency.
|
|
53
|
+
|
|
54
|
+
MIT licensed.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the sender values passed to `createEmails()`. Each must be a non-empty string; URLs must be
|
|
3
|
+
* https, and `supportEmail` an email address.
|
|
4
|
+
*/
|
|
5
|
+
export declare function readContext(keys: readonly string[], context: unknown): Readonly<Record<string, string>>;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { t as EmailRenderError } from "./errors-B2PPlpPP.js";
|
|
2
|
+
import { a as isObject, n as describe, t as HTTPS_URL } from "./shared-DpUIeN9b.js";
|
|
3
|
+
// src/context.ts
|
|
4
|
+
/**
|
|
5
|
+
* `@email-kit/runtime/context`: checks the sender values passed to `createEmails()`. The generated
|
|
6
|
+
* module imports it when the config has sender values set with `{ runtime: true }`.
|
|
7
|
+
*
|
|
8
|
+
* @packageDocumentation
|
|
9
|
+
*/
|
|
10
|
+
const URL_CONTEXT_KEYS = [
|
|
11
|
+
"helpUrl",
|
|
12
|
+
"privacyUrl",
|
|
13
|
+
"siteUrl"
|
|
14
|
+
];
|
|
15
|
+
const EMAIL_ADDRESS = /^[^\s@<>"]+@[^\s@<>"]+$/;
|
|
16
|
+
/**
|
|
17
|
+
* Reads the sender values passed to `createEmails()`. Each must be a non-empty string; URLs must be
|
|
18
|
+
* https, and `supportEmail` an email address.
|
|
19
|
+
*/
|
|
20
|
+
function readContext(keys, context) {
|
|
21
|
+
const values = {};
|
|
22
|
+
for (const key of keys) {
|
|
23
|
+
const value = isObject(context) ? context[key] : void 0;
|
|
24
|
+
if (typeof value !== "string" || value === "") throw new EmailRenderError("missing-context", `createEmails() needs "${key}" as a non-empty string`);
|
|
25
|
+
if (URL_CONTEXT_KEYS.includes(key) && !HTTPS_URL.test(value)) throw new EmailRenderError("invalid-context", `createEmails() needs "${key}" as an https URL, got ${describe(value)}`);
|
|
26
|
+
if (key === "supportEmail" && !EMAIL_ADDRESS.test(value)) throw new EmailRenderError("invalid-context", `createEmails() needs "supportEmail" as an email address, got ${describe(value)}`);
|
|
27
|
+
values[key] = value;
|
|
28
|
+
}
|
|
29
|
+
return values;
|
|
30
|
+
}
|
|
31
|
+
export { readContext };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
/**
|
|
3
|
+
* Why an email couldn't be rendered. `code` says what kind of problem it is; for `invalid-data`,
|
|
4
|
+
* `issues` lists each field that doesn't match the schema, with its path.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* try {
|
|
9
|
+
* emails.welcome.render(data)
|
|
10
|
+
* } catch (error) {
|
|
11
|
+
* if (error instanceof EmailRenderError && error.code === "invalid-data") {
|
|
12
|
+
* console.error(error.issues) // [{ path: "name", message: "is required" }]
|
|
13
|
+
* }
|
|
14
|
+
* }
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
var EmailRenderError = class extends Error {
|
|
18
|
+
/** What kind of problem it is, such as `"invalid-data"`. */
|
|
19
|
+
code;
|
|
20
|
+
/** For `invalid-data`: each field that doesn't match the schema. Empty otherwise. */
|
|
21
|
+
issues;
|
|
22
|
+
/**
|
|
23
|
+
* @param code - What kind of problem it is.
|
|
24
|
+
* @param message - What went wrong, for people.
|
|
25
|
+
* @param issues - For `invalid-data`, each field that doesn't match the schema.
|
|
26
|
+
*/
|
|
27
|
+
constructor(code, message, issues = []) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "EmailRenderError";
|
|
30
|
+
this.code = code;
|
|
31
|
+
this.issues = issues;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
export { EmailRenderError as t };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { a as Model, c as RenderedEmail, d as TemplateSpec, f as Node, h as fill, i as EmailTemplate, l as RuntimeTemplate, m as escapeHtml, n as DataIssue, o as Purpose, p as Template, r as EmailParts, s as RenderOptions, t as CompiledParts, u as TemplateOptions } from "./types-Rd7be9eo.js";
|
|
2
|
+
/**
|
|
3
|
+
* What kind of problem an `EmailRenderError` reports:
|
|
4
|
+
* - `invalid-data`: the data doesn't match the template's schema; `issues` lists each field;
|
|
5
|
+
* - `missing-context` or `invalid-context`: a sender value passed to `createEmails()` is missing,
|
|
6
|
+
* empty, or not an https URL or email address where one is needed;
|
|
7
|
+
* - `subject-line-break`: the data puts a line break in the subject;
|
|
8
|
+
* - `missing-value`, `non-scalar-value`, `invalid-number`: a value can't fill its placeholder.
|
|
9
|
+
* With validation on, data that passes it never causes these;
|
|
10
|
+
* - `incompatible-module`: the generated module was compiled for another version of this package.
|
|
11
|
+
*/
|
|
12
|
+
type RenderErrorCode = "invalid-data" | "missing-context" | "invalid-context" | "subject-line-break" | "missing-value" | "non-scalar-value" | "invalid-number" | "incompatible-module";
|
|
13
|
+
/**
|
|
14
|
+
* Why an email couldn't be rendered. `code` says what kind of problem it is; for `invalid-data`,
|
|
15
|
+
* `issues` lists each field that doesn't match the schema, with its path.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* try {
|
|
20
|
+
* emails.welcome.render(data)
|
|
21
|
+
* } catch (error) {
|
|
22
|
+
* if (error instanceof EmailRenderError && error.code === "invalid-data") {
|
|
23
|
+
* console.error(error.issues) // [{ path: "name", message: "is required" }]
|
|
24
|
+
* }
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare class EmailRenderError extends Error {
|
|
29
|
+
/** What kind of problem it is, such as `"invalid-data"`. */
|
|
30
|
+
readonly code: RenderErrorCode;
|
|
31
|
+
/** For `invalid-data`: each field that doesn't match the schema. Empty otherwise. */
|
|
32
|
+
readonly issues: readonly DataIssue[];
|
|
33
|
+
/**
|
|
34
|
+
* @param code - What kind of problem it is.
|
|
35
|
+
* @param message - What went wrong, for people.
|
|
36
|
+
* @param issues - For `invalid-data`, each field that doesn't match the schema.
|
|
37
|
+
*/
|
|
38
|
+
constructor(code: RenderErrorCode, message: string, issues?: readonly DataIssue[]);
|
|
39
|
+
}
|
|
40
|
+
/** The generated-module format this runtime renders. `email-kit compile` writes it. */
|
|
41
|
+
export declare const FORMAT = 1;
|
|
42
|
+
/**
|
|
43
|
+
* Makes one email of the generated `emails` object. Its `render()` validates the data when
|
|
44
|
+
* `options.validate` is given, picks the locale, keeps only the schema's fields, adds the plural
|
|
45
|
+
* and select flags and the sender values, and fills the four parts.
|
|
46
|
+
*
|
|
47
|
+
* The generated module calls it; apps call `render()` on the result.
|
|
48
|
+
*
|
|
49
|
+
* @param spec - The template: id, purpose, data model, locales and compiled parts.
|
|
50
|
+
* @param options - The module's format and the features it uses.
|
|
51
|
+
* @throws {EmailRenderError} `incompatible-module` when the module was compiled for another
|
|
52
|
+
* version of this package.
|
|
53
|
+
*/
|
|
54
|
+
export declare function createTemplate(spec: TemplateSpec, options: TemplateOptions): RuntimeTemplate;
|
|
55
|
+
export { type CompiledParts, type DataIssue, type EmailParts, type EmailTemplate, type Model, type Node, type Purpose, type RenderErrorCode, type RenderOptions, type RenderedEmail, type RuntimeTemplate, type Template, type TemplateOptions, type TemplateSpec, escapeHtml, fill };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { t as EmailRenderError } from "./errors-B2PPlpPP.js";
|
|
2
|
+
import { a as isObject, i as hasOwn, r as has } from "./shared-DpUIeN9b.js";
|
|
3
|
+
// src/render.ts
|
|
4
|
+
/** The characters escaped in HTML, and what replaces them. */
|
|
5
|
+
const HTML_ESCAPES = {
|
|
6
|
+
"&": "&",
|
|
7
|
+
"<": "<",
|
|
8
|
+
">": ">",
|
|
9
|
+
"\"": """,
|
|
10
|
+
"'": "'"
|
|
11
|
+
};
|
|
12
|
+
/** Escapes `&`, `<`, `>`, `"` and `'` for HTML. */
|
|
13
|
+
function escapeHtml(value) {
|
|
14
|
+
return value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Fills a compiled template with data, following mustache-core@1. Values are HTML-escaped when
|
|
18
|
+
* `html` is set (the `html` part), and written as they are otherwise (`subject`, `preheader`,
|
|
19
|
+
* `text`). A missing value or one that isn't a string, number or boolean throws an
|
|
20
|
+
* `EmailRenderError`.
|
|
21
|
+
*/
|
|
22
|
+
function fill(template, data, html) {
|
|
23
|
+
return renderNodes(template, [data], html);
|
|
24
|
+
}
|
|
25
|
+
/** Renders nodes against a stack of contexts, the innermost last. */
|
|
26
|
+
function renderNodes(nodes, stack, html) {
|
|
27
|
+
let out = "";
|
|
28
|
+
for (const node of nodes) {
|
|
29
|
+
if (typeof node === "string") {
|
|
30
|
+
out += node;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const [kind, name] = node;
|
|
34
|
+
if (kind < 2) {
|
|
35
|
+
const value = toText(lookup(stack, name), name);
|
|
36
|
+
out += html && kind === 0 ? escapeHtml(value) : value;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const children = node[2];
|
|
40
|
+
const value = lookup(stack, name);
|
|
41
|
+
const truthy = isTruthy(value, name);
|
|
42
|
+
if (kind === 3) {
|
|
43
|
+
if (!truthy) out += renderNodes(children, stack, html);
|
|
44
|
+
} else if (Array.isArray(value)) for (const item of value) {
|
|
45
|
+
stack.push(item);
|
|
46
|
+
out += renderNodes(children, stack, html);
|
|
47
|
+
stack.pop();
|
|
48
|
+
}
|
|
49
|
+
else if (value === true) out += renderNodes(children, stack, html);
|
|
50
|
+
else if (truthy) {
|
|
51
|
+
stack.push(value);
|
|
52
|
+
out += renderNodes(children, stack, html);
|
|
53
|
+
stack.pop();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Finds `name` in the innermost context that has its first part, then follows the rest of the
|
|
60
|
+
* path in that context only. `.` is the innermost context itself.
|
|
61
|
+
*/
|
|
62
|
+
function lookup(stack, name) {
|
|
63
|
+
if (name === ".") return stack[stack.length - 1];
|
|
64
|
+
const [first = "", ...rest] = name.split(".");
|
|
65
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
66
|
+
const context = stack[i];
|
|
67
|
+
if (isObject(context) && hasOwn(context, first)) {
|
|
68
|
+
let value = context[first];
|
|
69
|
+
for (const key of rest) {
|
|
70
|
+
if (!isObject(value) || !hasOwn(value, key)) return void 0;
|
|
71
|
+
value = value[key];
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Whether a section shows. Missing, `null`, `false`, `""`, `0` and an empty list don't. */
|
|
78
|
+
function isTruthy(value, name) {
|
|
79
|
+
if (typeof value === "number") return finite(value, name) !== 0;
|
|
80
|
+
if (Array.isArray(value)) return value.length > 0;
|
|
81
|
+
return !(value === void 0 || value === null || value === false || value === "");
|
|
82
|
+
}
|
|
83
|
+
/** A value as text. A missing value, or one that isn't a string, number or boolean, throws. */
|
|
84
|
+
function toText(value, name) {
|
|
85
|
+
if (typeof value === "string") return value;
|
|
86
|
+
if (typeof value === "number") return String(finite(value, name));
|
|
87
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
88
|
+
if (value === void 0 || value === null) fail("missing-value", `No value for "${name}"`);
|
|
89
|
+
return fail("non-scalar-value", `"${name}" is not a string, number or boolean`);
|
|
90
|
+
}
|
|
91
|
+
function finite(value, name) {
|
|
92
|
+
if (!Number.isFinite(value)) fail("invalid-number", `"${name}" is ${value}`);
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
function fail(code, message) {
|
|
96
|
+
throw new EmailRenderError(code, message);
|
|
97
|
+
}
|
|
98
|
+
// src/project.ts
|
|
99
|
+
/**
|
|
100
|
+
* A copy of the data with only the fields the schema has, and `null` for missing optional fields,
|
|
101
|
+
* so a tag never finds a same-named field of an outer object instead.
|
|
102
|
+
*/
|
|
103
|
+
function project(model, value) {
|
|
104
|
+
if (model.type === "array") return Array.isArray(value) ? value.map((item) => project(model.items, item)) : value;
|
|
105
|
+
if (model.type !== "object" || !isObject(value)) return value;
|
|
106
|
+
const out = {};
|
|
107
|
+
const required = model.required ?? [];
|
|
108
|
+
const properties = model.properties ?? {};
|
|
109
|
+
for (const key of Object.keys(properties)) if (has(value, key)) out[key] = project(properties[key], value[key]);
|
|
110
|
+
else if (required.indexOf(key) === -1) out[key] = null;
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
// src/template.ts
|
|
114
|
+
/** The generated-module format this runtime renders. `email-kit compile` writes it. */
|
|
115
|
+
const FORMAT = 1;
|
|
116
|
+
/**
|
|
117
|
+
* Makes one email of the generated `emails` object. Its `render()` validates the data when
|
|
118
|
+
* `options.validate` is given, picks the locale, keeps only the schema's fields, adds the plural
|
|
119
|
+
* and select flags and the sender values, and fills the four parts.
|
|
120
|
+
*
|
|
121
|
+
* The generated module calls it; apps call `render()` on the result.
|
|
122
|
+
*
|
|
123
|
+
* @param spec - The template: id, purpose, data model, locales and compiled parts.
|
|
124
|
+
* @param options - The module's format and the features it uses.
|
|
125
|
+
* @throws {EmailRenderError} `incompatible-module` when the module was compiled for another
|
|
126
|
+
* version of this package.
|
|
127
|
+
*/
|
|
128
|
+
function createTemplate(spec, options) {
|
|
129
|
+
if (options.format !== 1) throw new EmailRenderError("incompatible-module", `The emails were compiled for format ${options.format} of @email-kit/runtime, which renders format 1. Install the same version as @email-kit/cli, and run \`email-kit compile\``);
|
|
130
|
+
const { id, purpose, model, locales, parts } = spec;
|
|
131
|
+
const { context = {}, validate, plural, resolve } = options;
|
|
132
|
+
const default_ = locales[0];
|
|
133
|
+
const template = {
|
|
134
|
+
meta: {
|
|
135
|
+
id,
|
|
136
|
+
purpose,
|
|
137
|
+
locales
|
|
138
|
+
},
|
|
139
|
+
render(data, renderOptions = {}) {
|
|
140
|
+
if (validate) {
|
|
141
|
+
const issues = validate(model, data);
|
|
142
|
+
if (issues.length > 0) throw new EmailRenderError("invalid-data", `The data for "${id}" doesn't match its schema:\n${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`, issues);
|
|
143
|
+
}
|
|
144
|
+
const locale = resolve ? resolve(renderOptions.locale, locales) : default_;
|
|
145
|
+
const compiled = parts[locale];
|
|
146
|
+
const projected = project(model, data);
|
|
147
|
+
if (plural) plural.prepare(model, projected, plural.rules[locale] ?? (() => "other"));
|
|
148
|
+
const values = isObject(projected) ? {
|
|
149
|
+
...projected,
|
|
150
|
+
["_ek"]: {
|
|
151
|
+
...isObject(projected["_ek"]) ? projected["_ek"] : {},
|
|
152
|
+
context
|
|
153
|
+
}
|
|
154
|
+
} : projected;
|
|
155
|
+
const subject = fill(compiled.subject, values, false);
|
|
156
|
+
if (/[\r\n]/.test(subject)) throw new EmailRenderError("subject-line-break", `The subject of "${id}" contains a line break; check the data for CR or LF characters`);
|
|
157
|
+
return {
|
|
158
|
+
subject,
|
|
159
|
+
preheader: fill(compiled.preheader, values, false),
|
|
160
|
+
html: fill(compiled.html, values, true),
|
|
161
|
+
text: fill(compiled.text, values, false),
|
|
162
|
+
meta: {
|
|
163
|
+
id,
|
|
164
|
+
locale,
|
|
165
|
+
purpose
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
return validate ? {
|
|
171
|
+
...template,
|
|
172
|
+
validate: (data) => validate(model, data)
|
|
173
|
+
} : template;
|
|
174
|
+
}
|
|
175
|
+
export { EmailRenderError, FORMAT, createTemplate, escapeHtml, fill };
|
package/dist/locale.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** CLDR data for resolving a requested locale. Tags are lowercase. */
|
|
2
|
+
export interface LocaleData {
|
|
3
|
+
/**
|
|
4
|
+
* The next locale to try after one, from CLDR and the config's fallbacks: `es-mx` → `es-419`.
|
|
5
|
+
*/
|
|
6
|
+
readonly parents: Readonly<Record<string, string>>;
|
|
7
|
+
/** Each language's usual script: `sr` → `cyrl`. */
|
|
8
|
+
readonly scripts: Readonly<Record<string, string>>;
|
|
9
|
+
/** A region's script, where it differs from the language's: `zh-tw` → `hant`. */
|
|
10
|
+
readonly regions: Readonly<Record<string, string>>;
|
|
11
|
+
}
|
|
12
|
+
/** No CLDR data: only exact matches and dropping the last part of the tag. */
|
|
13
|
+
export declare const NO_LOCALE_DATA: LocaleData;
|
|
14
|
+
/**
|
|
15
|
+
* Picks the compiled locale for a requested one. It tries the tag, then its parents (`pt-AO` →
|
|
16
|
+
* `pt-PT` → `pt`), and falls back to the first available locale, the default.
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveLocale(requested: string | undefined, available: readonly string[], data?: LocaleData): string;
|
package/dist/locale.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { r as has } from "./shared-DpUIeN9b.js";
|
|
2
|
+
// src/locale.ts
|
|
3
|
+
/**
|
|
4
|
+
* `@email-kit/runtime/locale`: picks the compiled locale for a requested one. The generated module
|
|
5
|
+
* imports it when it has more than one locale, or `locales.fallback`.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
/** No CLDR data: only exact matches and dropping the last part of the tag. */
|
|
10
|
+
const NO_LOCALE_DATA = {
|
|
11
|
+
parents: {},
|
|
12
|
+
scripts: {},
|
|
13
|
+
regions: {}
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Picks the compiled locale for a requested one. It tries the tag, then its parents (`pt-AO` →
|
|
17
|
+
* `pt-PT` → `pt`), and falls back to the first available locale, the default.
|
|
18
|
+
*/
|
|
19
|
+
function resolveLocale(requested, available, data = NO_LOCALE_DATA) {
|
|
20
|
+
const fallback = available[0];
|
|
21
|
+
const keyOf = (tag) => {
|
|
22
|
+
const parts = tag.toLowerCase().replace(/_/g, "-").split("-");
|
|
23
|
+
const region = parts.length >= 2 && parts[1].length !== 4 ? data.regions[`${parts[0]}-${parts[1]}`] : void 0;
|
|
24
|
+
return (region ? [
|
|
25
|
+
parts[0],
|
|
26
|
+
region,
|
|
27
|
+
...parts.slice(1)
|
|
28
|
+
] : parts).join("-");
|
|
29
|
+
};
|
|
30
|
+
const compiled = {};
|
|
31
|
+
for (const locale of available) compiled[keyOf(locale)] = locale;
|
|
32
|
+
let tag = requested ? keyOf(requested) : void 0;
|
|
33
|
+
for (let steps = 0; tag && steps < 32; steps++) {
|
|
34
|
+
if (has(compiled, tag)) return compiled[tag];
|
|
35
|
+
const next = has(data.parents, tag) ? data.parents[tag] : truncate(tag, data);
|
|
36
|
+
tag = next === "und" || next === "root" ? void 0 : next;
|
|
37
|
+
}
|
|
38
|
+
return fallback;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The tag without its last part, or `undefined` when that would change the script: `zh-Hant`
|
|
42
|
+
* doesn't fall back to `zh`, which is written in Hans.
|
|
43
|
+
*/
|
|
44
|
+
function truncate(tag, data) {
|
|
45
|
+
const parts = tag.split("-");
|
|
46
|
+
parts.pop();
|
|
47
|
+
while (parts.length > 0 && parts[parts.length - 1].length === 1) parts.pop();
|
|
48
|
+
if (parts.length === 0) return void 0;
|
|
49
|
+
const script = tag.split("-")[1];
|
|
50
|
+
const likely = data.scripts[parts[0]];
|
|
51
|
+
if (parts.length === 1 && script.length === 4 && likely && script !== likely) return void 0;
|
|
52
|
+
return parts.join("-");
|
|
53
|
+
}
|
|
54
|
+
export { NO_LOCALE_DATA, resolveLocale };
|
package/dist/plural.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { a as Model } from "./types-Rd7be9eo.js";
|
|
2
|
+
/** The flag name for a select value, safe in a tag: `"pro-plan"` → `v_pro_2d_plan`. */
|
|
3
|
+
export declare function selectKey(value: string): string;
|
|
4
|
+
type Tree = Record<string, unknown>;
|
|
5
|
+
/**
|
|
6
|
+
* Adds the plural and select flags that compiled messages test, under `_ek` on each object in the
|
|
7
|
+
* data: `{ plural: { count: { one: true, exact_1: true } }, select: { plan: { v_pro: true } } }`.
|
|
8
|
+
* Flags from outer objects are copied in, so a list item can test a field of its parent.
|
|
9
|
+
*/
|
|
10
|
+
export declare function prepare(model: Model, value: unknown, category: (n: number) => string, inherited?: {
|
|
11
|
+
readonly plural: Tree;
|
|
12
|
+
readonly select: Tree;
|
|
13
|
+
}): void;
|
|
14
|
+
export {};
|
package/dist/plural.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { a as isObject } from "./shared-DpUIeN9b.js";
|
|
2
|
+
// src/plural.ts
|
|
3
|
+
/**
|
|
4
|
+
* `@email-kit/runtime/plural`: the flags compiled plurals and selects test. The generated module
|
|
5
|
+
* imports it when a template has `{n, plural, …}` or `{x, select, …}` in its messages.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
/** The flag name for a select value, safe in a tag: `"pro-plan"` → `v_pro_2d_plan`. */
|
|
10
|
+
function selectKey(value) {
|
|
11
|
+
return `v_${value.replace(/[^A-Za-z0-9]/gu, (c) => `_${c.codePointAt(0).toString(16)}_`)}`;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Adds the plural and select flags that compiled messages test, under `_ek` on each object in the
|
|
15
|
+
* data: `{ plural: { count: { one: true, exact_1: true } }, select: { plan: { v_pro: true } } }`.
|
|
16
|
+
* Flags from outer objects are copied in, so a list item can test a field of its parent.
|
|
17
|
+
*/
|
|
18
|
+
function prepare(model, value, category, inherited = {
|
|
19
|
+
plural: {},
|
|
20
|
+
select: {}
|
|
21
|
+
}) {
|
|
22
|
+
if (model.type === "array") {
|
|
23
|
+
if (Array.isArray(value)) for (const item of value) prepare(model.items, item, category, inherited);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (model.type !== "object" || !isObject(value)) return;
|
|
27
|
+
const plural = { ...inherited.plural };
|
|
28
|
+
const select = { ...inherited.select };
|
|
29
|
+
collect(model, value, plural, select, category);
|
|
30
|
+
if (Object.keys(plural).length > 0 || Object.keys(select).length > 0) value["_ek"] = {
|
|
31
|
+
plural,
|
|
32
|
+
select
|
|
33
|
+
};
|
|
34
|
+
const properties = model.properties ?? {};
|
|
35
|
+
for (const key of Object.keys(properties)) prepare(properties[key], value[key], category, {
|
|
36
|
+
plural,
|
|
37
|
+
select
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
function collect(model, value, plural, select, category) {
|
|
41
|
+
const properties = model.properties ?? {};
|
|
42
|
+
for (const key of Object.keys(properties)) {
|
|
43
|
+
const field = properties[key];
|
|
44
|
+
const v = value[key];
|
|
45
|
+
if ((field.type === "number" || field.type === "integer") && typeof v === "number" && Number.isFinite(v)) {
|
|
46
|
+
const entry = { [category(v)]: true };
|
|
47
|
+
if (Number.isSafeInteger(v) && v >= 0) entry[`exact_${v}`] = true;
|
|
48
|
+
plural[key] = entry;
|
|
49
|
+
} else if (field.type === "string" && field.enum && typeof v === "string") select[key] = { [selectKey(v)]: true };
|
|
50
|
+
else if (field.type === "object" && isObject(v)) {
|
|
51
|
+
const p = isObject(plural[key]) ? { ...plural[key] } : {};
|
|
52
|
+
const s = isObject(select[key]) ? { ...select[key] } : {};
|
|
53
|
+
collect(field, v, p, s, category);
|
|
54
|
+
plural[key] = p;
|
|
55
|
+
select[key] = s;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export { prepare, selectKey };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// src/shared.ts
|
|
2
|
+
/** A plain object: not `null` and not an array. */
|
|
3
|
+
function isObject(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
/** Whether an object has its own `key`, whatever its value. */
|
|
7
|
+
function hasOwn(object, key) {
|
|
8
|
+
return Object.prototype.hasOwnProperty.call(object, key);
|
|
9
|
+
}
|
|
10
|
+
/** Whether an object has its own `key`, set to something other than `undefined`. */
|
|
11
|
+
function has(record, key) {
|
|
12
|
+
return hasOwn(record, key) && record[key] !== void 0;
|
|
13
|
+
}
|
|
14
|
+
/** An https URL with a host. */
|
|
15
|
+
const HTTPS_URL = /^https:\/\/[^\s/?#]+[^\s]*$/i;
|
|
16
|
+
/** A value for an error message: a short quoted string, `null`, `a list` or `an object`. */
|
|
17
|
+
function describe(value) {
|
|
18
|
+
if (value === null) return "null";
|
|
19
|
+
if (Array.isArray(value)) return "a list";
|
|
20
|
+
if (typeof value === "string") return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);
|
|
21
|
+
return typeof value === "object" ? "an object" : `${typeof value} ${String(value)}`;
|
|
22
|
+
}
|
|
23
|
+
export { isObject as a, hasOwn as i, describe as n, has as r, HTTPS_URL as t };
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A piece of a compiled template, as the compiler writes it: literal text, or a tag. The compiler
|
|
3
|
+
* parses each `{{placeholder}}` template once, so nothing is parsed when an email is sent.
|
|
4
|
+
* - `[0, name]`: `{{name}}`, HTML-escaped in the `html` part;
|
|
5
|
+
* - `[1, name]`: `{{{name}}}`, never escaped;
|
|
6
|
+
* - `[2, name, children]`: `{{#name}}…{{/name}}`, shown for a truthy value, once per list item;
|
|
7
|
+
* - `[3, name, children]`: `{{^name}}…{{/name}}`, shown for a falsy value or an empty list.
|
|
8
|
+
*/
|
|
9
|
+
type Node = string | readonly [kind: 0 | 1, name: string] | readonly [kind: 2 | 3, name: string, children: readonly Node[]];
|
|
10
|
+
/** A compiled template: its pieces, in order. */
|
|
11
|
+
type Template = readonly Node[];
|
|
12
|
+
/** Escapes `&`, `<`, `>`, `"` and `'` for HTML. */
|
|
13
|
+
declare function escapeHtml(value: string): string;
|
|
14
|
+
/**
|
|
15
|
+
* Fills a compiled template with data, following mustache-core@1. Values are HTML-escaped when
|
|
16
|
+
* `html` is set (the `html` part), and written as they are otherwise (`subject`, `preheader`,
|
|
17
|
+
* `text`). A missing value or one that isn't a string, number or boolean throws an
|
|
18
|
+
* `EmailRenderError`.
|
|
19
|
+
*/
|
|
20
|
+
declare function fill(template: Template, data: unknown, html: boolean): string;
|
|
21
|
+
/** The legal purpose of an email, from `defineEmail({ purpose })`. */
|
|
22
|
+
type Purpose = "transactional" | "marketing" | "consent-request";
|
|
23
|
+
/**
|
|
24
|
+
* A template's data schema, cut down to what validating and rendering need: types, `enum`,
|
|
25
|
+
* nullability, limits such as `maxLength`, and fields marked as URLs.
|
|
26
|
+
*/
|
|
27
|
+
interface Model {
|
|
28
|
+
readonly type: "string" | "number" | "integer" | "boolean" | "array" | "object";
|
|
29
|
+
readonly nullable?: true;
|
|
30
|
+
readonly enum?: readonly string[];
|
|
31
|
+
readonly constraints?: Readonly<Record<string, number | string>>;
|
|
32
|
+
readonly url?: true;
|
|
33
|
+
readonly items?: Model;
|
|
34
|
+
readonly properties?: Readonly<Record<string, Model>>;
|
|
35
|
+
readonly required?: readonly string[];
|
|
36
|
+
}
|
|
37
|
+
/** One way the data doesn't match the schema. */
|
|
38
|
+
interface DataIssue {
|
|
39
|
+
/** Where, such as `order.items[2].price`, or `data` for the data itself. */
|
|
40
|
+
readonly path: string;
|
|
41
|
+
/** What's wrong, such as `expected a number, got string "12"`. */
|
|
42
|
+
readonly message: string;
|
|
43
|
+
}
|
|
44
|
+
/** One email in one locale, rendered. */
|
|
45
|
+
interface EmailParts {
|
|
46
|
+
/** The `Subject:` header. */
|
|
47
|
+
readonly subject: string;
|
|
48
|
+
/** The preview text inboxes show after the subject. It's also the start of `html` and `text`. */
|
|
49
|
+
readonly preheader: string;
|
|
50
|
+
/** The HTML body. */
|
|
51
|
+
readonly html: string;
|
|
52
|
+
/** The plain-text body. Send it with `html` as multipart/alternative. */
|
|
53
|
+
readonly text: string;
|
|
54
|
+
}
|
|
55
|
+
/** How to render an email. */
|
|
56
|
+
interface RenderOptions<Locale extends string = string> {
|
|
57
|
+
/**
|
|
58
|
+
* A BCP 47 tag. Falls back along CLDR's parents (`es-AR` → `es-419` → `es`, `de-AT` → `de`)
|
|
59
|
+
* and `locales.fallback`, then to the default locale. Default: the default locale.
|
|
60
|
+
*/
|
|
61
|
+
readonly locale?: Locale | (string & {}) | undefined;
|
|
62
|
+
}
|
|
63
|
+
/** A rendered email: send `html` and `text` as multipart/alternative, with `subject`. */
|
|
64
|
+
interface RenderedEmail<Id extends string = string, Locale extends string = string> extends EmailParts {
|
|
65
|
+
/** Which template and locale it came from, and why it's sent. */
|
|
66
|
+
readonly meta: {
|
|
67
|
+
readonly id: Id;
|
|
68
|
+
readonly locale: Locale;
|
|
69
|
+
readonly purpose: Purpose;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** One email of the generated `emails` object, such as `emails.welcome`. */
|
|
73
|
+
interface EmailTemplate<Id extends string, Data, Locale extends string = string> {
|
|
74
|
+
/** The template id, why it's sent, and the locales it's compiled in, the default first. */
|
|
75
|
+
readonly meta: {
|
|
76
|
+
readonly id: Id;
|
|
77
|
+
readonly purpose: Purpose;
|
|
78
|
+
readonly locales: readonly Locale[];
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Fills the template for one locale. Values are HTML-escaped in `html` only. With validation on
|
|
82
|
+
* (the default), invalid data throws an `EmailRenderError` (`invalid-data`) listing each field.
|
|
83
|
+
*
|
|
84
|
+
* @param data - The template's data, as its schema describes it.
|
|
85
|
+
* @param options - The locale to render in.
|
|
86
|
+
* @returns The subject, preheader, HTML and text, with `meta`.
|
|
87
|
+
*/
|
|
88
|
+
render(data: Data, options?: RenderOptions<Locale>): RenderedEmail<Id, Locale>;
|
|
89
|
+
/**
|
|
90
|
+
* Checks data against the template's schema without rendering, for data from a queue or
|
|
91
|
+
* webhook. Not there when the project compiles with `validate: false`.
|
|
92
|
+
*
|
|
93
|
+
* @param data - Anything.
|
|
94
|
+
* @returns Every problem, each with its path; empty when the data is valid.
|
|
95
|
+
*/
|
|
96
|
+
validate(data: unknown): readonly DataIssue[];
|
|
97
|
+
}
|
|
98
|
+
/** One email in one locale, as the compiler writes it: each part a compiled template. */
|
|
99
|
+
interface CompiledParts {
|
|
100
|
+
readonly subject: Template;
|
|
101
|
+
readonly preheader: Template;
|
|
102
|
+
readonly html: Template;
|
|
103
|
+
readonly text: Template;
|
|
104
|
+
}
|
|
105
|
+
/** What the generated module knows about one template. */
|
|
106
|
+
interface TemplateSpec {
|
|
107
|
+
readonly id: string;
|
|
108
|
+
readonly purpose: Purpose;
|
|
109
|
+
/** The schema's data model, for projecting (and validating) the data. */
|
|
110
|
+
readonly model: Model;
|
|
111
|
+
/** Every compiled locale, the default first. */
|
|
112
|
+
readonly locales: readonly string[];
|
|
113
|
+
/** The compiled parts in each locale. */
|
|
114
|
+
readonly parts: Readonly<Record<string, CompiledParts>>;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The runtime features the generated module turns on. Each optional one comes from its own entry
|
|
118
|
+
* point, so a project that doesn't use it doesn't load or bundle it.
|
|
119
|
+
*/
|
|
120
|
+
interface TemplateOptions {
|
|
121
|
+
/** The generated module's format. The runtime refuses one it doesn't know. */
|
|
122
|
+
readonly format: number;
|
|
123
|
+
/** The sender values passed at send time, checked by `readContext()`. */
|
|
124
|
+
readonly context?: Readonly<Record<string, string>>;
|
|
125
|
+
/**
|
|
126
|
+
* `validate` from `@email-kit/runtime/validate`: `render()` checks data first, and each
|
|
127
|
+
* template has `validate()`.
|
|
128
|
+
*/
|
|
129
|
+
readonly validate?: (model: Model, data: unknown) => DataIssue[];
|
|
130
|
+
/**
|
|
131
|
+
* `prepare` from `@email-kit/runtime/plural`, with each locale's CLDR plural rule: adds the
|
|
132
|
+
* flags compiled plurals and selects test.
|
|
133
|
+
*/
|
|
134
|
+
readonly plural?: {
|
|
135
|
+
readonly prepare: (model: Model, data: unknown, category: (n: number) => string) => void;
|
|
136
|
+
readonly rules: Readonly<Record<string, (n: number) => string>>;
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Picks the compiled locale for a requested one, from `@email-kit/runtime/locale`. Without it,
|
|
140
|
+
* every email renders in the default locale: the module has only one.
|
|
141
|
+
*/
|
|
142
|
+
readonly resolve?: (requested: string | undefined, available: readonly string[]) => string;
|
|
143
|
+
}
|
|
144
|
+
/** What `createTemplate()` returns, before the generated module gives it its exact type. */
|
|
145
|
+
interface RuntimeTemplate {
|
|
146
|
+
readonly meta: {
|
|
147
|
+
readonly id: string;
|
|
148
|
+
readonly purpose: Purpose;
|
|
149
|
+
readonly locales: readonly string[];
|
|
150
|
+
};
|
|
151
|
+
render(data: unknown, options?: RenderOptions): RenderedEmail;
|
|
152
|
+
validate?(data: unknown): readonly DataIssue[];
|
|
153
|
+
}
|
|
154
|
+
export { Model as a, RenderedEmail as c, TemplateSpec as d, Node as f, fill as h, EmailTemplate as i, RuntimeTemplate as l, escapeHtml as m, DataIssue as n, Purpose as o, Template as p, EmailParts as r, RenderOptions as s, CompiledParts as t, TemplateOptions as u };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { a as Model, n as DataIssue } from "./types-Rd7be9eo.js";
|
|
2
|
+
/** Checks data against a template's model, and returns every problem with its path. */
|
|
3
|
+
export declare function validate(model: Model, value: unknown, path?: string): DataIssue[];
|
|
4
|
+
export type { DataIssue, Model };
|
package/dist/validate.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { a as isObject, n as describe, r as has, t as HTTPS_URL } from "./shared-DpUIeN9b.js";
|
|
2
|
+
// src/validate.ts
|
|
3
|
+
/**
|
|
4
|
+
* `@email-kit/runtime/validate`: checks data against a template's schema. The generated module
|
|
5
|
+
* imports it unless the project compiles with `validate: false`.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
function counted(n, word) {
|
|
10
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
11
|
+
}
|
|
12
|
+
/** Checks data against a template's model, and returns every problem with its path. */
|
|
13
|
+
function validate(model, value, path = "") {
|
|
14
|
+
const issues = [];
|
|
15
|
+
const at = path || "data";
|
|
16
|
+
const fail = (message) => issues.push({
|
|
17
|
+
path: at,
|
|
18
|
+
message
|
|
19
|
+
});
|
|
20
|
+
if (value === null || value === void 0) {
|
|
21
|
+
if (value === null && model.nullable) return issues;
|
|
22
|
+
fail(value === null ? "can't be null" : "is required");
|
|
23
|
+
return issues;
|
|
24
|
+
}
|
|
25
|
+
const constraints = model.constraints ?? {};
|
|
26
|
+
const number = (name) => {
|
|
27
|
+
const limit = constraints[name];
|
|
28
|
+
return typeof limit === "number" ? limit : void 0;
|
|
29
|
+
};
|
|
30
|
+
const text = (name) => {
|
|
31
|
+
const limit = constraints[name];
|
|
32
|
+
return typeof limit === "string" ? limit : void 0;
|
|
33
|
+
};
|
|
34
|
+
switch (model.type) {
|
|
35
|
+
case "string": {
|
|
36
|
+
if (typeof value !== "string") {
|
|
37
|
+
fail(`expected a string, got ${describe(value)}`);
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
const length = Array.from(value).length;
|
|
41
|
+
if (model.enum && model.enum.indexOf(value) === -1) fail(`expected one of ${model.enum.map((v) => JSON.stringify(v)).join(", ")}, got ${describe(value)}`);
|
|
42
|
+
const min = number("minLength");
|
|
43
|
+
const max = number("maxLength");
|
|
44
|
+
const pattern = text("pattern");
|
|
45
|
+
if (min !== void 0 && length < min) fail(`must be at least ${counted(min, "character")}`);
|
|
46
|
+
if (max !== void 0 && length > max) fail(`must be at most ${counted(max, "character")}`);
|
|
47
|
+
if (pattern !== void 0 && !new RegExp(pattern, "u").test(value)) fail(`must match ${pattern}`);
|
|
48
|
+
if (model.url && !HTTPS_URL.test(value)) fail(`must be an https URL, got ${describe(value)}`);
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case "number":
|
|
52
|
+
case "integer": {
|
|
53
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
54
|
+
fail(`expected a number, got ${describe(value)}`);
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
if (model.type === "integer" && Math.floor(value) !== value) fail(`expected an integer, got ${value}`);
|
|
58
|
+
const bounds = [
|
|
59
|
+
[
|
|
60
|
+
"minimum",
|
|
61
|
+
(limit) => value >= limit,
|
|
62
|
+
"at least"
|
|
63
|
+
],
|
|
64
|
+
[
|
|
65
|
+
"maximum",
|
|
66
|
+
(limit) => value <= limit,
|
|
67
|
+
"at most"
|
|
68
|
+
],
|
|
69
|
+
[
|
|
70
|
+
"exclusiveMinimum",
|
|
71
|
+
(limit) => value > limit,
|
|
72
|
+
"more than"
|
|
73
|
+
],
|
|
74
|
+
[
|
|
75
|
+
"exclusiveMaximum",
|
|
76
|
+
(limit) => value < limit,
|
|
77
|
+
"less than"
|
|
78
|
+
]
|
|
79
|
+
];
|
|
80
|
+
for (const [name, ok, words] of bounds) {
|
|
81
|
+
const limit = number(name);
|
|
82
|
+
if (limit !== void 0 && !ok(limit)) fail(`must be ${words} ${limit}, got ${value}`);
|
|
83
|
+
}
|
|
84
|
+
const step = number("multipleOf");
|
|
85
|
+
if (step !== void 0 && Math.abs(value / step - Math.round(value / step)) > 1e-9) fail(`must be a multiple of ${step}`);
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
case "boolean":
|
|
89
|
+
if (typeof value !== "boolean") fail(`expected true or false, got ${describe(value)}`);
|
|
90
|
+
break;
|
|
91
|
+
case "array": {
|
|
92
|
+
if (!Array.isArray(value)) {
|
|
93
|
+
fail(`expected a list, got ${describe(value)}`);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
const minItems = number("minItems");
|
|
97
|
+
const maxItems = number("maxItems");
|
|
98
|
+
if (minItems !== void 0 && value.length < minItems) fail(`must have at least ${counted(minItems, "item")}`);
|
|
99
|
+
if (maxItems !== void 0 && value.length > maxItems) fail(`must have at most ${counted(maxItems, "item")}`);
|
|
100
|
+
value.forEach((item, index) => {
|
|
101
|
+
issues.push(...validate(model.items, item, `${path}[${index}]`));
|
|
102
|
+
});
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
case "object": {
|
|
106
|
+
if (!isObject(value)) {
|
|
107
|
+
fail(`expected an object, got ${describe(value)}`);
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
const required = model.required ?? [];
|
|
111
|
+
const properties = model.properties ?? {};
|
|
112
|
+
for (const key of Object.keys(properties)) {
|
|
113
|
+
const child = path ? `${path}.${key}` : key;
|
|
114
|
+
if (has(value, key)) issues.push(...validate(properties[key], value[key], child));
|
|
115
|
+
else if (required.indexOf(key) !== -1) issues.push({
|
|
116
|
+
path: child,
|
|
117
|
+
message: "is required"
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return issues;
|
|
124
|
+
}
|
|
125
|
+
export { validate };
|
package/package.json
CHANGED
|
@@ -1,6 +1,84 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@email-kit/runtime",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "email-kit runtime: renders the emails `email-kit compile` generates. The only email-kit package an app needs at runtime; zero dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"email",
|
|
7
|
+
"email-templates",
|
|
8
|
+
"typescript",
|
|
9
|
+
"mustache",
|
|
10
|
+
"runtime"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/email-kit/email-kit#readme",
|
|
13
|
+
"bugs": "https://github.com/email-kit/email-kit/issues",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/email-kit/email-kit.git",
|
|
17
|
+
"directory": "packages/runtime"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"type": "module",
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./validate": {
|
|
28
|
+
"types": "./dist/validate.d.ts",
|
|
29
|
+
"default": "./dist/validate.js"
|
|
30
|
+
},
|
|
31
|
+
"./plural": {
|
|
32
|
+
"types": "./dist/plural.d.ts",
|
|
33
|
+
"default": "./dist/plural.js"
|
|
34
|
+
},
|
|
35
|
+
"./locale": {
|
|
36
|
+
"types": "./dist/locale.d.ts",
|
|
37
|
+
"default": "./dist/locale.js"
|
|
38
|
+
},
|
|
39
|
+
"./context": {
|
|
40
|
+
"types": "./dist/context.d.ts",
|
|
41
|
+
"default": "./dist/context.js"
|
|
42
|
+
},
|
|
43
|
+
"./package.json": "./package.json"
|
|
44
|
+
},
|
|
45
|
+
"types": "./dist/index.d.ts",
|
|
46
|
+
"typesVersions": {
|
|
47
|
+
"*": {
|
|
48
|
+
"validate": [
|
|
49
|
+
"./dist/validate.d.ts"
|
|
50
|
+
],
|
|
51
|
+
"plural": [
|
|
52
|
+
"./dist/plural.d.ts"
|
|
53
|
+
],
|
|
54
|
+
"locale": [
|
|
55
|
+
"./dist/locale.d.ts"
|
|
56
|
+
],
|
|
57
|
+
"context": [
|
|
58
|
+
"./dist/context.d.ts"
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"files": [
|
|
63
|
+
"dist"
|
|
64
|
+
],
|
|
65
|
+
"engines": {
|
|
66
|
+
"node": ">=22.12"
|
|
67
|
+
},
|
|
68
|
+
"publishConfig": {
|
|
69
|
+
"access": "public"
|
|
70
|
+
},
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"@types/node": "22.20.5",
|
|
73
|
+
"rolldown": "1.2.15",
|
|
74
|
+
"tsdown": "0.23.2",
|
|
75
|
+
"typescript": "7.0.2",
|
|
76
|
+
"vitest": "5.0.5"
|
|
77
|
+
},
|
|
78
|
+
"scripts": {
|
|
79
|
+
"build": "tsdown",
|
|
80
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
81
|
+
"test": "vitest run",
|
|
82
|
+
"check:package": "publint --strict && attw --pack . --profile esm-only"
|
|
83
|
+
}
|
|
6
84
|
}
|