feat: release design system engine, studio and component contracts

This commit is contained in:
Clintchiz committed 2026-10-19 13:09:03 +05:30
1 parent ff1065fb27
commit 3943b946d6
693 files changed
+175546 -3894

No files matched your search

+23 -4
View File
@@ -4,10 +4,29 @@ import { renderEmail } from "../src/email.ts";
import type { BlockDocument } from "@wrnexus/blocks";
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Local preview", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: {
content: [{ id: "text", type: "content.text", version: 1, props: { text: "Hello {{recipientName|friend}}" }, styles: {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Local preview", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "text",
type: "content.text",
version: 1,
props: { text: "Hello {{recipientName|friend}}" },
styles: {},
slots: {},
},
],
},
},
};
test("browser preview matches production HTML/text without server validators", async () => {
+131 -24
View File
@@ -5,18 +5,55 @@ import { renderEmail, validateMjml } from "../src/index.ts";
test("button alignment maps physical and logical positions consistently in LTR and RTL", async () => {
for (const direction of ["ltr", "rtl"] as const) {
for (const alignment of [undefined, "left", "center", "right", "start", "end"]) {
const expected = !alignment || alignment === "start" ? (direction === "rtl" ? "right" : "left") : alignment === "end" ? (direction === "rtl" ? "left" : "right") : alignment;
const expected =
!alignment || alignment === "start"
? direction === "rtl"
? "right"
: "left"
: alignment === "end"
? direction === "rtl"
? "left"
: "right"
: alignment;
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Alignment", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: {
content: [{ id: "cta", type: "content.button", version: 1, props: { label: "Act", href: "https://example.com" }, styles: alignment ? { textAlign: { base: alignment } } : {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Alignment", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "cta",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: alignment ? { textAlign: { base: alignment } } : {},
slots: {},
},
],
},
},
};
const rendered = await renderEmail(document, { direction, amp: true, mjml: true, ampValidationTimeoutMs: 10000 });
const rendered = await renderEmail(document, {
direction,
amp: true,
mjml: true,
ampValidationTimeoutMs: 10000,
});
expect(rendered.ok).toBe(true);
if (!rendered.ok) continue;
expect(rendered.value.parts.html.content).toContain(`<table role="presentation" align="${expected}" cellpadding="0"`);
expect(rendered.value.parts.amp?.content).toContain(`data-block-id="cta" align="${expected}"`);
expect(rendered.value.parts.html.content).toContain(
`<table role="presentation" align="${expected}" cellpadding="0"`,
);
expect(rendered.value.parts.amp?.content).toContain(
`data-block-id="cta" align="${expected}"`,
);
expect(rendered.value.parts.amp?.validation.valid).toBe(true);
expect(rendered.value.exports?.mjml).toContain(`<mj-button align="${expected}"`);
}
@@ -25,24 +62,62 @@ test("button alignment maps physical and logical positions consistently in LTR a
test("button typography and corners reach the clickable element in every target", async () => {
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Styled CTA", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: {
content: [{ id: "cta", type: "content.button", version: 1, props: { label: "Read more", href: "https://example.com" }, styles: {
color: { base: "#123456" }, fontSize: { base: "22px" }, fontWeight: { base: "400" }, borderRadius: { base: "18px" },
}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Styled CTA", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "cta",
type: "content.button",
version: 1,
props: { label: "Read more", href: "https://example.com" },
styles: {
color: { base: "#123456" },
fontSize: { base: "22px" },
fontWeight: { base: "400" },
borderRadius: { base: "18px" },
},
slots: {},
},
],
},
},
};
const before = structuredClone(document);
const result = await renderEmail(document, { amp: true, mjml: true, ampValidationTimeoutMs: 10000 });
const result = await renderEmail(document, {
amp: true,
mjml: true,
ampValidationTimeoutMs: 10000,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const anchor = result.value.parts.html.content.match(/<a href="https:\/\/example.com" style="([^"]+)"/)?.[1];
for (const declaration of ["color:#123456", "font-size:22px", "font-weight:400", "border-radius:18px"]) {
const anchor = result.value.parts.html.content.match(
/<a href="https:\/\/example.com" style="([^"]+)"/,
)?.[1];
for (const declaration of [
"color:#123456",
"font-size:22px",
"font-weight:400",
"border-radius:18px",
]) {
expect(anchor).toContain(declaration);
expect(result.value.parts.amp?.content).toContain(declaration);
}
expect(result.value.parts.amp?.validation.valid).toBe(true);
for (const attribute of ['color="#123456"', 'font-size="22px"', 'font-weight="400"', 'border-radius="18px"']) {
for (const attribute of [
'color="#123456"',
'font-size="22px"',
'font-weight="400"',
'border-radius="18px"',
]) {
expect(result.value.exports?.mjml).toContain(attribute);
}
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
@@ -52,14 +127,46 @@ test("button typography and corners reach the clickable element in every target"
test("button background inherits brand color with explicit semantic overrides across formats", async () => {
for (const override of [undefined, "#aabbcc"]) {
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Brand", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { linkColor: "#125634" }, styles: {}, slots: {
content: [{ id: "button", type: "content.button", version: 1, props: { label: "Act", href: "https://example.com" }, styles: override ? { backgroundColor: { base: override } } : {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Brand", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { linkColor: "#125634" },
styles: {},
slots: {
content: [
{
id: "button",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: override ? { backgroundColor: { base: override } } : {},
slots: {},
},
],
},
},
};
document.root.slots.content = [{ id: "section", type: "layout.section", version: 1, props: {}, styles: {}, slots: { content: document.root.slots.content } }];
document.root.slots.content = [
{
id: "section",
type: "layout.section",
version: 1,
props: {},
styles: {},
slots: { content: document.root.slots.content },
},
];
const before = structuredClone(document);
const rendered = await renderEmail(document, { amp: true, mjml: true, ampValidationTimeoutMs: 10000 });
const rendered = await renderEmail(document, {
amp: true,
mjml: true,
ampValidationTimeoutMs: 10000,
});
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
const color = override ?? "#125634";
@@ -2,8 +2,19 @@ import { expect, test } from "bun:test";
import { buttonBlock, ampLayoutCss } from "../src/blocks.ts";
test("button visuals target the clickable surface rather than the full-width wrapper", async () => {
const node = {id:"cta",type:"content.button",version:1,props:{label:"Act",href:"https://example.com"},styles:{backgroundColor:{base:"#123456"},padding:{base:"8px 32px"},borderRadius:{base:"20px"}},slots:{}};
const context = {node,context:{},slots:{}} as never;
const node = {
id: "cta",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: {
backgroundColor: { base: "#123456" },
padding: { base: "8px 32px" },
borderRadius: { base: "20px" },
},
slots: {},
};
const context = { node, context: {}, slots: {} } as never;
const html = String(await buttonBlock.renderers!.emailHtml!(context));
const wrapper = html.match(/<td data-block-id="cta"[^>]*>/)![0];
expect(wrapper).not.toContain("#123456");
@@ -12,7 +12,7 @@ test("countdown ticks across boundaries and stops at zero", () => {
test("countdown generates deterministic bounded non-looping GIF output", () => {
const first = renderCountdownGif(60000, 0);
expect(first).toEqual(renderCountdownGif(60000, 0));
expect(new TextDecoder().decode(first.subarray(0,6))).toBe("GIF89a");
expect(new TextDecoder().decode(first.subarray(0, 6))).toBe("GIF89a");
expect(first[6]! + first[7]! * 256).toBe(320);
expect(first[8]! + first[9]! * 256).toBe(64);
expect(first.at(-1)).toBe(0x3b);
+7 -3
View File
@@ -4,15 +4,19 @@ import { emailCoreBlocks } from "../src/blocks.ts";
test("palette factory produces schema-valid independent blocks with injected IDs and time", () => {
let sequence = 0;
for (const definition of emailCoreBlocks.filter(block => /^(content|commerce)\./.test(block.manifest.type))) {
for (const definition of emailCoreBlocks.filter((block) =>
/^(content|commerce)\./.test(block.manifest.type),
)) {
const context = { id: () => `node-${++sequence}`, now: Date.parse("2026-09-05T00:00:00Z") };
const first = createEmailBlock(definition.manifest.type, context), second = createEmailBlock(definition.manifest.type, context);
const first = createEmailBlock(definition.manifest.type, context),
second = createEmailBlock(definition.manifest.type, context);
expect(definition.manifest.props.parse(first.props).ok).toBe(true);
expect(first.id).not.toBe(second.id);
expect(first.props).toEqual(second.props);
expect(first.props).not.toBe(second.props);
expect(first.version).toBe(definition.manifest.version);
if (first.type === "content.countdown") expect(first.props.deadline).toBe("2026-09-06T00:00:00.000Z");
if (first.type === "content.countdown")
expect(first.props.deadline).toBe("2026-09-06T00:00:00.000Z");
}
expect(() => createEmailBlock("untrusted.block", { id: () => "id" })).toThrow();
});
@@ -4,7 +4,9 @@ import { emailPresets } from "../src/presets.ts";
test("published email editor content factories return valid independent instances", () => {
let id = 0;
for (const definition of emailEditorBlocks.filter(block => block.manifest.category === "content")) {
for (const definition of emailEditorBlocks.filter(
(block) => block.manifest.category === "content",
)) {
const first = definition.create({ id: () => String(++id) });
const second = definition.create({ id: () => String(++id) });
expect(first.id).not.toBe(second.id);
+143 -38
View File
@@ -16,19 +16,35 @@ test("AMP section and spacer CSS retains configured layout values", async () =>
const draft = structuredClone(document);
const section = draft.root.slots.content[0]!;
section.props = { background: "#abcdef", padding: "12px 30px" };
const spacer = { id: 'spacer:one"', type: "content.spacer", version: 1, props: { height: "77" }, styles: {}, slots: {} };
const spacer = {
id: 'spacer:one"',
type: "content.spacer",
version: 1,
props: { height: "77" },
styles: {},
slots: {},
};
section.slots.content = [spacer];
const result = await renderEmail(draft, { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
const amp = result.value.parts.amp;
expect(amp?.validation.valid).toBe(true);
expect(amp?.content).toContain(`.${ampLayoutClass(section)}{background:#abcdef;padding:12px 30px}`);
expect(amp?.content).toContain(`.${ampLayoutClass(spacer)}{height:77px;line-height:77px;font-size:1px}`);
expect(amp?.content).toContain(
`.${ampLayoutClass(section)}{background:#abcdef;padding:12px 30px}`,
);
expect(amp?.content).toContain(
`.${ampLayoutClass(spacer)}{height:77px;line-height:77px;font-size:1px}`,
);
expect(amp?.content).toContain(`class="${ampLayoutClass(spacer)}"`);
expect(result.value.parts.html.content).toContain("height:77px");
expect(result.value.exports?.mjml).toContain('height="77px"');
expect(ampLayoutCss({ ...section, props: { background: "red;}body{display:none", padding: "</style>" } })).not.toContain("display:none");
expect(
ampLayoutCss({
...section,
props: { background: "red;}body{display:none", padding: "</style>" },
}),
).not.toContain("display:none");
});
const document: BlockDocument = {
@@ -78,33 +94,66 @@ const document: BlockDocument = {
describe("email renderer", () => {
test("optional AMP validation failures preserve HTML/text fallbacks", async () => {
for (const ampValidator of [async () => {throw new Error("network unavailable")}, () => new Promise<never>(() => {})]) {
const result=await renderEmail(document,{amp:true,ampValidator,ampValidationTimeoutMs:10});
for (const ampValidator of [
async () => {
throw new Error("network unavailable");
},
() => new Promise<never>(() => {}),
]) {
const result = await renderEmail(document, {
amp: true,
ampValidator,
ampValidationTimeoutMs: 10,
});
expect(result.ok).toBe(true);
if(!result.ok)continue;
if (!result.ok) continue;
expect(result.value.parts.amp).toBeUndefined();
expect(result.value.parts.html.content).toContain("Hello &lt;world&gt;");
expect(result.value.parts.text.content).toContain("Hello <world>");
expect(result.value.warnings.some(item=>item.code==="amp.validatorUnavailable"&&item.severity==="warning")).toBe(true);
expect(
result.value.warnings.some(
(item) => item.code === "amp.validatorUnavailable" && item.severity === "warning",
),
).toBe(true);
}
});
test("builder column rows export without nesting mj-column inside mj-column", async () => {
for (const count of [1,2,3,4]) {
const draft=structuredClone(document);
const content=draft.root.slots.content[0]!.slots.content;
draft.root.slots.content[0]!.slots.content=[{id:"columns",type:"layout.columns",version:1,props:{},styles:{},slots:{columns:Array.from({length:count},(_,index)=>({id:`column-${index}`,type:"layout.column",version:1,props:{width:`${100/count}%`},styles:{},slots:{content:index===0?content:[]}}))}}];
const result=await renderEmail(draft,{mjml:true,amp:true});
for (const count of [1, 2, 3, 4]) {
const draft = structuredClone(document);
const content = draft.root.slots.content[0]!.slots.content;
draft.root.slots.content[0]!.slots.content = [
{
id: "columns",
type: "layout.columns",
version: 1,
props: {},
styles: {},
slots: {
columns: Array.from({ length: count }, (_, index) => ({
id: `column-${index}`,
type: "layout.column",
version: 1,
props: { width: `${100 / count}%` },
styles: {},
slots: { content: index === 0 ? content : [] },
})),
},
},
];
const result = await renderEmail(draft, { mjml: true, amp: true });
expect(result.ok).toBe(true);
if(!result.ok)continue;
const mjml=result.value.exports!.mjml!;
if (!result.ok) continue;
const mjml = result.value.exports!.mjml!;
expect(mjml.match(/<mj-column\b/g)).toHaveLength(count);
expect(await validateMjml(mjml)).toEqual([]);
expect(mjml).toContain("Hello &lt;world&gt;");
const amp=result.value.parts.amp;
const amp = result.value.parts.amp;
expect(amp?.validation.valid).toBe(true);
expect(amp?.content.match(/class="wrn-column"/g)).toHaveLength(count);
expect(amp?.content).toContain('class="wrn-columns"');
expect(amp?.content).toContain('@media only screen and (max-width:480px){.email-body .wrn-columns{display:block}.email-body .wrn-column{display:block;width:100%}}');
expect(amp?.content).toContain(
"@media only screen and (max-width:480px){.email-body .wrn-columns{display:block}.email-body .wrn-column{display:block;width:100%}}",
);
}
});
test("global brand logo survives HTML, AMP, and strict MJML export", async () => {
@@ -113,10 +162,14 @@ describe("email renderer", () => {
draft.root.props.logoAlt = 'Brand & "Company"';
draft.root.props.logoWidth = "180";
draft.root.props.logoHeight = "90";
const result = await renderEmail(draft,{amp:true,mjml:true});
const result = await renderEmail(draft, { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
for (const output of [result.value.parts.html.content,result.value.parts.amp?.content,result.value.exports?.mjml]) {
for (const output of [
result.value.parts.html.content,
result.value.parts.amp?.content,
result.value.exports?.mjml,
]) {
expect(output).toContain('src="https://example.com/logo.png"');
expect(output).toContain('alt="Brand &amp; &quot;Company&quot;"');
}
@@ -124,8 +177,12 @@ describe("email renderer", () => {
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
expect(result.value.parts.html.content).toContain('width="180" height="90"');
expect(result.value.parts.amp?.content).toContain('width="180" height="90"');
expect(result.value.parts.amp?.content).toContain('width="180" height="90" layout="responsive"');
expect(result.value.parts.amp?.content).toContain('.brand-logo{max-width:180px;width:100%;margin:20px auto}');
expect(result.value.parts.amp?.content).toContain(
'width="180" height="90" layout="responsive"',
);
expect(result.value.parts.amp?.content).toContain(
".brand-logo{max-width:180px;width:100%;margin:20px auto}",
);
expect(result.value.exports?.mjml).toContain('width="180px" height="90px"');
for (const value of ["0", "4001", "180px", "1;display:none"]) {
const invalid = structuredClone(draft);
@@ -133,7 +190,7 @@ describe("email renderer", () => {
expect((await renderEmail(invalid)).ok).toBe(false);
}
draft.root.props.logoUrl = "";
const empty = await renderEmail(draft,{amp:true,mjml:true});
const empty = await renderEmail(draft, { amp: true, mjml: true });
expect(empty.ok).toBe(true);
if (empty.ok) {
expect(empty.value.parts.amp?.content).not.toContain("<amp-img");
@@ -143,13 +200,21 @@ describe("email renderer", () => {
test("text line breaks survive all formats without interpreting entered markup", async () => {
const draft = structuredClone(document);
const text = 'First line\r\nSecond line\n\n<script>alert("x")</script>\rLast line';
draft.root.slots.content[0]!.slots.content = [{id:"text",type:"content.text",version:1,props:{text},styles:{},slots:{}}];
const rendered = await renderEmail(draft,{amp:true,mjml:true});
draft.root.slots.content[0]!.slots.content = [
{ id: "text", type: "content.text", version: 1, props: { text }, styles: {}, slots: {} },
];
const rendered = await renderEmail(draft, { amp: true, mjml: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
for (const output of [rendered.value.parts.html.content,rendered.value.parts.amp?.content,rendered.value.exports?.mjml]) {
expect(output).toContain('First line<br />Second line<br /><br />&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;<br />Last line');
expect(output).not.toContain('<script>alert');
for (const output of [
rendered.value.parts.html.content,
rendered.value.parts.amp?.content,
rendered.value.exports?.mjml,
]) {
expect(output).toContain(
"First line<br />Second line<br /><br />&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;<br />Last line",
);
expect(output).not.toContain("<script>alert");
}
expect(rendered.value.parts.text.content).toContain(text);
expect(rendered.value.parts.amp?.validation.valid).toBe(true);
@@ -157,21 +222,44 @@ describe("email renderer", () => {
});
test("AMP inherits the saved brand font, colors and body width", async () => {
const draft = structuredClone(document);
Object.assign(draft.root.props, {width:"720",fontFamily:"Georgia, serif",textColor:"#112233",linkColor:"#445566",background:"#eeeeee",contentBackground:"#fafafa"});
const rendered = await renderEmail(draft, {amp:true});
Object.assign(draft.root.props, {
width: "720",
fontFamily: "Georgia, serif",
textColor: "#112233",
linkColor: "#445566",
background: "#eeeeee",
contentBackground: "#fafafa",
});
const rendered = await renderEmail(draft, { amp: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
const amp = rendered.value.parts.amp;
expect(amp?.validation.valid).toBe(true);
for (const style of ["font-family:Georgia, serif", "color:#112233", "a{color:#445566}", "background:#eeeeee", "background:#fafafa", "max-width:720px"]) expect(amp?.content).toContain(style);
for (const style of [
"font-family:Georgia, serif",
"color:#112233",
"a{color:#445566}",
"background:#eeeeee",
"background:#fafafa",
"max-width:720px",
])
expect(amp?.content).toContain(style);
});
test("brand fields reject arbitrary CSS and invalid widths before rendering", async () => {
for (const [key,value] of [["fontFamily","Arial;position:fixed"],["fontFamily","</style><script>alert(1)</script>"],["textColor","red;background:url(https://example.com)"],["background","#fff;display:none"],["width","600;position:absolute"],["width","9999"]]) {
for (const [key, value] of [
["fontFamily", "Arial;position:fixed"],
["fontFamily", "</style><script>alert(1)</script>"],
["textColor", "red;background:url(https://example.com)"],
["background", "#fff;display:none"],
["width", "600;position:absolute"],
["width", "9999"],
]) {
const draft = structuredClone(document);
draft.root.props[key!] = value!;
const rendered = await renderEmail(draft, {amp:true});
const rendered = await renderEmail(draft, { amp: true });
expect(rendered.ok).toBe(false);
if (!rendered.ok) expect(rendered.errors.some(error => error.code === "email.brand")).toBe(true);
if (!rendered.ok)
expect(rendered.errors.some((error) => error.code === "email.brand")).toBe(true);
}
});
test("responsive stacking begins below the desktop email width", async () => {
@@ -184,9 +272,22 @@ describe("email renderer", () => {
});
test("countdown URLs are derived for HTML AMP and MJML without mutating the document", async () => {
const draft = structuredClone(document);
draft.root.slots.content[0]!.slots.content = [{id:"timer",type:"content.countdown",version:1,props:{label:"Offer ends",deadline:"2026-10-01T00:00:00Z",fallback:"Offer ended"},styles:{},slots:{}}];
draft.root.slots.content[0]!.slots.content = [
{
id: "timer",
type: "content.countdown",
version: 1,
props: { label: "Offer ends", deadline: "2026-10-01T00:00:00Z", fallback: "Offer ended" },
styles: {},
slots: {},
},
];
const before = JSON.stringify(draft);
const result = await renderEmail(draft, {amp:true,mjml:true,countdownImageUrl:"https://email.example.com/api/countdown"});
const result = await renderEmail(draft, {
amp: true,
mjml: true,
countdownImageUrl: "https://email.example.com/api/countdown",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const image = "https://email.example.com/api/countdown?deadline=1790812800000";
@@ -194,7 +295,7 @@ describe("email renderer", () => {
expect(result.value.parts.amp?.content).toContain(image);
expect(result.value.exports?.mjml).toContain(image);
expect(JSON.stringify(draft)).toBe(before);
expect((await renderEmail(draft, {countdownImageUrl:"javascript:alert(1)"})).ok).toBe(false);
expect((await renderEmail(draft, { countdownImageUrl: "javascript:alert(1)" })).ok).toBe(false);
});
test("content inherits the selected brand font instead of overriding it", async () => {
const branded = structuredClone(document);
@@ -214,9 +315,13 @@ describe("email renderer", () => {
const tree = parse(rendered.value.parts.html.content);
const ancestry = new Map<string, string[]>();
const walk = (node: DefaultTreeAdapterMap["node"], parents: string[]) => {
const id = "attrs" in node ? node.attrs.find(attr => attr.name === "data-block-id")?.value : undefined;
const id =
"attrs" in node
? node.attrs.find((attr) => attr.name === "data-block-id")?.value
: undefined;
if (id) ancestry.set(id, parents);
if ("childNodes" in node) for (const child of node.childNodes) walk(child, id ? [...parents, id] : parents);
if ("childNodes" in node)
for (const child of node.childNodes) walk(child, id ? [...parents, id] : parents);
};
walk(tree, []);
expect(ancestry.get("heading")).toEqual(["root", "section"]);
@@ -3,10 +3,37 @@ import { renderEmail } from "../src/index.ts";
test("explicit heading sizes are not multiplied by browser heading defaults", async () => {
for (const size of [undefined, "36px", "expression(1)"]) {
const result = await renderEmail({schemaVersion:1,kind:"email",meta:{subject:"Typography",lang:"en"},theme:{tokens:{}},root:{id:"root",type:"layout.email-document",version:1,props:{width:"600"},styles:{},slots:{content:[{id:"heading",type:"content.heading",version:1,props:{text:"Design that works",level:"1"},styles:size?{fontSize:{base:size}}:{},slots:{}}]}}}, {amp:false,mjml:false});
const result = await renderEmail(
{
schemaVersion: 1,
kind: "email",
meta: { subject: "Typography", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "heading",
type: "content.heading",
version: 1,
props: { text: "Design that works", level: "1" },
styles: size ? { fontSize: { base: size } } : {},
slots: {},
},
],
},
},
},
{ amp: false, mjml: false },
);
expect(result.ok).toBe(true);
if (!result.ok) continue;
const html=result.value.parts.html.content;
const html = result.value.parts.html.content;
expect(html.includes("font-size:inherit;line-height:1.2;")).toBe(size === "36px");
expect(html).not.toContain("expression(");
}
@@ -2,7 +2,37 @@ import { expect, test } from "bun:test";
import type { BlockDocument, BlockNode } from "@wrnexus/blocks";
import { renderEmail, importMjml } from "../src/index.ts";
const documentFor = (decorative: boolean): BlockDocument => ({ schemaVersion: 1, kind: "email", meta: { subject: "Images" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: { content: [{ id: "image", type: "content.image", version: 1, props: { src: "https://example.com/image.png", alt: "Accessible & descriptive", width: "320", height: "180", decorative }, styles: {}, slots: {} }] } } });
const documentFor = (decorative: boolean): BlockDocument => ({
schemaVersion: 1,
kind: "email",
meta: { subject: "Images" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "image",
type: "content.image",
version: 1,
props: {
src: "https://example.com/image.png",
alt: "Accessible & descriptive",
width: "320",
height: "180",
decorative,
},
styles: {},
slots: {},
},
],
},
},
});
test("decorative image descriptions stay omitted across HTML text and MJML", async () => {
const rendered = await renderEmail(documentFor(true), { mjml: true });
@@ -23,7 +53,8 @@ test("meaningful image alt and explicit dimensions survive MJML round trip", asy
let id = 0;
const imported = importMjml(rendered.value.exports!.mjml!, { id: () => `n${++id}` });
if (!imported.ok) throw new Error("Import failed");
const find = (node: BlockNode): BlockNode | undefined => node.type === "content.image" ? node : Object.values(node.slots).flat().map(find).find(Boolean);
const find = (node: BlockNode): BlockNode | undefined =>
node.type === "content.image" ? node : Object.values(node.slots).flat().map(find).find(Boolean);
expect(find(imported.value.root)!.props.width).toBe("320");
expect(find(imported.value.root)!.props.height).toBe("180");
expect(find(imported.value.root)!.props.alt).toBe("Accessible & descriptive");
@@ -115,12 +115,23 @@ test("marketing image dimensions reject invalid or injected values", async () =>
});
test("video exports preserve thumbnail proportions, safe destination and accessible text", async () => {
const draft = document("content.video", { title: "Watch & learn", href: "https://example.com/watch?a=1&b=2", thumbnail: "https://example.com/poster.png", alt: 'Demo & "preview"', width: "360", height: "240" });
const draft = document("content.video", {
title: "Watch & learn",
href: "https://example.com/watch?a=1&b=2",
thumbnail: "https://example.com/poster.png",
alt: 'Demo & "preview"',
width: "360",
height: "240",
});
const before = JSON.stringify(draft);
const result = await renderEmail(draft, { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
for (const output of [result.value.parts.html.content, result.value.parts.amp?.content, result.value.exports?.mjml]) {
for (const output of [
result.value.parts.html.content,
result.value.parts.amp?.content,
result.value.exports?.mjml,
]) {
expect(output).toContain('href="https://example.com/watch?a=1&amp;b=2"');
expect(output).toContain('src="https://example.com/poster.png"');
expect(output).toContain('alt="Demo &amp; &quot;preview&quot;"');
@@ -128,29 +139,46 @@ test("video exports preserve thumbnail proportions, safe destination and accessi
expect(result.value.parts.html.content).toContain('width="360" height="240"');
expect(result.value.parts.amp?.content).toContain('width="360" height="240" layout="responsive"');
expect(result.value.exports?.mjml).toContain('width="360px" height="240px"');
expect(result.value.parts.text.content).toContain("Watch & learn: https://example.com/watch?a=1&b=2");
expect(result.value.parts.text.content).toContain(
"Watch & learn: https://example.com/watch?a=1&b=2",
);
expect(result.value.parts.amp?.validation.valid).toBe(true);
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
expect(JSON.stringify(draft)).toBe(before);
});
test("social exports include only configured networks and retain safe links in plain text", async () => {
const props = { label: "Follow & connect", facebook: "https://example.com/facebook?a=1&b=2", linkedin: "https://example.com/linkedin", instagram: "", x: "" };
const props = {
label: "Follow & connect",
facebook: "https://example.com/facebook?a=1&b=2",
linkedin: "https://example.com/linkedin",
instagram: "",
x: "",
};
const result = await renderEmail(document("content.social", props), { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
for (const output of [result.value.parts.html.content, result.value.parts.amp?.content, result.value.exports?.mjml]) {
for (const output of [
result.value.parts.html.content,
result.value.parts.amp?.content,
result.value.exports?.mjml,
]) {
expect(output).toContain("Follow &amp; connect");
expect(output).toContain('href="https://example.com/facebook?a=1&amp;b=2"');
expect(output).toContain('href="https://example.com/linkedin"');
expect(output).not.toContain(">Instagram</a>");
expect(output).not.toContain(">X</a>");
}
expect(result.value.parts.text.content).toContain("Facebook: https://example.com/facebook?a=1&b=2");
expect(result.value.parts.text.content).toContain(
"Facebook: https://example.com/facebook?a=1&b=2",
);
expect(result.value.parts.text.content).toContain("LinkedIn: https://example.com/linkedin");
expect(result.value.parts.amp?.validation.valid).toBe(true);
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
expect((await renderEmail(document("content.social", { ...props, facebook: "javascript:alert(1)" }))).ok).toBe(false);
expect(
(await renderEmail(document("content.social", { ...props, facebook: "javascript:alert(1)" })))
.ok,
).toBe(false);
});
test("basic images, video thumbnails and spacers validate dimensions before rendering", async () => {
@@ -7,18 +7,50 @@ const compile = createRequire(import.meta.url)("mjml");
test("MJML preserves document metadata and global typography in compiled HTML", async () => {
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: 'Brand & "News" <today>', preheader: 'Preview <safe> & useful', lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600", fontFamily: "Georgia, serif", textColor: "#123456", linkColor: "#a12345" }, styles: {}, slots: {
content: [{ id: "text", type: "content.text", version: 1, props: { text: "Brand text" }, styles: {}, slots: {} }, { id: "button", type: "content.button", version: 1, props: { label: "Brand action", href: "https://example.com" }, styles: {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: 'Brand & "News" <today>', preheader: "Preview <safe> & useful", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {
width: "600",
fontFamily: "Georgia, serif",
textColor: "#123456",
linkColor: "#a12345",
},
styles: {},
slots: {
content: [
{
id: "text",
type: "content.text",
version: 1,
props: { text: "Brand text" },
styles: {},
slots: {},
},
{
id: "button",
type: "content.button",
version: 1,
props: { label: "Brand action", href: "https://example.com" },
styles: {},
slots: {},
},
],
},
},
};
const before = structuredClone(document);
const result = await renderEmail(document, { mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
const source = result.value.exports!.mjml!;
expect(source).toContain('<mj-title>Brand &amp; &quot;News&quot; &lt;today&gt;</mj-title>');
expect(source).toContain('<mj-preview>Preview &lt;safe&gt; &amp; useful</mj-preview>');
expect(source).toContain("<mj-title>Brand &amp; &quot;News&quot; &lt;today&gt;</mj-title>");
expect(source).toContain("<mj-preview>Preview &lt;safe&gt; &amp; useful</mj-preview>");
expect(source).toContain('<mj-all font-family="Georgia, serif" />');
const compiled = await compile(source, { validationLevel: "strict", minify: false });
expect(compiled.errors).toEqual([]);
@@ -46,10 +78,15 @@ test("MJML header import rejects unsupported globals and unsafe typography", ()
'<mj-attributes><mj-all padding="20px" /></mj-attributes>',
'<mj-attributes><mj-all font-family="Arial;position:fixed" /></mj-attributes>',
'<mj-attributes><mj-text font-size="20px" /></mj-attributes>',
'<mj-style>.test{color:red}</mj-style>',
"<mj-style>.test{color:red}</mj-style>",
'<mj-breakpoint width="900px" />',
]) {
let id = 0;
expect(importMjml(`<mjml><mj-head>${header}</mj-head><mj-body><mj-section><mj-column><mj-text>Text</mj-text></mj-column></mj-section></mj-body></mjml>`, { id: () => `n${++id}` }).ok).toBe(false);
expect(
importMjml(
`<mjml><mj-head>${header}</mj-head><mj-body><mj-section><mj-column><mj-text>Text</mj-text></mj-column></mj-section></mj-body></mjml>`,
{ id: () => `n${++id}` },
).ok,
).toBe(false);
}
});
@@ -2,21 +2,39 @@ import { expect, test } from "bun:test";
import type { BlockNode } from "@wrnexus/blocks";
import { importMjml, renderEmail } from "../src/index.ts";
const source = (attributes: string) => `<mjml><mj-body><mj-section><mj-column><mj-button href="https://example.com/?a=1&amp;b=2" ${attributes}>Buy &amp; save &#33;</mj-button></mj-column></mj-section></mj-body></mjml>`;
const findButton = (node: BlockNode): BlockNode | undefined => node.type === "content.button" ? node : Object.values(node.slots).flat().map(findButton).find(Boolean);
const source = (attributes: string) =>
`<mjml><mj-body><mj-section><mj-column><mj-button href="https://example.com/?a=1&amp;b=2" ${attributes}>Buy &amp; save &#33;</mj-button></mj-column></mj-section></mj-body></mjml>`;
const findButton = (node: BlockNode): BlockNode | undefined =>
node.type === "content.button"
? node
: Object.values(node.slots).flat().map(findButton).find(Boolean);
test("imported button preserves supported appearance and escaped label/link across export", async () => {
let id = 0;
const imported = importMjml(source('align="right" background-color="#123456" color="#abcdef" font-size="22px" font-weight="400" border-radius="12px"'), { id: () => `n${++id}` });
const imported = importMjml(
source(
'align="right" background-color="#123456" color="#abcdef" font-size="22px" font-weight="400" border-radius="12px"',
),
{ id: () => `n${++id}` },
);
expect(imported.ok).toBe(true);
if (!imported.ok) return;
const button = findButton(imported.value.root)!;
expect(button.props).toEqual({ label: "Buy & save !", href: "https://example.com/?a=1&b=2" });
expect(button.styles).toEqual({ textAlign: { base: "right" }, backgroundColor: { base: "#123456" }, color: { base: "#abcdef" }, fontSize: { base: "22px" }, fontWeight: { base: "400" }, borderRadius: { base: "12px" } });
expect(button.styles).toEqual({
textAlign: { base: "right" },
backgroundColor: { base: "#123456" },
color: { base: "#abcdef" },
fontSize: { base: "22px" },
fontWeight: { base: "400" },
borderRadius: { base: "12px" },
});
const rendered = await renderEmail(imported.value, { mjml: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
expect(rendered.value.parts.html.content).toContain("font-size:22px;font-weight:400;border-radius:12px");
expect(rendered.value.parts.html.content).toContain(
"font-size:22px;font-weight:400;border-radius:12px",
);
expect(rendered.value.parts.text.content).toContain("Buy & save !");
const again = importMjml(rendered.value.exports!.mjml!, { id: () => `n${++id}` });
expect(again.ok).toBe(true);
@@ -28,10 +46,17 @@ test("imported button preserves supported appearance and escaped label/link acro
});
test("unsupported or unsafe button attributes produce explicit diagnostics", () => {
for (const attributes of ['color="red;position:fixed"', 'align="justify"', 'font-size="expression(1)"', 'onclick="alert(1)"', 'padding="20px"']) {
for (const attributes of [
'color="red;position:fixed"',
'align="justify"',
'font-size="expression(1)"',
'onclick="alert(1)"',
'padding="20px"',
]) {
let id = 0;
const result = importMjml(source(attributes), { id: () => `n${++id}` });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.errors.some(error => error.code === "mjml.button-attribute")).toBe(true);
if (!result.ok)
expect(result.errors.some((error) => error.code === "mjml.button-attribute")).toBe(true);
}
});
@@ -3,18 +3,40 @@ import { importMjml, renderEmail } from "../src/index.ts";
const parse = (columns: string) => {
let id = 0;
return importMjml(`<mjml><mj-body><mj-section>${columns}</mj-section></mj-body></mjml>`, { subject: "Imported", id: () => `n${++id}` });
return importMjml(`<mjml><mj-body><mj-section>${columns}</mj-section></mj-body></mjml>`, {
subject: "Imported",
id: () => `n${++id}`,
});
};
test("imported columns form one native row with preserved order and exact width totals", async () => {
for (const widths of [["", ""], ["33%", ""], ["", "", ""], ["25%", "75%"]]) {
const result = parse(widths.map((width, index) => `<mj-column${width ? ` width="${width}"` : ""}><mj-text>Column ${index}</mj-text></mj-column>`).join(""));
for (const widths of [
["", ""],
["33%", ""],
["", "", ""],
["25%", "75%"],
]) {
const result = parse(
widths
.map(
(width, index) =>
`<mj-column${width ? ` width="${width}"` : ""}><mj-text>Column ${index}</mj-text></mj-column>`,
)
.join(""),
);
expect(result.ok).toBe(true);
if (!result.ok) continue;
const row = result.value.root.slots.content[0]!.slots.content[0]!;
expect(row.type).toBe("layout.columns");
expect(row.slots.columns.map(column => column.slots.content[0]!.props.text)).toEqual(widths.map((_, index) => `Column ${index}`));
expect(row.slots.columns.reduce((sum, column) => sum + Number.parseFloat(String(column.props.width)), 0)).toBeCloseTo(100, 8);
expect(row.slots.columns.map((column) => column.slots.content[0]!.props.text)).toEqual(
widths.map((_, index) => `Column ${index}`),
);
expect(
row.slots.columns.reduce(
(sum, column) => sum + Number.parseFloat(String(column.props.width)),
0,
),
).toBeCloseTo(100, 8);
const rendered = await renderEmail(result.value, { mjml: true });
expect(rendered.ok).toBe(true);
if (rendered.ok) expect(rendered.value.exports?.mjml).toContain("<mj-column");
@@ -27,12 +49,23 @@ test("import rejects invalid URLs, dimensions, widths, and native slot limits",
'<mj-column><mj-image src="https://example.com/x.png" width="99999px" /></mj-column>',
'<mj-column width="75%"></mj-column><mj-column width="75%"></mj-column>',
'<mj-column width="400px"></mj-column>',
Array(5).fill('<mj-column><mj-text>X</mj-text></mj-column>').join(""),
]) expect(parse(input).ok).toBe(false);
Array(5).fill("<mj-column><mj-text>X</mj-text></mj-column>").join(""),
])
expect(parse(input).ok).toBe(false);
});
test("import enforces depth limits and rejects repeated instance IDs", () => {
const nested = '<mjml><mj-body>' + '<mj-wrapper>'.repeat(100) + '<mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section>' + '</mj-wrapper>'.repeat(100) + '</mj-body></mjml>';
const nested =
"<mjml><mj-body>" +
"<mj-wrapper>".repeat(100) +
"<mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section>" +
"</mj-wrapper>".repeat(100) +
"</mj-body></mjml>";
expect(importMjml(nested, { subject: "Depth", id: () => "id" }).ok).toBe(false);
expect(importMjml('<mjml><mj-body><mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section></mj-body></mjml>', { subject: "IDs", id: () => "same" }).ok).toBe(false);
expect(
importMjml(
"<mjml><mj-body><mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section></mj-body></mjml>",
{ subject: "IDs", id: () => "same" },
).ok,
).toBe(false);
});
@@ -7,9 +7,28 @@ test("every designed preset renders natively without remote placeholder assets",
for (const preset of emailPresets) {
let id = 0;
const section = createSectionPreset(preset.id, () => `preset-${++id}`);
const document: BlockDocument = {schemaVersion:1,kind:"email",meta:{subject:"Preset QA"},theme:{tokens:{}},root:{id:"root",type:"layout.email-document",version:1,props:{width:"600"},styles:{},slots:{content:[section]}}};
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Preset QA" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: { content: [section] },
},
};
const before = JSON.stringify(document);
const result = await renderEmailPreview(document, {variables:{recipientName:"Alex",organizationAddress:"Company address",unsubscribeUrl:"https://example.com/unsubscribe"}});
const result = await renderEmailPreview(document, {
variables: {
recipientName: "Alex",
organizationAddress: "Company address",
unsubscribeUrl: "https://example.com/unsubscribe",
},
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.html).not.toContain("placehold.co");
+15 -5
View File
@@ -2,9 +2,19 @@ import { expect, test } from "bun:test";
import { renderRichText, richTextSchema } from "../src/rich-text.ts";
test("semantic text is escaped, bounded, and rejects arbitrary markup properties", () => {
expect(renderRichText({text:"<hello>\nworld",richText:[{text:"<hello>",bold:true},{text:"\nworld",italic:true,underline:true}]})).toBe("<strong>&lt;hello&gt;</strong><em><u><br />world</u></em>");
expect(richTextSchema.parse([{text:"hello",html:"<script>"}]).ok).toBe(false);
expect(richTextSchema.parse([{text:"hello",bold:"yes"}]).ok).toBe(false);
expect(richTextSchema.parse([{text:"a".repeat(200001)}]).ok).toBe(false);
expect(renderRichText({text:"Changed",richText:[{text:"Old",bold:true}]})).toBe("Changed");
expect(
renderRichText({
text: "<hello>\nworld",
richText: [
{ text: "<hello>", bold: true },
{ text: "\nworld", italic: true, underline: true },
],
}),
).toBe("<strong>&lt;hello&gt;</strong><em><u><br />world</u></em>");
expect(richTextSchema.parse([{ text: "hello", html: "<script>" }]).ok).toBe(false);
expect(richTextSchema.parse([{ text: "hello", bold: "yes" }]).ok).toBe(false);
expect(richTextSchema.parse([{ text: "a".repeat(200001) }]).ok).toBe(false);
expect(renderRichText({ text: "Changed", richText: [{ text: "Old", bold: true }] })).toBe(
"Changed",
);
});
+91 -5
View File
@@ -2,22 +2,108 @@ import { expect, test } from "bun:test";
import type { BlockDocument, BlockNode } from "@wrnexus/blocks";
import { renderEmail, validateMjml } from "../src/index.ts";
const text = (id: string): BlockNode => ({ id, type: "content.text", version: 1, props: { text: id }, styles: {}, slots: {} });
const columns = (id: string): BlockNode => ({ id, type: "layout.columns", version: 1, props: {}, styles: {}, slots: { columns: [0, 1].map(index => ({ id: `${id}-${index}`, type: "layout.column", version: 1, props: { width: "50%" }, styles: {}, slots: { content: [text(`${id}-text-${index}`)] } })) } });
const text = (id: string): BlockNode => ({
id,
type: "content.text",
version: 1,
props: { text: id },
styles: {},
slots: {},
});
const columns = (id: string): BlockNode => ({
id,
type: "layout.columns",
version: 1,
props: {},
styles: {},
slots: {
columns: [0, 1].map((index) => ({
id: `${id}-${index}`,
type: "layout.column",
version: 1,
props: { width: "50%" },
styles: {},
slots: { content: [text(`${id}-text-${index}`)] },
})),
},
});
test("invalid nested MJML is diagnosed and omitted while HTML and text remain usable", async () => {
const document: BlockDocument = { schemaVersion: 1, kind: "email", meta: { subject: "Nested", lang: "en" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: {}, styles: {}, slots: { content: [{ id: "outer", type: "layout.section", version: 1, props: {}, styles: {}, slots: { content: [{ id: "inner", type: "layout.section", version: 1, props: {}, styles: {}, slots: { content: [text("Retained nested content")] } }] } }] } } };
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Nested", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {},
styles: {},
slots: {
content: [
{
id: "outer",
type: "layout.section",
version: 1,
props: {},
styles: {},
slots: {
content: [
{
id: "inner",
type: "layout.section",
version: 1,
props: {},
styles: {},
slots: { content: [text("Retained nested content")] },
},
],
},
},
],
},
},
};
const rendered = await renderEmail(document, { mjml: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
expect(rendered.value.exports?.mjml).toBeUndefined();
expect(rendered.value.warnings.some(warning => warning.code === "mjml.validation")).toBe(true);
expect(rendered.value.warnings.some((warning) => warning.code === "mjml.validation")).toBe(true);
expect(rendered.value.parts.html.content).toContain("Retained nested content");
expect(rendered.value.parts.text.content).toContain("Retained nested content");
});
test("root content and separate column rows produce valid ordered MJML without changing the document", async () => {
const document: BlockDocument = { schemaVersion: 1, kind: "email", meta: { subject: "Root blocks", lang: "en" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: {}, styles: {}, slots: { content: [text("intro"), columns("first"), columns("second"), { id: "cta", type: "content.button", version: 1, props: { label: "Act", href: "https://example.com" }, styles: {}, slots: {} }, text("end")] } } };
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Root blocks", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {},
styles: {},
slots: {
content: [
text("intro"),
columns("first"),
columns("second"),
{
id: "cta",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: {},
slots: {},
},
text("end"),
],
},
},
};
const before = structuredClone(document);
const rendered = await renderEmail(document, { mjml: true });
expect(rendered.ok).toBe(true);
@@ -2,20 +2,51 @@ import { expect, test } from "bun:test";
import { emailStyleValue, validateEmailStyleValue } from "../src/style-values.ts";
test("base style syntax rejects ignored or injected values and accepts supported units", () => {
for (const [key, value] of [["padding","12"],["padding","1px 2px 3px 4px 5px"],["color","#12345"],["fontWeight","heavy"],["fontSize","12px;color:red"],["position","fixed"],["constructor","x"]]) {
for (const [key, value] of [
["padding", "12"],
["padding", "1px 2px 3px 4px 5px"],
["color", "#12345"],
["fontWeight", "heavy"],
["fontSize", "12px;color:red"],
["position", "fixed"],
["constructor", "x"],
]) {
expect(emailStyleValue(key!, value)).toBe("");
expect(() => validateEmailStyleValue(key!, value!)).toThrow();
}
for (const [key, value] of [["padding","0 12px"],["margin","1rem 2%"],["color","#1234"],["fontWeight","700"],["fontSize","16px"],["borderRadius","0"],["textAlign","end"]]) {
for (const [key, value] of [
["padding", "0 12px"],
["margin", "1rem 2%"],
["color", "#1234"],
["fontWeight", "700"],
["fontSize", "16px"],
["borderRadius", "0"],
["textAlign", "end"],
]) {
expect(emailStyleValue(key!, value)).toBe(value!);
expect(() => validateEmailStyleValue(key!, value!)).not.toThrow();
}
});
test("RGB functions require correct channel counts, units and bounded components", () => {
for (const value of ["rgb(1)", "rgb(1,2,3,4)", "rgba(1,2,3)", "rgb(256,0,0)", "rgb(100%,0,0)", "rgba(1,2,3,1.1)", "rgb(1..2,2,3)", "rgba(0,0,0,101%)"])
for (const value of [
"rgb(1)",
"rgb(1,2,3,4)",
"rgba(1,2,3)",
"rgb(256,0,0)",
"rgb(100%,0,0)",
"rgba(1,2,3,1.1)",
"rgb(1..2,2,3)",
"rgba(0,0,0,101%)",
])
expect(emailStyleValue("color", value)).toBe("");
for (const value of ["rgb(255, 0, 12)", "rgb(100%, 0%, 50%)", "rgba(0,0,0,.5)", "rgba(0,0,0,50%)", "transparent"])
for (const value of [
"rgb(255, 0, 12)",
"rgb(100%, 0%, 50%)",
"rgba(0,0,0,.5)",
"rgba(0,0,0,50%)",
"transparent",
])
expect(emailStyleValue("backgroundColor", value)).toBe(value);
expect(emailStyleValue("padding", "0 4000px")).toBe("0 4000px");
expect(emailStyleValue("padding", "0 4001px")).toBe("");
@@ -5,10 +5,40 @@ import { renderEmail } from "../src/index.ts";
const compile = createRequire(import.meta.url)("mjml");
test("survey MJML button inherits brand color and preserves safe text fallback", async () => {
const document: BlockDocument = { schemaVersion: 1, kind: "email", meta: { subject: "Survey" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600", linkColor: "#a12345" }, styles: {}, slots: { content: [{ id: "survey", type: "content.survey", version: 1, props: { question: "How was your visit?", buttonLabel: "Answer & share", href: "https://example.com/survey" }, styles: {}, slots: {} }] } } };
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Survey" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600", linkColor: "#a12345" },
styles: {},
slots: {
content: [
{
id: "survey",
type: "content.survey",
version: 1,
props: {
question: "How was your visit?",
buttonLabel: "Answer & share",
href: "https://example.com/survey",
},
styles: {},
slots: {},
},
],
},
},
};
const result = await renderEmail(document, { mjml: true });
if (!result.ok) throw new Error("Render failed");
expect(result.value.parts.text.content).toContain("How was your visit?\nAnswer & share: https://example.com/survey");
expect(result.value.parts.text.content).toContain(
"How was your visit?\nAnswer & share: https://example.com/survey",
);
const compiled = await compile(result.value.exports!.mjml!, { validationLevel: "strict" });
expect(compiled.errors).toEqual([]);
expect(compiled.html).toContain("background:#a12345");
@@ -3,16 +3,38 @@ import { resolveDocumentVariables, type BlockDocument } from "@wrnexus/blocks";
import { renderEmail } from "../src/index.ts";
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Hi {{recipientName|friend}}", lang: "en" },
schemaVersion: 1,
kind: "email",
meta: { subject: "Hi {{recipientName|friend}}", lang: "en" },
theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: {}, styles: {}, slots: {
content: [{ id: "text", type: "content.text", version: 1, props: { text: "Hello {{recipientName|friend}}" }, styles: {}, slots: {} }],
} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {},
styles: {},
slots: {
content: [
{
id: "text",
type: "content.text",
version: 1,
props: { text: "Hello {{recipientName|friend}}" },
styles: {},
slots: {},
},
],
},
},
};
test("template rendering preserves fallback tokens rather than baking in sample or fallback values", async () => {
const before = structuredClone(document);
const rendered = await renderEmail(document, { preserveVariables: true, mjml: true, variables: { recipientName: "Preview only" } });
const rendered = await renderEmail(document, {
preserveVariables: true,
mjml: true,
variables: { recipientName: "Preview only" },
});
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
expect(rendered.value.subject).toBe("Hi {{recipientName|friend}}");
@@ -20,13 +42,25 @@ test("template rendering preserves fallback tokens rather than baking in sample
expect(rendered.value.parts.text.content).toContain("Hello {{recipientName|friend}}");
expect(rendered.value.exports?.mjml).toContain("Hello {{recipientName|friend}}");
expect(document).toEqual(before);
const resolved = await renderEmail(document, { variables: { recipientName: "Ada" }, requireVariables: true });
const resolved = await renderEmail(document, {
variables: { recipientName: "Ada" },
requireVariables: true,
});
expect(resolved.ok && resolved.value.subject).toBe("Hi Ada");
});
test("preservation still validates token allowlists and cannot masquerade as resolved delivery", () => {
const unknown = structuredClone(document);
unknown.meta.subject = "{{unregistered}}";
expect(resolveDocumentVariables(unknown, { recipientName: "string" }, {}, { preserveTokens: true }).ok).toBe(false);
expect(resolveDocumentVariables(document, { recipientName: "string" }, {}, { preserveTokens: true, requireValues: true }).ok).toBe(false);
expect(
resolveDocumentVariables(unknown, { recipientName: "string" }, {}, { preserveTokens: true }).ok,
).toBe(false);
expect(
resolveDocumentVariables(
document,
{ recipientName: "string" },
{},
{ preserveTokens: true, requireValues: true },
).ok,
).toBe(false);
});