@marlinjai/email-editor-core 0.2.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.
@@ -0,0 +1,1966 @@
1
+ import {
2
+ CURRENT_TEMPLATE_VERSION,
3
+ allSections,
4
+ buildGradientCSS,
5
+ isLeafBlockType,
6
+ isTemplateMigrationError,
7
+ isWrapper,
8
+ migrateTemplate
9
+ } from "./chunk-2ZL7A2I6.mjs";
10
+
11
+ // src/compiler/MJMLCompiler.ts
12
+ import mjml2html from "mjml";
13
+
14
+ // src/compiler/blockToRawHtml.ts
15
+ function escapeAttr(s) {
16
+ return s.replace(/"/g, "&quot;").replace(/</g, "&lt;");
17
+ }
18
+ function spacingToCss(p) {
19
+ if (!p) return "";
20
+ const t = p.top ?? "0", r = p.right ?? "0", b = p.bottom ?? "0", l = p.left ?? "0";
21
+ return `padding:${t} ${r} ${b} ${l};`;
22
+ }
23
+ function textToHtml(b) {
24
+ const styles = [];
25
+ if (b.color) styles.push(`color:${b.color}`);
26
+ if (b.fontSize) styles.push(`font-size:${b.fontSize}`);
27
+ if (b.fontFamily) styles.push(`font-family:${b.fontFamily}`);
28
+ if (b.lineHeight) styles.push(`line-height:${b.lineHeight}`);
29
+ if (b.align) styles.push(`text-align:${b.align}`);
30
+ styles.push("margin:0");
31
+ const padding = spacingToCss(b.padding);
32
+ return `<div style="${styles.join(";")};${padding}">${b.content}</div>`;
33
+ }
34
+ function imageToHtml(b) {
35
+ const align = b.align ?? "center";
36
+ const wrap = `style="text-align:${align};${spacingToCss(b.padding)}"`;
37
+ const widthAttr = b.width ? ` width="${escapeAttr(b.width)}"` : "";
38
+ const heightAttr = b.height ? ` height="${escapeAttr(b.height)}"` : "";
39
+ const radius = b.borderRadius ? `border-radius:${b.borderRadius};` : "";
40
+ const img = `<img src="${escapeAttr(b.src)}" alt="${escapeAttr(b.alt ?? "")}"${widthAttr}${heightAttr} style="display:block;max-width:100%;${radius}border:0;outline:none;text-decoration:none;" />`;
41
+ const inner = b.href ? `<a href="${escapeAttr(b.href)}" target="_blank" rel="noopener" style="text-decoration:none;">${img}</a>` : img;
42
+ return `<div ${wrap}>${inner}</div>`;
43
+ }
44
+ function buttonToHtml(b) {
45
+ const align = b.align ?? "center";
46
+ const bg = b.backgroundColor ?? "#000000";
47
+ const fg = b.color ?? "#ffffff";
48
+ const radius = b.borderRadius ?? "3px";
49
+ const innerPadding = b.innerPadding ?? "10px 25px";
50
+ const border = b.border ? `border:${b.border};` : "";
51
+ return `<div style="text-align:${align};${spacingToCss(b.padding)}">
52
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="border-collapse:separate;line-height:100%;display:inline-block;">
53
+ <tr>
54
+ <td align="center" valign="middle" role="presentation" style="background-color:${bg};border-radius:${radius};${border}padding:${innerPadding};">
55
+ <a href="${escapeAttr(b.href)}" target="_blank" rel="noopener" style="display:inline-block;color:${fg};font-family:inherit;font-size:14px;font-weight:600;line-height:120%;text-decoration:none;text-transform:none;">${escapeAttr(b.label)}</a>
56
+ </td>
57
+ </tr>
58
+ </table>
59
+ </div>`;
60
+ }
61
+ function dividerToHtml(b) {
62
+ const color = b.borderColor ?? "#cccccc";
63
+ const w = b.borderWidth ?? "1px";
64
+ const style = b.borderStyle ?? "solid";
65
+ const width = b.width ?? "100%";
66
+ return `<div style="${spacingToCss(b.padding)}">
67
+ <div style="border-top:${w} ${style} ${color};width:${width};font-size:1px;line-height:1px;">&nbsp;</div>
68
+ </div>`;
69
+ }
70
+ function spacerToHtml(b) {
71
+ return `<div style="height:${b.height};line-height:${b.height};font-size:1px;">&nbsp;</div>`;
72
+ }
73
+ function socialToHtml(b) {
74
+ const items = (b.links ?? []).map((link) => {
75
+ const icon = link.icon ?? "";
76
+ return `<a href="${escapeAttr(link.url)}" target="_blank" rel="noopener" style="display:inline-block;margin:0 4px;">
77
+ <img src="${escapeAttr(icon)}" alt="${escapeAttr(link.platform)}" width="24" height="24" style="display:inline-block;border:0;" />
78
+ </a>`;
79
+ }).join("");
80
+ return `<div style="text-align:center;">${items}</div>`;
81
+ }
82
+ function blockToRawHtml(block) {
83
+ if (!isLeafBlockType(block.type)) {
84
+ throw new Error(`blockToRawHtml only handles leaf blocks; got "${block.type}"`);
85
+ }
86
+ switch (block.type) {
87
+ case "text" /* TEXT */:
88
+ return textToHtml(block);
89
+ case "image" /* IMAGE */:
90
+ return imageToHtml(block);
91
+ case "button" /* BUTTON */:
92
+ return buttonToHtml(block);
93
+ case "divider" /* DIVIDER */:
94
+ return dividerToHtml(block);
95
+ case "spacer" /* SPACER */:
96
+ return spacerToHtml(block);
97
+ case "social" /* SOCIAL */:
98
+ return socialToHtml(block);
99
+ default:
100
+ throw new Error(`Unhandled leaf block type: ${block.type}`);
101
+ }
102
+ }
103
+
104
+ // src/compiler/MJMLCompiler.ts
105
+ var DEFAULT_MJML_ATTRIBUTES = `
106
+ <mj-all font-family="Georgia, serif" />
107
+ <mj-text font-size="14px" line-height="1.6" />
108
+ `;
109
+ var EDITOR_DATA_ATTRIBUTE = {
110
+ social: "data-ee-social",
111
+ subColumns: "data-ee-subcols"
112
+ };
113
+ function encodeEditorData(value) {
114
+ return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
115
+ }
116
+ function finishAttributes(attrs, classes, extra) {
117
+ const out = [...attrs];
118
+ const taken = new Set(attrs.map((a) => a.slice(0, a.indexOf("="))));
119
+ const allClasses = [...classes];
120
+ if (extra) {
121
+ for (const [name, value] of Object.entries(extra)) {
122
+ if (name === "css-class") {
123
+ for (const c of value.replace(/"/g, "&quot;").split(/\s+/)) if (c && !allClasses.includes(c)) allClasses.push(c);
124
+ continue;
125
+ }
126
+ if (taken.has(name)) continue;
127
+ out.push(`${name}="${value.replace(/"/g, "&quot;")}"`);
128
+ }
129
+ }
130
+ if (allClasses.length > 0) out.push(`css-class="${allClasses.join(" ")}"`);
131
+ return out.join(" ");
132
+ }
133
+ function quoted(value) {
134
+ return value.replace(/"/g, "&quot;");
135
+ }
136
+ function spacingToString(spacing) {
137
+ if (!spacing) return "";
138
+ const { top, right, bottom, left } = spacing;
139
+ if (!top && !right && !bottom && !left) return "";
140
+ return [top || "0", right || "0", bottom || "0", left || "0"].join(" ");
141
+ }
142
+ var MJMLCompiler = class {
143
+ constructor() {
144
+ /**
145
+ * Set true while emitting a column with sub-columns. Causes generateHead
146
+ * to inject the responsive media query exactly once per template.
147
+ */
148
+ this.needsSubColumnStyles = false;
149
+ /**
150
+ * Platform brand colors for social icons
151
+ */
152
+ this.SOCIAL_COLORS = {
153
+ facebook: "#1877F2",
154
+ twitter: "#000000",
155
+ instagram: "#E4405F",
156
+ linkedin: "#0A66C2",
157
+ youtube: "#FF0000",
158
+ pinterest: "#BD081C",
159
+ github: "#181717"
160
+ };
161
+ }
162
+ /**
163
+ * Compile email template to MJML and HTML
164
+ */
165
+ compile(template, options = {}) {
166
+ try {
167
+ this.needsSubColumnStyles = false;
168
+ const mjml = this.templateToMJML(template);
169
+ const result = mjml2html(mjml, {
170
+ // Never resolve <mj-include>: its path is read from the server's disk,
171
+ // and a stored document (a Raw block's html) must not reach local files.
172
+ ignoreIncludes: true,
173
+ validationLevel: "soft",
174
+ minify: false,
175
+ ...options.webFonts === false ? { fonts: {} } : {}
176
+ });
177
+ return {
178
+ mjml,
179
+ html: result.html,
180
+ errors: result.errors.length > 0 ? result.errors.map((e) => e.formattedMessage) : void 0
181
+ };
182
+ } catch (error) {
183
+ return {
184
+ mjml: "",
185
+ html: "",
186
+ errors: [error instanceof Error ? error.message : "Unknown compilation error"]
187
+ };
188
+ }
189
+ }
190
+ /**
191
+ * The MJML markup for a document, without compiling it to HTML.
192
+ */
193
+ toMJML(template) {
194
+ this.needsSubColumnStyles = false;
195
+ return this.templateToMJML(template);
196
+ }
197
+ /**
198
+ * Convert template to MJML markup
199
+ */
200
+ templateToMJML(template) {
201
+ const { metadata, sections } = template;
202
+ const body = sections.map((item) => isWrapper(item) ? this.wrapperToMJML(item) : this.sectionToMJML(item)).join("\n");
203
+ const gradientCSS = this.collectGradientStyles(sections);
204
+ const head = this.generateHead(metadata, gradientCSS);
205
+ const bodyAttributes = finishAttributes([], [], metadata.mjmlHead?.bodyAttributes);
206
+ return `
207
+ <mjml>
208
+ ${head}
209
+ <mj-body${bodyAttributes ? ` ${bodyAttributes}` : ""}>
210
+ ${body}
211
+ </mj-body>
212
+ </mjml>
213
+ `.trim();
214
+ }
215
+ /**
216
+ * Generate MJML head section with all head components
217
+ * Supports: mj-title, mj-preview, mj-font, mj-breakpoint, mj-style
218
+ */
219
+ generateHead(metadata, gradientCSS) {
220
+ const parts = ["<mj-head>"];
221
+ if (metadata.title) {
222
+ parts.push(`<mj-title>${metadata.title}</mj-title>`);
223
+ }
224
+ if (metadata.previewText || metadata.subject) {
225
+ parts.push(`<mj-preview>${metadata.previewText || metadata.subject || ""}</mj-preview>`);
226
+ }
227
+ if (metadata.fonts && metadata.fonts.length > 0) {
228
+ for (const font of metadata.fonts) {
229
+ parts.push(`<mj-font name="${font.name}" href="${font.href}" />`);
230
+ }
231
+ }
232
+ if (metadata.breakpoint) {
233
+ parts.push(`<mj-breakpoint width="${metadata.breakpoint}" />`);
234
+ }
235
+ const mjmlHead = metadata.mjmlHead;
236
+ const attributes = mjmlHead?.attributes ?? DEFAULT_MJML_ATTRIBUTES;
237
+ if (attributes.trim()) parts.push(`<mj-attributes>${attributes}</mj-attributes>`);
238
+ if (mjmlHead?.headRaw) parts.push(mjmlHead.headRaw);
239
+ if (metadata.customCSS) {
240
+ parts.push(`<mj-style>${metadata.customCSS}</mj-style>`);
241
+ }
242
+ if (metadata.inlineCSS) {
243
+ parts.push(`<mj-style inline="inline">${metadata.inlineCSS}</mj-style>`);
244
+ }
245
+ if (gradientCSS) {
246
+ parts.push(`<mj-style>${gradientCSS}</mj-style>`);
247
+ }
248
+ if (this.needsSubColumnStyles) {
249
+ parts.push(`<mj-style>
250
+ @media only screen and (max-width:480px) {
251
+ table.ee-sub-cols td.ee-sub-col {
252
+ display: block !important;
253
+ width: 100% !important;
254
+ padding-bottom: 12px !important;
255
+ }
256
+ table.ee-sub-cols td.ee-sub-col:last-child {
257
+ padding-bottom: 0 !important;
258
+ }
259
+ }
260
+ </mj-style>`);
261
+ }
262
+ parts.push("</mj-head>");
263
+ return parts.join("\n");
264
+ }
265
+ /**
266
+ * Collect background-image CSS rules for all wrappers, sections and columns that have gradients.
267
+ * Returns a string of CSS rules to inject as a single mj-style block.
268
+ */
269
+ collectGradientStyles(items) {
270
+ const rules = [];
271
+ for (const item of items) {
272
+ if (isWrapper(item) && item.backgroundGradient) {
273
+ const css = buildGradientCSS(item.backgroundGradient);
274
+ if (css) rules.push(`.el-grad-${item.id} { background-image: ${css}; }`);
275
+ }
276
+ }
277
+ for (const section of allSections(items)) {
278
+ if (section.backgroundGradient) {
279
+ const css = buildGradientCSS(section.backgroundGradient);
280
+ if (css) {
281
+ rules.push(`.el-grad-${section.id} { background-image: ${css}; }`);
282
+ }
283
+ }
284
+ for (const column of section.columns) {
285
+ if (column.backgroundGradient) {
286
+ const css = buildGradientCSS(column.backgroundGradient);
287
+ if (css) {
288
+ rules.push(`.el-grad-${column.id} { background-image: ${css}; }`);
289
+ }
290
+ }
291
+ }
292
+ }
293
+ return rules.join("\n");
294
+ }
295
+ /**
296
+ * Convert a wrapper to an `<mj-wrapper>` around its sections. The wrapper's
297
+ * attributes are MJML's own for `mj-wrapper`; the sections inside follow
298
+ * MJML's rules there (a full-width section inside a full-width wrapper
299
+ * renders at standard width, which the inspector explains).
300
+ */
301
+ wrapperToMJML(wrapper) {
302
+ if (wrapper.hidden) return "";
303
+ const attrs = [];
304
+ const cssClasses = ["el-wrapper", `el-${wrapper.id}`];
305
+ this.pushBackground(attrs, cssClasses, wrapper);
306
+ if (wrapper.border) attrs.push(`border="${quoted(wrapper.border)}"`);
307
+ if (wrapper.borderTop) attrs.push(`border-top="${quoted(wrapper.borderTop)}"`);
308
+ if (wrapper.borderRight) attrs.push(`border-right="${quoted(wrapper.borderRight)}"`);
309
+ if (wrapper.borderBottom) attrs.push(`border-bottom="${quoted(wrapper.borderBottom)}"`);
310
+ if (wrapper.borderLeft) attrs.push(`border-left="${quoted(wrapper.borderLeft)}"`);
311
+ if (wrapper.borderRadius) attrs.push(`border-radius="${quoted(wrapper.borderRadius)}"`);
312
+ if (wrapper.fullWidth) attrs.push('full-width="full-width"');
313
+ const padding = spacingToString(wrapper.padding);
314
+ if (padding) attrs.push(`padding="${quoted(padding)}"`);
315
+ if (wrapper.gap) attrs.push(`gap="${quoted(wrapper.gap)}"`);
316
+ if (wrapper.textAlign) attrs.push(`text-align="${quoted(wrapper.textAlign)}"`);
317
+ for (const c of (wrapper.cssClass ?? "").split(/\s+/)) if (c && !cssClasses.includes(quoted(c))) cssClasses.push(quoted(c));
318
+ const sections = wrapper.sections.map((section) => this.sectionToMJML(section)).filter(Boolean).join("\n");
319
+ return `
320
+ <mj-wrapper ${finishAttributes(attrs, cssClasses, wrapper.extraAttributes)}>
321
+ ${sections}
322
+ </mj-wrapper>
323
+ `.trim();
324
+ }
325
+ /** Background attributes shared by sections and wrappers: a gradient (with its Outlook fallback colour), or colour and image. */
326
+ pushBackground(attrs, cssClasses, node) {
327
+ if (node.backgroundGradient) {
328
+ const fallbackColor = node.backgroundGradient.stops[0]?.color;
329
+ if (fallbackColor) attrs.push(`background-color="${quoted(fallbackColor)}"`);
330
+ cssClasses.push(`el-grad-${node.id}`);
331
+ return;
332
+ }
333
+ if (node.backgroundColor) attrs.push(`background-color="${quoted(node.backgroundColor)}"`);
334
+ if (node.backgroundImage) attrs.push(`background-url="${quoted(node.backgroundImage)}"`);
335
+ if (node.backgroundPosition) attrs.push(`background-position="${quoted(node.backgroundPosition)}"`);
336
+ if (node.backgroundRepeat) attrs.push(`background-repeat="${quoted(node.backgroundRepeat)}"`);
337
+ if (node.backgroundSize) attrs.push(`background-size="${quoted(node.backgroundSize)}"`);
338
+ }
339
+ /**
340
+ * Convert section to MJML
341
+ * Supports background images, full-width, and mj-group for non-stacking columns
342
+ */
343
+ sectionToMJML(section) {
344
+ if (section.hidden) return "";
345
+ if (section.bodyRaw) {
346
+ const blocks = section.columns.flatMap((c) => c.blocks).filter((b) => !b.hidden);
347
+ if (blocks.every((b) => b.type === "raw") && section.columns.every((c) => !c.subColumns?.length)) {
348
+ return blocks.map((b) => `<mj-raw>${b.html}</mj-raw>`).join("\n");
349
+ }
350
+ }
351
+ const attrs = [];
352
+ const cssClasses = ["el-section", `el-${section.id}`];
353
+ this.pushBackground(attrs, cssClasses, section);
354
+ if (section.fullWidth) {
355
+ attrs.push('full-width="full-width"');
356
+ }
357
+ if (section.padding) {
358
+ const padding = spacingToString(section.padding);
359
+ if (padding) attrs.push(`padding="${padding}"`);
360
+ }
361
+ const columns = section.columns.map((col) => this.columnToMJML(col)).join("\n");
362
+ const sectionAttrs = finishAttributes(attrs, cssClasses, section.extraAttributes);
363
+ if (section.noStack && section.columns.length > 1) {
364
+ return `
365
+ <mj-section ${sectionAttrs}>
366
+ <mj-group>
367
+ ${columns}
368
+ </mj-group>
369
+ </mj-section>
370
+ `.trim();
371
+ }
372
+ return `
373
+ <mj-section ${sectionAttrs}>
374
+ ${columns}
375
+ </mj-section>
376
+ `.trim();
377
+ }
378
+ /**
379
+ * Convert column to MJML
380
+ */
381
+ columnToMJML(column) {
382
+ if (column.hidden) return "";
383
+ if (column.subColumns && column.subColumns.length > 0) {
384
+ return this.subColumnsToMJML(column);
385
+ }
386
+ const cssClasses = ["el-column", `el-${column.id}`];
387
+ const attrs = [];
388
+ if (column.width) {
389
+ attrs.push(`width="${column.width}%"`);
390
+ }
391
+ if (column.backgroundGradient) {
392
+ const fallbackColor = column.backgroundGradient.stops[0]?.color;
393
+ if (fallbackColor) attrs.push(`background-color="${fallbackColor}"`);
394
+ cssClasses.push(`el-grad-${column.id}`);
395
+ } else {
396
+ if (column.backgroundColor) {
397
+ attrs.push(`background-color="${column.backgroundColor}"`);
398
+ }
399
+ }
400
+ if (column.verticalAlign) {
401
+ attrs.push(`vertical-align="${column.verticalAlign}"`);
402
+ }
403
+ if (column.padding) {
404
+ const padding = spacingToString(column.padding);
405
+ if (padding) attrs.push(`padding="${padding}"`);
406
+ }
407
+ const blocks = column.blocks.map((block) => this.blockToMJML(block)).join("\n");
408
+ return `
409
+ <mj-column ${finishAttributes(attrs, cssClasses, column.extraAttributes)}>
410
+ ${blocks}
411
+ </mj-column>
412
+ `.trim();
413
+ }
414
+ /**
415
+ * Emit a group column as an mj-column wrapping a hand-built nested
416
+ * table inside an mj-raw island. The parent mj-section structure
417
+ * stays standard MJML; only the nested area escapes MJML's parser.
418
+ *
419
+ * The responsive media query (table.ee-sub-cols td.ee-sub-col) is
420
+ * injected once at document head via generateHead when the
421
+ * needsSubColumnStyles flag is set.
422
+ */
423
+ subColumnsToMJML(column) {
424
+ this.needsSubColumnStyles = true;
425
+ const subs = column.subColumns ?? [];
426
+ const sumRaw = subs.reduce((a, s) => a + (s.width || 0), 0) || 100;
427
+ const widths = subs.map((s) => Math.round((s.width || 0) / sumRaw * 1e4) / 100);
428
+ const cells = subs.map((sc, i) => {
429
+ const inner = (sc.blocks ?? []).map((b) => blockToRawHtml(b)).join("\n");
430
+ const valign = sc.verticalAlign ?? "top";
431
+ const hasPadding = sc.paddingTop || sc.paddingRight || sc.paddingBottom || sc.paddingLeft;
432
+ const padding = hasPadding ? `padding:${sc.paddingTop || "0"} ${sc.paddingRight || "0"} ${sc.paddingBottom || "0"} ${sc.paddingLeft || "0"};` : "padding:10px;";
433
+ const bg = sc.backgroundColor ? `background-color:${sc.backgroundColor};` : "";
434
+ return `<td class="ee-sub-col" width="${widths[i]}%" valign="${valign}" style="${padding}${bg}">${inner}</td>`;
435
+ }).join("");
436
+ const colAttrs = [];
437
+ if (column.width) colAttrs.push(`width="${column.width}%"`);
438
+ if (column.backgroundColor) colAttrs.push(`background-color="${column.backgroundColor}"`);
439
+ if (column.verticalAlign) colAttrs.push(`vertical-align="${column.verticalAlign}"`);
440
+ if (column.padding) {
441
+ const padding = spacingToString(column.padding);
442
+ if (padding) colAttrs.push(`padding="${padding}"`);
443
+ }
444
+ return `
445
+ <mj-column ${finishAttributes(colAttrs, ["el-column", `el-${column.id}`], column.extraAttributes)}>
446
+ <mj-raw>
447
+ <table role="presentation" class="ee-sub-cols" ${EDITOR_DATA_ATTRIBUTE.subColumns}="${encodeEditorData(subs)}" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;">
448
+ <tr>${cells}</tr>
449
+ </table>
450
+ </mj-raw>
451
+ </mj-column>
452
+ `.trim();
453
+ }
454
+ /**
455
+ * Convert block to MJML based on type
456
+ */
457
+ blockToMJML(block) {
458
+ if (block.hidden) return "";
459
+ switch (block.type) {
460
+ case "text":
461
+ return this.textBlockToMJML(block);
462
+ case "image":
463
+ return this.imageBlockToMJML(block);
464
+ case "button":
465
+ return this.buttonBlockToMJML(block);
466
+ case "divider":
467
+ return this.dividerBlockToMJML(block);
468
+ case "spacer":
469
+ return this.spacerBlockToMJML(block);
470
+ case "social":
471
+ return this.socialBlockToMJML(block);
472
+ case "hero":
473
+ return this.heroBlockToMJML(block);
474
+ case "accordion":
475
+ return this.accordionBlockToMJML(block);
476
+ case "raw":
477
+ return this.rawBlockToMJML(block);
478
+ case "navbar":
479
+ return this.navbarBlockToMJML(block);
480
+ case "carousel":
481
+ return this.carouselBlockToMJML(block);
482
+ case "table":
483
+ return this.tableBlockToMJML(block);
484
+ case "header":
485
+ return this.headerBlockToMJML();
486
+ case "footer":
487
+ return this.footerBlockToMJML();
488
+ default:
489
+ console.warn(`Unknown block type: ${block.type}`);
490
+ return "";
491
+ }
492
+ }
493
+ /**
494
+ * Convert text block to MJML
495
+ *
496
+ * Note: MJML applies styles to the container <td>, but TipTap content
497
+ * (wrapped in <p> tags) doesn't inherit these styles. We solve this by
498
+ * wrapping the content in a <div> with explicit inline styles.
499
+ */
500
+ textBlockToMJML(block) {
501
+ const attrs = [];
502
+ const inlineStyles = [];
503
+ if (block.align) {
504
+ attrs.push(`align="${block.align}"`);
505
+ inlineStyles.push(`text-align:${block.align}`);
506
+ }
507
+ if (block.color) {
508
+ attrs.push(`color="${block.color}"`);
509
+ inlineStyles.push(`color:${block.color}`);
510
+ }
511
+ if (block.fontSize) {
512
+ attrs.push(`font-size="${block.fontSize}"`);
513
+ inlineStyles.push(`font-size:${block.fontSize}`);
514
+ }
515
+ if (block.fontFamily) {
516
+ attrs.push(`font-family="${block.fontFamily}"`);
517
+ inlineStyles.push(`font-family:${block.fontFamily}`);
518
+ }
519
+ if (block.lineHeight) {
520
+ attrs.push(`line-height="${block.lineHeight}"`);
521
+ inlineStyles.push(`line-height:${block.lineHeight}`);
522
+ }
523
+ if (block.padding) {
524
+ const padding = spacingToString(block.padding);
525
+ if (padding) attrs.push(`padding="${padding}"`);
526
+ }
527
+ const styledContent = inlineStyles.length > 0 ? `<div style="${inlineStyles.join(";")}">${block.content}</div>` : block.content;
528
+ return `<mj-text ${finishAttributes(attrs, ["el-text", `el-${block.id}`], block.extraAttributes)}>${styledContent}</mj-text>`;
529
+ }
530
+ /**
531
+ * Convert image block to MJML
532
+ */
533
+ imageBlockToMJML(block) {
534
+ const attrs = [`src="${block.src}"`];
535
+ if (block.alt) attrs.push(`alt="${block.alt}"`);
536
+ if (block.width) attrs.push(`width="${block.width}"`);
537
+ if (block.height) attrs.push(`height="${block.height}"`);
538
+ if (block.align) attrs.push(`align="${block.align}"`);
539
+ if (block.href) attrs.push(`href="${block.href}"`);
540
+ if (block.borderRadius) attrs.push(`border-radius="${block.borderRadius}"`);
541
+ if (block.padding) {
542
+ const padding = spacingToString(block.padding);
543
+ if (padding) attrs.push(`padding="${padding}"`);
544
+ }
545
+ return `<mj-image ${finishAttributes(attrs, ["el-image", `el-${block.id}`], block.extraAttributes)} />`;
546
+ }
547
+ /**
548
+ * Convert button block to MJML
549
+ */
550
+ buttonBlockToMJML(block) {
551
+ const attrs = [`href="${block.href}"`];
552
+ if (block.align) attrs.push(`align="${block.align}"`);
553
+ if (block.backgroundColor) attrs.push(`background-color="${block.backgroundColor}"`);
554
+ if (block.color) attrs.push(`color="${block.color}"`);
555
+ if (block.borderRadius) attrs.push(`border-radius="${block.borderRadius}"`);
556
+ if (block.border) attrs.push(`border="${block.border}"`);
557
+ if (block.innerPadding) attrs.push(`inner-padding="${block.innerPadding}"`);
558
+ if (block.padding) {
559
+ const padding = spacingToString(block.padding);
560
+ if (padding) attrs.push(`padding="${padding}"`);
561
+ }
562
+ return `<mj-button ${finishAttributes(attrs, ["el-button", `el-${block.id}`], block.extraAttributes)}>${block.label}</mj-button>`;
563
+ }
564
+ /**
565
+ * Convert divider block to MJML
566
+ */
567
+ dividerBlockToMJML(block) {
568
+ const attrs = [];
569
+ if (block.borderColor) attrs.push(`border-color="${block.borderColor}"`);
570
+ if (block.borderWidth) attrs.push(`border-width="${block.borderWidth}"`);
571
+ if (block.borderStyle) attrs.push(`border-style="${block.borderStyle}"`);
572
+ if (block.width) attrs.push(`width="${block.width}"`);
573
+ if (block.padding) {
574
+ const padding = spacingToString(block.padding);
575
+ if (padding) attrs.push(`padding="${padding}"`);
576
+ }
577
+ return `<mj-divider ${finishAttributes(attrs, ["el-divider", `el-${block.id}`], block.extraAttributes)} />`;
578
+ }
579
+ /**
580
+ * Convert spacer block to MJML
581
+ */
582
+ spacerBlockToMJML(block) {
583
+ return `<mj-spacer ${finishAttributes([`height="${block.height}"`], ["el-spacer", `el-${block.id}`], block.extraAttributes)} />`;
584
+ }
585
+ /**
586
+ * Get white SVG icon as data URI for a platform
587
+ * Uses clean, minimal SVGs optimized for email
588
+ */
589
+ getSocialIconDataUri(platform) {
590
+ const svgIcons = {
591
+ facebook: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>',
592
+ twitter: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/></svg>',
593
+ instagram: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M12 0C8.74 0 8.333.015 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.74 0 12s.015 3.667.072 4.947c.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.74 24 12 24s3.667-.015 4.947-.072c4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/></svg>',
594
+ linkedin: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>',
595
+ youtube: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M23.498 6.186a3.016 3.016 0 00-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 00.502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 002.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 002.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>',
596
+ pinterest: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M12 0C5.373 0 0 5.372 0 12c0 5.084 3.163 9.426 7.627 11.174-.105-.949-.2-2.405.042-3.441.218-.937 1.407-5.965 1.407-5.965s-.359-.719-.359-1.782c0-1.668.967-2.914 2.171-2.914 1.023 0 1.518.769 1.518 1.69 0 1.029-.655 2.568-.994 3.995-.283 1.194.599 2.169 1.777 2.169 2.133 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.012-4.882-3.414 0-5.418 2.561-5.418 5.207 0 1.031.397 2.138.893 2.738a.36.36 0 01.083.345c-.091.378-.293 1.194-.333 1.361-.052.218-.174.265-.402.159-1.495-.696-2.428-2.882-2.428-4.64 0-3.779 2.744-7.253 7.917-7.253 4.158 0 7.389 2.963 7.389 6.923 0 4.13-2.607 7.461-6.229 7.461-1.217 0-2.36-.632-2.75-1.378l-.748 2.853c-.271 1.043-1.002 2.35-1.492 3.146C9.57 23.812 10.763 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"/></svg>',
597
+ github: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>'
598
+ };
599
+ const svg = svgIcons[platform] || svgIcons.facebook;
600
+ return `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
601
+ }
602
+ /**
603
+ * Convert social block to MJML using raw HTML table for reliable horizontal layout
604
+ * Uses styled anchor tags with background colors for full width control
605
+ */
606
+ socialBlockToMJML(block) {
607
+ const iconSize = block.iconSize || "40px";
608
+ const iconPadding = block.iconPadding || "8px";
609
+ const borderRadius = block.borderRadius || "999px";
610
+ const align = block.align || "center";
611
+ const isVertical = block.mode === "vertical";
612
+ const sizeNum = parseInt(iconSize, 10) || 40;
613
+ const innerIconSize = Math.round(sizeNum * 0.5);
614
+ const paddingNum = parseInt(iconPadding, 10) || 8;
615
+ const getLinkColor = (link) => {
616
+ return link.color || this.SOCIAL_COLORS[link.platform] || "#666666";
617
+ };
618
+ if (isVertical) {
619
+ const verticalButtons = block.links.map((link) => {
620
+ const bgColor = getLinkColor(link);
621
+ const iconUrl = this.getSocialIconDataUri(link.platform);
622
+ return `<mj-button
623
+ href="${link.url}"
624
+ background-color="${bgColor}"
625
+ border-radius="${borderRadius}"
626
+ width="${iconSize}"
627
+ height="${iconSize}"
628
+ padding="${iconPadding} 0"
629
+ inner-padding="0"
630
+ align="${align}"
631
+ css-class="el-social-btn el-${block.id}-${link.platform}"
632
+ ><img src="${iconUrl}" alt="${link.platform}" width="${innerIconSize}" height="${innerIconSize}" style="display:block;margin:auto;" /></mj-button>`;
633
+ }).join("\n");
634
+ return `<!-- Social Icons (vertical) -->
635
+ ${verticalButtons}`;
636
+ }
637
+ const alignMargin = align === "center" ? "0 auto" : align === "right" ? "0 0 0 auto" : "0 auto 0 0";
638
+ const socialCells = block.links.map((link, index) => {
639
+ const bgColor = getLinkColor(link);
640
+ const iconUrl = this.getSocialIconDataUri(link.platform);
641
+ const isLast = index === block.links.length - 1;
642
+ const cellPadding = isLast ? "0" : `0 ${paddingNum}px 0 0`;
643
+ const paddingForCentering = Math.round((sizeNum - innerIconSize) / 2);
644
+ return `<td style="padding: ${cellPadding};">
645
+ <a href="${link.url}" target="_blank" style="display: block; width: ${iconSize}; height: ${iconSize}; background-color: ${bgColor}; border-radius: ${borderRadius}; text-decoration: none;">
646
+ <img src="${iconUrl}" alt="${link.platform}" width="${innerIconSize}" height="${innerIconSize}" style="display: block; margin: ${paddingForCentering}px auto 0 auto;" />
647
+ </a>
648
+ </td>`;
649
+ }).join("\n ");
650
+ return `<!-- Social Icons (horizontal) -->
651
+ <mj-raw>
652
+ <table align="${align}" role="presentation" cellpadding="0" cellspacing="0" style="margin: ${alignMargin};" ${EDITOR_DATA_ATTRIBUTE.social}="${encodeEditorData(block)}">
653
+ <tr>
654
+ ${socialCells}
655
+ </tr>
656
+ </table>
657
+ </mj-raw>`;
658
+ }
659
+ /**
660
+ * Convert hero block to MJML
661
+ */
662
+ heroBlockToMJML(block) {
663
+ const attrs = [`background-url="${block.backgroundImage}"`];
664
+ if (block.backgroundHeight) attrs.push(`background-height="${block.backgroundHeight}"`);
665
+ if (block.backgroundWidth) attrs.push(`background-width="${block.backgroundWidth}"`);
666
+ if (block.backgroundColor) attrs.push(`background-color="${block.backgroundColor}"`);
667
+ if (block.verticalAlign) attrs.push(`vertical-align="${block.verticalAlign}"`);
668
+ if (block.mode) attrs.push(`mode="${block.mode}"`);
669
+ return `
670
+ <mj-hero ${finishAttributes(attrs, ["el-hero", `el-${block.id}`], block.extraAttributes)}>
671
+ <mj-text align="center" color="#ffffff" font-size="32px" font-weight="bold">
672
+ Hero Title
673
+ </mj-text>
674
+ <mj-text align="center" color="#ffffff" font-size="16px">
675
+ Add your hero content here
676
+ </mj-text>
677
+ <mj-button href="#" background-color="#ffffff" color="#944923">
678
+ Call to Action
679
+ </mj-button>
680
+ </mj-hero>
681
+ `.trim();
682
+ }
683
+ /**
684
+ * Convert accordion block to MJML
685
+ */
686
+ accordionBlockToMJML(block) {
687
+ const attrs = [];
688
+ if (block.iconPosition) attrs.push(`icon-position="${block.iconPosition}"`);
689
+ if (block.borderColor) attrs.push(`border="${block.borderColor}"`);
690
+ if (block.fontFamily) attrs.push(`font-family="${block.fontFamily}"`);
691
+ const items = block.items.map(
692
+ (item) => `
693
+ <mj-accordion-element>
694
+ <mj-accordion-title>${item.title}</mj-accordion-title>
695
+ <mj-accordion-text>${item.content}</mj-accordion-text>
696
+ </mj-accordion-element>`
697
+ ).join("\n");
698
+ return `
699
+ <mj-accordion ${finishAttributes(attrs, ["el-accordion", `el-${block.id}`], block.extraAttributes)}>
700
+ ${items}
701
+ </mj-accordion>
702
+ `.trim();
703
+ }
704
+ /**
705
+ * Convert raw HTML block to MJML
706
+ */
707
+ rawBlockToMJML(block) {
708
+ return `<mj-raw css-class="el-raw el-${block.id}">${block.html}</mj-raw>`;
709
+ }
710
+ /**
711
+ * Convert navbar block to MJML
712
+ */
713
+ navbarBlockToMJML(block) {
714
+ const attrs = [];
715
+ if (block.hamburger) attrs.push('hamburger="hamburger"');
716
+ if (block.baseUrl) attrs.push(`base-url="${block.baseUrl}"`);
717
+ if (block.align) attrs.push(`align="${block.align}"`);
718
+ if (block.icoColor) attrs.push(`ico-color="${block.icoColor}"`);
719
+ if (block.padding) {
720
+ const padding = spacingToString(block.padding);
721
+ if (padding) attrs.push(`padding="${padding}"`);
722
+ }
723
+ const links = block.links.map((link) => {
724
+ const linkAttrs = [`href="${link.href}"`];
725
+ if (link.color) linkAttrs.push(`color="${link.color}"`);
726
+ return ` <mj-navbar-link ${linkAttrs.join(" ")}>${link.label}</mj-navbar-link>`;
727
+ }).join("\n");
728
+ return `
729
+ <mj-navbar ${finishAttributes(attrs, ["el-navbar", `el-${block.id}`], block.extraAttributes)}>
730
+ ${links}
731
+ </mj-navbar>
732
+ `.trim();
733
+ }
734
+ /**
735
+ * Convert carousel block to MJML
736
+ */
737
+ carouselBlockToMJML(block) {
738
+ const attrs = [];
739
+ if (block.thumbnails) attrs.push(`thumbnails="${block.thumbnails}"`);
740
+ if (block.borderRadius) attrs.push(`border-radius="${block.borderRadius}"`);
741
+ if (block.iconWidth) attrs.push(`icon-width="${block.iconWidth}"`);
742
+ if (block.tbBorderRadius) attrs.push(`tb-border-radius="${block.tbBorderRadius}"`);
743
+ if (block.padding) {
744
+ const padding = spacingToString(block.padding);
745
+ if (padding) attrs.push(`padding="${padding}"`);
746
+ }
747
+ const images = block.images.map((img) => {
748
+ const imgAttrs = [`src="${img.src}"`];
749
+ if (img.alt) imgAttrs.push(`alt="${img.alt}"`);
750
+ if (img.href) imgAttrs.push(`href="${img.href}"`);
751
+ if (img.thumbnailSrc) imgAttrs.push(`thumbnails-src="${img.thumbnailSrc}"`);
752
+ return ` <mj-carousel-image ${imgAttrs.join(" ")} />`;
753
+ }).join("\n");
754
+ return `
755
+ <mj-carousel ${finishAttributes(attrs, ["el-carousel", `el-${block.id}`], block.extraAttributes)}>
756
+ ${images}
757
+ </mj-carousel>
758
+ `.trim();
759
+ }
760
+ /**
761
+ * Convert table block to MJML
762
+ */
763
+ tableBlockToMJML(block) {
764
+ const attrs = [];
765
+ if (block.align) attrs.push(`align="${block.align}"`);
766
+ if (block.color) attrs.push(`color="${block.color}"`);
767
+ if (block.fontFamily) attrs.push(`font-family="${block.fontFamily}"`);
768
+ if (block.fontSize) attrs.push(`font-size="${block.fontSize}"`);
769
+ if (block.cellpadding) attrs.push(`cellpadding="${block.cellpadding}"`);
770
+ if (block.cellspacing) attrs.push(`cellspacing="${block.cellspacing}"`);
771
+ if (block.border) attrs.push(`border="${block.border}"`);
772
+ if (block.padding) {
773
+ const padding = spacingToString(block.padding);
774
+ if (padding) attrs.push(`padding="${padding}"`);
775
+ }
776
+ const headerCells = block.headers.map((h) => `<th style="padding: 8px; border-bottom: 1px solid #ddd; text-align: left;">${h}</th>`).join("");
777
+ const headerRow = `<tr style="background-color: #f5f5f5;">${headerCells}</tr>`;
778
+ const dataRows = block.rows.map((row) => {
779
+ const cells = row.map((cell) => `<td style="padding: 8px; border-bottom: 1px solid #eee;">${cell}</td>`).join("");
780
+ return `<tr>${cells}</tr>`;
781
+ }).join("\n");
782
+ return `
783
+ <mj-table ${finishAttributes(attrs, ["el-table", `el-${block.id}`], block.extraAttributes)}>
784
+ ${headerRow}
785
+ ${dataRows}
786
+ </mj-table>
787
+ `.trim();
788
+ }
789
+ /**
790
+ * Generate the locked header block.
791
+ *
792
+ * It used to render one client's company name and a logo from an image host;
793
+ * both are gone. What is left is a placeholder image slot. Keep this in step
794
+ * with `headerBlockDefinition` in `packages/blocks/src/branded/index.ts`:
795
+ * which of the two runs depends on how the registry is configured.
796
+ *
797
+ * The placeholder is a `data:` URI rather than an address on an image host,
798
+ * so a workspace whose `asset_policy` is `service_only` can still send a mail
799
+ * that contains this block.
800
+ */
801
+ headerBlockToMJML() {
802
+ return `
803
+ <mj-wrapper background-color="#ffffff" padding="20px" css-class="el-header-wrapper">
804
+ <mj-section css-class="el-header-section">
805
+ <mj-column css-class="el-header-column">
806
+ <!-- Nothing: see headerBlockDefinition in packages/blocks. -->
807
+ <mj-spacer height="1px" css-class="el-header-spacer" />
808
+ </mj-column>
809
+ </mj-section>
810
+ </mj-wrapper>
811
+ `.trim();
812
+ }
813
+ /**
814
+ * Generate the locked footer block: the unsubscribe link and nothing else.
815
+ *
816
+ * It used to carry a copyright line naming one client's company. A locked
817
+ * block carries no props, so whoever sends the mail cannot correct a name
818
+ * that is not theirs; the line is gone rather than replaced with a fake one.
819
+ * Keep this in step with `footerBlockDefinition` in
820
+ * `packages/blocks/src/branded/index.ts`.
821
+ */
822
+ footerBlockToMJML() {
823
+ return `
824
+ <mj-wrapper background-color="#f5f5f5" padding="20px" css-class="el-footer-wrapper">
825
+ <mj-section css-class="el-footer-section">
826
+ <mj-column css-class="el-footer-column">
827
+ <mj-text align="center" font-size="12px" color="#666666" css-class="el-footer-text-2">
828
+ <a href="{{unsubscribe_url}}" style="color: #374151; text-decoration: underline;">Unsubscribe</a>
829
+ </mj-text>
830
+ </mj-column>
831
+ </mj-section>
832
+ </mj-wrapper>
833
+ `.trim();
834
+ }
835
+ };
836
+ function createMJMLCompiler() {
837
+ return new MJMLCompiler();
838
+ }
839
+
840
+ // src/store/mst/MJMLExporter.ts
841
+ import mjml2html2 from "mjml";
842
+ import { getSnapshot } from "mobx-state-tree";
843
+ var MJMLExporter = class {
844
+ constructor(options = {}) {
845
+ this.compiler = new MJMLCompiler();
846
+ this.options = {
847
+ validationLevel: options.validationLevel || "soft",
848
+ minify: options.minify ?? false,
849
+ beautify: options.beautify ?? false
850
+ };
851
+ }
852
+ /**
853
+ * Export template to MJML + HTML
854
+ */
855
+ export(template) {
856
+ const mjml = this.exportMJML(template);
857
+ try {
858
+ const result = mjml2html2(mjml, {
859
+ // Never resolve <mj-include>: see MJMLCompiler.compile.
860
+ ignoreIncludes: true,
861
+ validationLevel: this.options.validationLevel,
862
+ minify: this.options.minify,
863
+ beautify: this.options.beautify
864
+ });
865
+ return {
866
+ mjml,
867
+ html: result.html,
868
+ errors: result.errors.length > 0 ? result.errors.map((e) => e.formattedMessage) : void 0
869
+ };
870
+ } catch (error) {
871
+ return { mjml, html: "", errors: [error instanceof Error ? error.message : "Unknown compilation error"] };
872
+ }
873
+ }
874
+ /**
875
+ * Export only MJML (without HTML compilation)
876
+ */
877
+ exportMJML(template) {
878
+ return this.compiler.toMJML(JSON.parse(JSON.stringify(getSnapshot(template))));
879
+ }
880
+ };
881
+ function createMJMLExporter(options) {
882
+ return new MJMLExporter(options);
883
+ }
884
+ function exportTemplate(template, options) {
885
+ const exporter = new MJMLExporter(options);
886
+ return exporter.export(template);
887
+ }
888
+
889
+ // src/importer/importMjml.ts
890
+ import mjml2html3 from "mjml";
891
+ import { nanoid } from "nanoid";
892
+
893
+ // src/importer/types.ts
894
+ var MAX_MJML_BYTES = 512 * 1024;
895
+ var MAX_MJML_DEPTH = 32;
896
+ var MAX_MJML_ELEMENTS = 5e3;
897
+ var MjmlImportError = class extends Error {
898
+ constructor(code, message, position = {}) {
899
+ super(position.line !== void 0 ? `Line ${position.line}${position.column !== void 0 ? `, column ${position.column}` : ""}: ${message}` : message);
900
+ this.name = "MjmlImportError";
901
+ this.code = code;
902
+ this.line = position.line;
903
+ this.column = position.column;
904
+ }
905
+ /** A plain object that survives a worker thread boundary. */
906
+ toJSON() {
907
+ return { code: this.code, message: this.message, line: this.line, column: this.column };
908
+ }
909
+ };
910
+ function isMjmlImportError(error) {
911
+ return error instanceof MjmlImportError;
912
+ }
913
+
914
+ // src/importer/scan.ts
915
+ function locator(source) {
916
+ const starts = [0];
917
+ for (let i = 0; i < source.length; i++) if (source.charCodeAt(i) === 10) starts.push(i + 1);
918
+ return (index) => {
919
+ let lo = 0;
920
+ let hi = starts.length - 1;
921
+ while (lo < hi) {
922
+ const mid = lo + hi + 1 >> 1;
923
+ if (starts[mid] <= index) lo = mid;
924
+ else hi = mid - 1;
925
+ }
926
+ return { line: lo + 1, column: index - starts[lo] + 1 };
927
+ };
928
+ }
929
+ var NAME = /[A-Za-z_][A-Za-z0-9_.:-]*/y;
930
+ var ATTRIBUTE = /\s+([^\s=/>"'<]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/y;
931
+ var TAG_END = /\s*(\/?)>/y;
932
+ function scanMjml(source, endingTags) {
933
+ if (Buffer.byteLength(source, "utf8") > MAX_MJML_BYTES) {
934
+ throw new MjmlImportError("too_large", `The MJML is larger than ${MAX_MJML_BYTES} bytes.`);
935
+ }
936
+ const at = locator(source);
937
+ const include = /<\s*mj-include\b/i.exec(source);
938
+ if (include) {
939
+ throw new MjmlImportError(
940
+ "include_not_supported",
941
+ "mj-include is not supported: an import has no files to include. Paste the included MJML in its place.",
942
+ at(include.index)
943
+ );
944
+ }
945
+ const fail = (code, message, index) => {
946
+ throw new MjmlImportError(code, message, at(index));
947
+ };
948
+ const stack = [];
949
+ let elements = 0;
950
+ let rootClosed = false;
951
+ let rootSeen = false;
952
+ let i = 0;
953
+ const skipPast = (terminator, from, what) => {
954
+ const end = source.indexOf(terminator, from);
955
+ if (end < 0) fail("invalid_xml", `${what} is never closed.`, from);
956
+ return end + terminator.length;
957
+ };
958
+ while (i < source.length) {
959
+ const lt = source.indexOf("<", i);
960
+ const textEnd = lt < 0 ? source.length : lt;
961
+ if (source.slice(i, textEnd).trim() !== "" && (stack.length === 0 || rootClosed)) {
962
+ fail(rootSeen ? "invalid_xml" : "not_mjml", rootSeen ? "Text after the closing </mjml>." : "The document must start with <mjml>.", i + source.slice(i, textEnd).search(/\S/));
963
+ }
964
+ if (lt < 0) break;
965
+ i = lt;
966
+ if (source.startsWith("<!--", i)) {
967
+ i = skipPast("-->", i + 4, "A comment");
968
+ continue;
969
+ }
970
+ if (source.startsWith("<![CDATA[", i)) {
971
+ i = skipPast("]]>", i + 9, "A CDATA section");
972
+ continue;
973
+ }
974
+ if (source.startsWith("<?", i)) {
975
+ if (rootSeen) fail("invalid_xml", "A processing instruction inside the document.", i);
976
+ i = skipPast("?>", i + 2, "A processing instruction");
977
+ continue;
978
+ }
979
+ if (source.startsWith("<!", i)) {
980
+ if (rootSeen) fail("invalid_xml", "A declaration inside the document.", i);
981
+ i = skipPast(">", i + 2, "A declaration");
982
+ continue;
983
+ }
984
+ const closing = source[i + 1] === "/";
985
+ NAME.lastIndex = i + (closing ? 2 : 1);
986
+ const nameMatch = NAME.exec(source);
987
+ if (!nameMatch) fail("invalid_xml", 'A "<" that does not start a tag. Write it as &lt; outside content.', i);
988
+ const name = nameMatch[0];
989
+ let cursor = NAME.lastIndex;
990
+ if (closing) {
991
+ TAG_END.lastIndex = cursor;
992
+ const end2 = TAG_END.exec(source);
993
+ if (!end2 || end2[1] === "/") fail("invalid_xml", `The closing tag </${name}> is malformed.`, i);
994
+ const open2 = stack.pop();
995
+ if (!open2) fail("invalid_xml", `</${name}> closes nothing.`, i);
996
+ if (open2.name !== name) {
997
+ const where = at(open2.index);
998
+ fail("invalid_xml", `</${name}> does not match <${open2.name}> opened on line ${where.line}, column ${where.column}.`, i);
999
+ }
1000
+ if (stack.length === 0) rootClosed = true;
1001
+ i = TAG_END.lastIndex;
1002
+ continue;
1003
+ }
1004
+ if (rootClosed) fail("invalid_xml", `<${name}> after the closing </mjml>.`, i);
1005
+ if (!rootSeen) {
1006
+ if (name !== "mjml") fail("not_mjml", `The document must start with <mjml>, not <${name}>.`, i);
1007
+ rootSeen = true;
1008
+ }
1009
+ if (name === "mj-include") {
1010
+ fail("include_not_supported", "mj-include is not supported: an import has no files to include. Paste the included MJML in its place.", i);
1011
+ }
1012
+ const seen = /* @__PURE__ */ new Set();
1013
+ for (; ; ) {
1014
+ ATTRIBUTE.lastIndex = cursor;
1015
+ const attr = ATTRIBUTE.exec(source);
1016
+ if (!attr) break;
1017
+ if (seen.has(attr[1])) fail("invalid_xml", `The attribute "${attr[1]}" appears twice on <${name}>.`, cursor);
1018
+ seen.add(attr[1]);
1019
+ cursor = ATTRIBUTE.lastIndex;
1020
+ }
1021
+ TAG_END.lastIndex = cursor;
1022
+ const end = TAG_END.exec(source);
1023
+ if (!end) fail("invalid_xml", `The tag <${name}> is malformed (an unquoted or unclosed attribute value?).`, cursor);
1024
+ i = TAG_END.lastIndex;
1025
+ elements += 1;
1026
+ if (elements > MAX_MJML_ELEMENTS) fail("too_many_elements", `More than ${MAX_MJML_ELEMENTS} MJML elements.`, i);
1027
+ if (end[1] === "/") {
1028
+ if (stack.length === 0) rootClosed = true;
1029
+ continue;
1030
+ }
1031
+ if (stack.length + 1 > MAX_MJML_DEPTH) fail("too_deep", `MJML elements are nested more than ${MAX_MJML_DEPTH} deep.`, i);
1032
+ if (endingTags.has(name)) {
1033
+ let depth = 1;
1034
+ const token = new RegExp(`<!--|<(/?)${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=[\\s/>])`, "g");
1035
+ token.lastIndex = i;
1036
+ let m;
1037
+ while (m = token.exec(source)) {
1038
+ if (m[0] === "<!--") {
1039
+ const close = source.indexOf("-->", m.index + 4);
1040
+ if (close < 0) fail("invalid_xml", "A comment is never closed.", m.index);
1041
+ token.lastIndex = close + 3;
1042
+ continue;
1043
+ }
1044
+ const gt = source.indexOf(">", m.index);
1045
+ if (gt < 0) fail("invalid_xml", `The tag at this position is never closed.`, m.index);
1046
+ if (m[1] === "/") depth -= 1;
1047
+ else if (source[gt - 1] !== "/") depth += 1;
1048
+ token.lastIndex = gt + 1;
1049
+ if (depth === 0) break;
1050
+ }
1051
+ if (depth !== 0) fail("invalid_xml", `<${name}> is never closed.`, i);
1052
+ i = token.lastIndex;
1053
+ if (stack.length === 0) rootClosed = true;
1054
+ continue;
1055
+ }
1056
+ stack.push({ name, index: lt });
1057
+ }
1058
+ if (!rootSeen) fail("not_mjml", "The document is empty: it must start with <mjml>.", 0);
1059
+ const open = stack.pop();
1060
+ if (open) fail("invalid_xml", `<${open.name}> is never closed.`, open.index);
1061
+ }
1062
+
1063
+ // src/importer/tree.ts
1064
+ import parseXmlModule from "mjml-parser-xml";
1065
+ import presetModule from "mjml-preset-core";
1066
+ function unwrap(mod) {
1067
+ const m = mod;
1068
+ return m && typeof m === "object" && "default" in m && m.default ? m.default : mod;
1069
+ }
1070
+ var parseXml = unwrap(parseXmlModule);
1071
+ var preset = unwrap(presetModule);
1072
+ var componentName = (c) => c.getTagName ? c.getTagName() : c.componentName ?? "";
1073
+ var COMPONENTS = Object.fromEntries(preset.components.map((c) => [componentName(c), c]));
1074
+ var ENDING_TAGS = new Set(
1075
+ preset.components.filter((c) => c.endingTag).map((c) => componentName(c))
1076
+ );
1077
+ var KNOWN_TAGS = /* @__PURE__ */ new Set(["mjml", ...Object.keys(COMPONENTS), "mj-all", "mj-class", "mj-selector", "mj-html-attribute"]);
1078
+ function normalize(node) {
1079
+ const attributes = {};
1080
+ for (const [k, v] of Object.entries(node.attributes ?? {})) attributes[k] = String(v).replace(/"/g, "&quot;");
1081
+ return {
1082
+ tagName: node.tagName,
1083
+ attributes,
1084
+ content: node.content,
1085
+ children: (node.children ?? []).map(normalize),
1086
+ line: node.line
1087
+ };
1088
+ }
1089
+ function parseMjml(source) {
1090
+ const root = parseXml(source, {
1091
+ components: COMPONENTS,
1092
+ keepComments: true,
1093
+ ignoreIncludes: true,
1094
+ convertBooleans: false,
1095
+ addEmptyAttributes: true
1096
+ });
1097
+ return normalize(root);
1098
+ }
1099
+ function serialize(node) {
1100
+ const attrs = Object.entries(node.attributes).map(([k, v]) => ` ${k}="${v}"`).join("");
1101
+ const inner = node.content !== void 0 ? node.content : node.children.map(serialize).join("");
1102
+ if (inner === "" && node.children.length === 0 && node.content === void 0) return `<${node.tagName}${attrs} />`;
1103
+ return `<${node.tagName}${attrs}>${inner}</${node.tagName}>`;
1104
+ }
1105
+ function isComment(node) {
1106
+ return node.tagName === "mj-raw" && Object.keys(node.attributes).length === 0 && node.children.length === 0 && /^<!--[\s\S]*-->$/.test(node.content ?? "");
1107
+ }
1108
+
1109
+ // src/importer/importMjml.ts
1110
+ var ID = /^[A-Za-z0-9_-]{1,64}$/;
1111
+ var ATTRIBUTE_NAME = /^[a-z][a-z0-9-]*$/;
1112
+ var FRAGMENT_LIMIT = 2e3;
1113
+ var EDITOR_SUB_COLUMN_STYLE = `@media only screen and (max-width:480px) {
1114
+ table.ee-sub-cols td.ee-sub-col {
1115
+ display: block !important;
1116
+ width: 100% !important;
1117
+ padding-bottom: 12px !important;
1118
+ }
1119
+ table.ee-sub-cols td.ee-sub-col:last-child {
1120
+ padding-bottom: 0 !important;
1121
+ }
1122
+ }`;
1123
+ var EDITOR_COMMENTS = /* @__PURE__ */ new Set(["<!-- Social Icons (horizontal) -->", "<!-- Social Icons (vertical) -->"]);
1124
+ var SOCIAL_PLATFORMS = /* @__PURE__ */ new Set(["facebook", "twitter", "instagram", "linkedin", "youtube", "pinterest", "github"]);
1125
+ var SOCIAL_COLORS = {
1126
+ facebook: "#1877F2",
1127
+ twitter: "#000000",
1128
+ instagram: "#E4405F",
1129
+ linkedin: "#0A66C2",
1130
+ youtube: "#FF0000",
1131
+ pinterest: "#BD081C",
1132
+ github: "#181717"
1133
+ };
1134
+ var squash = (s) => s.replace(/\s+/g, " ").trim();
1135
+ var shorten = (s) => s.length > FRAGMENT_LIMIT ? `${s.slice(0, FRAGMENT_LIMIT)}...` : s;
1136
+ function decodeEditorData(value) {
1137
+ if (!value || !/^[A-Za-z0-9+/=]+$/.test(value)) return null;
1138
+ try {
1139
+ return JSON.parse(Buffer.from(value, "base64").toString("utf8"));
1140
+ } catch {
1141
+ return null;
1142
+ }
1143
+ }
1144
+ function parsePadding(value) {
1145
+ const parts = value.trim().split(/\s+/);
1146
+ if (parts.length < 1 || parts.length > 4 || parts.some((p) => !/^-?[0-9.]+(px|%|em|rem)?$/.test(p))) return null;
1147
+ const [top, right = top, bottom = top, left = right] = parts;
1148
+ const all = { top, right, bottom, left };
1149
+ const out = {};
1150
+ for (const side of ["top", "right", "bottom", "left"]) if (all[side] !== "0") out[side] = all[side];
1151
+ if (Object.keys(out).length === 0) return { top: "0", right: "0", bottom: "0", left: "0" };
1152
+ return out;
1153
+ }
1154
+ function parseGradientRules(css) {
1155
+ const rules = css.trim().split("\n").filter((l) => l.trim() !== "");
1156
+ const out = /* @__PURE__ */ new Map();
1157
+ for (const rule of rules) {
1158
+ const m = /^\.el-grad-([A-Za-z0-9_-]+) \{ background-image: (linear|radial)-gradient\((?:(-?[0-9.]+)deg|circle), (.*)\); \}$/.exec(rule.trim());
1159
+ if (!m) return null;
1160
+ const stops = m[4].split(/,\s(?![^()]*\))/).map((s) => {
1161
+ const sm = /^(.*) (-?[0-9.]+)%$/.exec(s.trim());
1162
+ return sm ? { color: sm[1], position: Number(sm[2]) } : null;
1163
+ });
1164
+ if (stops.some((s) => s === null)) return null;
1165
+ out.set(m[1], { type: m[2], angle: m[3] ? Number(m[3]) : 0, stops });
1166
+ }
1167
+ return out;
1168
+ }
1169
+ var Importer = class {
1170
+ constructor(root) {
1171
+ this.root = root;
1172
+ this.warnings = [];
1173
+ this.usedIds = /* @__PURE__ */ new Set();
1174
+ this.fallbacks = [];
1175
+ this.gradients = /* @__PURE__ */ new Map();
1176
+ this.kept = /* @__PURE__ */ new Map();
1177
+ this.usesMjClass = false;
1178
+ this.hasOwnDefaults = false;
1179
+ }
1180
+ warn(code, severity, path, node, message, withFragment = false) {
1181
+ this.warnings.push({
1182
+ severity,
1183
+ code,
1184
+ path,
1185
+ line: node?.line,
1186
+ message,
1187
+ ...withFragment && node ? { fragment: shorten(serialize(node)) } : {}
1188
+ });
1189
+ }
1190
+ id(candidate) {
1191
+ if (candidate && ID.test(candidate) && !this.usedIds.has(candidate)) {
1192
+ this.usedIds.add(candidate);
1193
+ return candidate;
1194
+ }
1195
+ let fresh = nanoid();
1196
+ while (this.usedIds.has(fresh)) fresh = nanoid();
1197
+ this.usedIds.add(fresh);
1198
+ return fresh;
1199
+ }
1200
+ /** `css-class="el-<type> el-<id> ..."`: the editor's id, and the author's own classes. */
1201
+ identity(attrs, marker) {
1202
+ const classes = (attrs["css-class"] ?? "").split(/\s+/).filter(Boolean);
1203
+ delete attrs["css-class"];
1204
+ if (classes[0] === marker && classes[1]?.startsWith("el-")) {
1205
+ const id = classes[1].slice(3);
1206
+ return { id, classes: classes.slice(2).filter((c) => c !== `el-grad-${id}`) };
1207
+ }
1208
+ return { classes };
1209
+ }
1210
+ /** Whatever is left of `attrs` (plus the author's classes), as kept attributes. */
1211
+ extras(attrs, classes, path, node) {
1212
+ const out = {};
1213
+ for (const [name, value] of Object.entries(attrs)) {
1214
+ if (!ATTRIBUTE_NAME.test(name)) {
1215
+ this.warn("attribute_dropped", "info", path, node, `The attribute "${name}" is not an MJML attribute name; MJML ignored it and so does the editor.`);
1216
+ continue;
1217
+ }
1218
+ if (name === "mj-class") this.usesMjClass = true;
1219
+ out[name] = value;
1220
+ this.kept.set(name, (this.kept.get(name) ?? 0) + 1);
1221
+ }
1222
+ if (classes.length > 0) {
1223
+ out["css-class"] = classes.join(" ");
1224
+ this.kept.set("css-class", (this.kept.get("css-class") ?? 0) + 1);
1225
+ }
1226
+ return Object.keys(out).length > 0 ? out : void 0;
1227
+ }
1228
+ /** Marks `node` (a child of `parent`) to be kept as compiled HTML. */
1229
+ fallback(node, parent, path, reason, unknown = false) {
1230
+ const block = { id: this.id(), type: "raw", html: "" };
1231
+ this.fallbacks.push({ node, parent, block, unknown });
1232
+ if (unknown) {
1233
+ this.warn("unknown_component", "warning", path, node, `<${node.tagName}> is not an MJML component, so MJML renders nothing for it. Its source is kept, as a comment, in a Raw block.`, true);
1234
+ } else {
1235
+ this.warn("kept_as_html", "warning", path, node, `${reason} It is kept as compiled HTML in a Raw block: the mail looks the same, but it is not editable as a block. Rebuild it in the editor to edit it.`, true);
1236
+ }
1237
+ return block;
1238
+ }
1239
+ // Head
1240
+ head(head, body) {
1241
+ const metadata = {};
1242
+ const mjmlHead = {};
1243
+ const fonts = [];
1244
+ const css = [];
1245
+ const inline = [];
1246
+ const raw = [];
1247
+ let attributes;
1248
+ for (const [index, node] of (head?.children ?? []).entries()) {
1249
+ const path = `mj-head > ${node.tagName}[${index + 1}]`;
1250
+ const a = node.attributes;
1251
+ switch (node.tagName) {
1252
+ case "mj-title":
1253
+ metadata.title = node.content ?? "";
1254
+ break;
1255
+ case "mj-preview":
1256
+ metadata.previewText = node.content ?? "";
1257
+ break;
1258
+ case "mj-font":
1259
+ if (a.name && a.href && Object.keys(a).length === 2) fonts.push({ name: a.name, href: a.href });
1260
+ else raw.push(serialize(node));
1261
+ break;
1262
+ case "mj-breakpoint":
1263
+ if (a.width && Object.keys(a).length === 1) metadata.breakpoint = a.width;
1264
+ else raw.push(serialize(node));
1265
+ break;
1266
+ case "mj-style": {
1267
+ const content = node.content ?? "";
1268
+ const keys = Object.keys(a);
1269
+ if (keys.length === 1 && a.inline === "inline") inline.push(content);
1270
+ else if (keys.length > 0) {
1271
+ raw.push(serialize(node));
1272
+ this.warn("head_element_kept", "info", path, node, "An mj-style with attributes the editor has no field for is kept as it is.");
1273
+ } else if (squash(content) === squash(EDITOR_SUB_COLUMN_STYLE)) {
1274
+ } else {
1275
+ const gradients = parseGradientRules(content);
1276
+ if (gradients && gradients.size > 0) for (const [id, g] of gradients) this.gradients.set(id, g);
1277
+ else css.push(content);
1278
+ }
1279
+ break;
1280
+ }
1281
+ case "mj-attributes": {
1282
+ const markup = node.children.map(serialize).join("");
1283
+ attributes = (attributes ?? "") + markup;
1284
+ break;
1285
+ }
1286
+ default:
1287
+ raw.push(serialize(node));
1288
+ if (isComment(node)) break;
1289
+ if (!KNOWN_TAGS.has(node.tagName)) {
1290
+ this.warn("unknown_component", "warning", path, node, `<${node.tagName}> is not an MJML head element; it is kept as it is, and MJML ignores it.`, true);
1291
+ } else {
1292
+ this.warn("head_element_kept", "info", path, node, `<${node.tagName}> has no field in the editor; it is kept as it is and applies to the mail.`);
1293
+ }
1294
+ }
1295
+ }
1296
+ if (fonts.length > 0) metadata.fonts = fonts;
1297
+ if (css.length > 0) metadata.customCSS = css.join("\n");
1298
+ if (inline.length > 0) metadata.inlineCSS = inline.join("\n");
1299
+ const isEditorDefault = attributes !== void 0 && squash(attributes) === squash(DEFAULT_MJML_ATTRIBUTES.replace(/\s*\n\s*/g, ""));
1300
+ if (!isEditorDefault) {
1301
+ mjmlHead.attributes = attributes ?? "";
1302
+ if ((attributes ?? "").trim() !== "") this.hasOwnDefaults = true;
1303
+ }
1304
+ if (raw.length > 0) mjmlHead.headRaw = raw.join("\n");
1305
+ const bodyAttrs = { ...body.attributes };
1306
+ const bodyExtra = this.extras(bodyAttrs, [], "mj-body", body);
1307
+ if (bodyExtra) mjmlHead.bodyAttributes = bodyExtra;
1308
+ if (Object.keys(mjmlHead).length > 0) metadata.mjmlHead = mjmlHead;
1309
+ return metadata;
1310
+ }
1311
+ // Body
1312
+ body(body) {
1313
+ const items = [];
1314
+ const raw = this.rawRuns((section) => items.push(section));
1315
+ const counts = /* @__PURE__ */ new Map();
1316
+ for (const node of body.children) {
1317
+ const n = (counts.get(node.tagName) ?? 0) + 1;
1318
+ counts.set(node.tagName, n);
1319
+ const path = `mj-body > ${node.tagName}[${n}]`;
1320
+ if (node.tagName === "mj-raw") {
1321
+ if (isComment(node) && EDITOR_COMMENTS.has(node.content.trim())) continue;
1322
+ raw.push(this.raw(node, body, path));
1323
+ continue;
1324
+ }
1325
+ if (node.tagName === "mj-wrapper") {
1326
+ raw.end();
1327
+ items.push(this.wrapper(node, path));
1328
+ continue;
1329
+ }
1330
+ if (node.tagName === "mj-section") {
1331
+ const section = this.section(node, path);
1332
+ if (section) {
1333
+ raw.end();
1334
+ items.push(section);
1335
+ } else {
1336
+ raw.push(this.fallback(node, body, path, "The editor cannot hold this section as it is (see the other warnings for it)."));
1337
+ }
1338
+ continue;
1339
+ }
1340
+ if (node.tagName === "mj-hero") {
1341
+ raw.push(this.fallback(node, body, path, "The editor's Hero block has no content of its own, so an mj-hero with text and buttons cannot become one."));
1342
+ continue;
1343
+ }
1344
+ if (!KNOWN_TAGS.has(node.tagName)) {
1345
+ raw.push(this.fallback(node, body, path, "", true));
1346
+ continue;
1347
+ }
1348
+ raw.push(this.fallback(node, body, path, `<${node.tagName}> does not belong directly in mj-body; MJML renders it as it can.`));
1349
+ }
1350
+ if (typeof body.content === "string" && body.content.trim()) {
1351
+ this.warn("stray_text", "info", "mj-body", body, "Text directly in mj-body is ignored by MJML, and by the import.");
1352
+ }
1353
+ return items;
1354
+ }
1355
+ /**
1356
+ * Consecutive raw markup (in mj-body or in an mj-wrapper) collects in one
1357
+ * raw-only section (`bodyRaw`), which the compiler emits back in place as
1358
+ * `mj-raw`; any other child ends the run.
1359
+ */
1360
+ rawRuns(add) {
1361
+ let run = null;
1362
+ return {
1363
+ push: (block) => {
1364
+ if (!run) {
1365
+ run = [];
1366
+ add({ id: this.id(), type: "section", bodyRaw: true, columns: [{ id: this.id(), width: 100, blocks: run }] });
1367
+ }
1368
+ run.push(block);
1369
+ },
1370
+ end: () => {
1371
+ run = null;
1372
+ }
1373
+ };
1374
+ }
1375
+ /** An `mj-raw` child of mj-body or mj-wrapper: its markup, or its compiled output when it has attributes the editor cannot keep. */
1376
+ raw(node, parent, path) {
1377
+ const attrs = { ...node.attributes };
1378
+ const { id, classes } = this.identity(attrs, "el-raw");
1379
+ if (Object.keys(attrs).length > 0 || classes.length > 0) {
1380
+ return this.fallback(node, parent, path, "This mj-raw has attributes (such as position) the editor cannot keep.");
1381
+ }
1382
+ return { id: this.id(id), type: "raw", html: node.content ?? "" };
1383
+ }
1384
+ wrapper(node, path) {
1385
+ const attrs = { ...node.attributes };
1386
+ const { id, classes } = this.identity(attrs, "el-wrapper");
1387
+ const wrapper = { id: this.id(id), type: "wrapper", sections: [] };
1388
+ const gradient = id ? this.gradients.get(id) : void 0;
1389
+ if (gradient) {
1390
+ wrapper.backgroundGradient = gradient;
1391
+ delete attrs["background-color"];
1392
+ }
1393
+ this.mapCommon(attrs, wrapper, {
1394
+ "background-color": "backgroundColor",
1395
+ "background-url": "backgroundImage",
1396
+ "background-position": "backgroundPosition",
1397
+ "background-size": "backgroundSize",
1398
+ border: "border",
1399
+ "border-top": "borderTop",
1400
+ "border-right": "borderRight",
1401
+ "border-bottom": "borderBottom",
1402
+ "border-left": "borderLeft",
1403
+ "border-radius": "borderRadius"
1404
+ });
1405
+ this.mapEnum(attrs, wrapper, "background-repeat", "backgroundRepeat", ["repeat", "no-repeat"]);
1406
+ this.mapEnum(attrs, wrapper, "text-align", "textAlign", ["left", "center", "right"]);
1407
+ if (attrs["full-width"] === "full-width") {
1408
+ wrapper.fullWidth = true;
1409
+ delete attrs["full-width"];
1410
+ }
1411
+ if (attrs.gap !== void 0 && /^[0-9]+(\.[0-9]+)?px$/.test(attrs.gap)) {
1412
+ wrapper.gap = attrs.gap;
1413
+ delete attrs.gap;
1414
+ }
1415
+ this.mapPadding(attrs, wrapper);
1416
+ if (classes.length > 0) wrapper.cssClass = classes.join(" ");
1417
+ const extra = this.extras(attrs, [], path, node);
1418
+ if (extra) wrapper.extraAttributes = extra;
1419
+ const raw = this.rawRuns((section) => wrapper.sections.push(section));
1420
+ const counts = /* @__PURE__ */ new Map();
1421
+ for (const child of node.children) {
1422
+ const n = (counts.get(child.tagName) ?? 0) + 1;
1423
+ counts.set(child.tagName, n);
1424
+ const childPath = `${path} > ${child.tagName}[${n}]`;
1425
+ if (child.tagName === "mj-raw") {
1426
+ if (isComment(child) && EDITOR_COMMENTS.has(child.content.trim())) continue;
1427
+ raw.push(this.raw(child, node, childPath));
1428
+ continue;
1429
+ }
1430
+ if (child.tagName === "mj-section") {
1431
+ const section = this.section(child, childPath);
1432
+ if (section) {
1433
+ raw.end();
1434
+ wrapper.sections.push(section);
1435
+ } else {
1436
+ raw.push(this.fallback(child, node, childPath, "The editor cannot hold this section as it is (see the other warnings for it); it stays in its wrapper."));
1437
+ }
1438
+ continue;
1439
+ }
1440
+ if (!KNOWN_TAGS.has(child.tagName)) {
1441
+ raw.push(this.fallback(child, node, childPath, "", true));
1442
+ continue;
1443
+ }
1444
+ const why = child.tagName === "mj-hero" ? "The editor's Hero block has no content of its own, so an mj-hero with text and buttons cannot become one; it stays in its wrapper." : child.tagName === "mj-wrapper" ? "A wrapper cannot hold another wrapper; MJML renders this one as it can, and it stays in its outer wrapper." : `<${child.tagName}> does not belong directly in mj-wrapper; MJML renders it as it can, and it stays in its wrapper.`;
1445
+ raw.push(this.fallback(child, node, childPath, why));
1446
+ }
1447
+ if (typeof node.content === "string" && node.content.trim()) {
1448
+ this.warn("stray_text", "info", path, node, "Text directly in mj-wrapper is ignored by MJML, and by the import.");
1449
+ }
1450
+ return wrapper;
1451
+ }
1452
+ section(node, path) {
1453
+ const attrs = { ...node.attributes };
1454
+ const { id, classes } = this.identity(attrs, "el-section");
1455
+ const sectionId = this.id(id);
1456
+ const section = { id: sectionId, type: "section", columns: [] };
1457
+ const gradient = id ? this.gradients.get(id) : void 0;
1458
+ if (gradient) {
1459
+ section.backgroundGradient = gradient;
1460
+ delete attrs["background-color"];
1461
+ }
1462
+ this.mapCommon(attrs, section, {
1463
+ "background-color": "backgroundColor",
1464
+ "background-url": "backgroundImage",
1465
+ "background-position": "backgroundPosition",
1466
+ "background-size": "backgroundSize"
1467
+ });
1468
+ if (attrs["background-repeat"] === "repeat" || attrs["background-repeat"] === "no-repeat") {
1469
+ section.backgroundRepeat = attrs["background-repeat"];
1470
+ delete attrs["background-repeat"];
1471
+ }
1472
+ if (attrs["full-width"] === "full-width") {
1473
+ section.fullWidth = true;
1474
+ delete attrs["full-width"];
1475
+ }
1476
+ this.mapPadding(attrs, section);
1477
+ const children = [];
1478
+ for (const child of node.children) {
1479
+ if (isComment(child)) {
1480
+ if (/^<!--\[if/.test(child.content ?? "")) return null;
1481
+ this.warn("comment_dropped", "info", `${path} > comment`, child, "A comment between columns is left out: it renders nothing.");
1482
+ continue;
1483
+ }
1484
+ children.push(child);
1485
+ }
1486
+ let columnNodes = children;
1487
+ let parent = node;
1488
+ if (children.length === 1 && children[0].tagName === "mj-group") {
1489
+ const group = children[0];
1490
+ if (Object.keys(group.attributes).length > 0) return null;
1491
+ columnNodes = group.children.filter((c) => {
1492
+ if (!isComment(c)) return true;
1493
+ if (/^<!--\[if/.test(c.content ?? "")) columnNodes = [];
1494
+ return false;
1495
+ });
1496
+ parent = group;
1497
+ if (columnNodes.length > 1) section.noStack = true;
1498
+ }
1499
+ if (columnNodes.length === 0 || columnNodes.some((c) => c.tagName !== "mj-column")) return null;
1500
+ const counts = /* @__PURE__ */ new Map();
1501
+ for (const [index, col] of columnNodes.entries()) {
1502
+ const n = (counts.get(col.tagName) ?? 0) + 1;
1503
+ counts.set(col.tagName, n);
1504
+ section.columns.push(this.column(col, columnNodes.length, `${path}${parent !== node ? " > mj-group[1]" : ""} > mj-column[${index + 1}]`));
1505
+ }
1506
+ const extra = this.extras(attrs, classes, path, node);
1507
+ if (extra) section.extraAttributes = extra;
1508
+ return section;
1509
+ }
1510
+ column(node, siblings, path) {
1511
+ const attrs = { ...node.attributes };
1512
+ const { id, classes } = this.identity(attrs, "el-column");
1513
+ const column = { id: this.id(id), blocks: [] };
1514
+ const gradient = id ? this.gradients.get(id) : void 0;
1515
+ if (gradient) {
1516
+ column.backgroundGradient = gradient;
1517
+ delete attrs["background-color"];
1518
+ }
1519
+ const width = attrs.width;
1520
+ if (width === void 0) {
1521
+ if (!id) column.width = 100 / siblings;
1522
+ } else if (/^[0-9]+(\.[0-9]+)?%$/.test(width) && Number.parseFloat(width) <= 100) {
1523
+ column.width = Number.parseFloat(width);
1524
+ delete attrs.width;
1525
+ } else {
1526
+ this.warn("column_width_px", "info", path, node, `The column width "${width}" is kept as it is; the editor's width control works in percent.`);
1527
+ }
1528
+ this.mapCommon(attrs, column, { "background-color": "backgroundColor" });
1529
+ if (attrs["vertical-align"] === "top" || attrs["vertical-align"] === "middle" || attrs["vertical-align"] === "bottom") {
1530
+ column.verticalAlign = attrs["vertical-align"];
1531
+ delete attrs["vertical-align"];
1532
+ }
1533
+ this.mapPadding(attrs, column);
1534
+ const only = node.children.length === 1 ? node.children[0] : void 0;
1535
+ if (only?.tagName === "mj-raw") {
1536
+ const m = /^\s*<table role="presentation" class="ee-sub-cols" data-ee-subcols="([A-Za-z0-9+/=]+)"/.exec(only.content ?? "");
1537
+ const subs = decodeEditorData(m?.[1]);
1538
+ if (subs && Array.isArray(subs) && subs.length > 0) {
1539
+ column.subColumns = subs;
1540
+ for (const s of subs) this.id(s.id);
1541
+ const extra2 = this.extras(attrs, classes, path, node);
1542
+ if (extra2) column.extraAttributes = extra2;
1543
+ return column;
1544
+ }
1545
+ }
1546
+ const counts = /* @__PURE__ */ new Map();
1547
+ const children = node.children;
1548
+ for (let i = 0; i < children.length; i++) {
1549
+ const child = children[i];
1550
+ const n = (counts.get(child.tagName) ?? 0) + 1;
1551
+ counts.set(child.tagName, n);
1552
+ const childPath = `${path} > ${child.tagName}[${n}]`;
1553
+ if (isComment(child) && EDITOR_COMMENTS.has(child.content.trim())) continue;
1554
+ const social = this.socialButtons(children, i);
1555
+ if (social) {
1556
+ column.blocks.push(social.block);
1557
+ i = social.end - 1;
1558
+ continue;
1559
+ }
1560
+ const block = this.block(child, childPath);
1561
+ column.blocks.push(block ?? this.fallback(child, node, childPath, this.fallbackReason(child), !KNOWN_TAGS.has(child.tagName)));
1562
+ }
1563
+ const extra = this.extras(attrs, classes, path, node);
1564
+ if (extra) column.extraAttributes = extra;
1565
+ return column;
1566
+ }
1567
+ fallbackReason(node) {
1568
+ switch (node.tagName) {
1569
+ case "mj-social":
1570
+ return "The editor's Social block draws its own icons, so an mj-social would look different as one.";
1571
+ case "mj-table":
1572
+ return "The editor's Table block styles every cell itself, so this table would look different as one.";
1573
+ case "mj-hero":
1574
+ return "The editor's Hero block has no content of its own.";
1575
+ case "mj-button":
1576
+ return "A button without a link or a label cannot be an editor Button block.";
1577
+ case "mj-image":
1578
+ return "An image without a src cannot be an editor Image block.";
1579
+ default:
1580
+ return `The editor has no block for this <${node.tagName}> as it is written.`;
1581
+ }
1582
+ }
1583
+ socialButtons(children, start) {
1584
+ const read = (node) => {
1585
+ if (!node || node.tagName !== "mj-button") return null;
1586
+ const classes = (node.attributes["css-class"] ?? "").split(/\s+/);
1587
+ if (classes[0] !== "el-social-btn" || !classes[1]?.startsWith("el-")) return null;
1588
+ const m = /^el-(.+)-([a-z]+)$/.exec(classes[1]);
1589
+ if (!m || !SOCIAL_PLATFORMS.has(m[2])) return null;
1590
+ return { id: m[1], platform: m[2], a: node.attributes };
1591
+ };
1592
+ const first = read(children[start]);
1593
+ if (!first) return null;
1594
+ const links = [];
1595
+ let end = start;
1596
+ let cur = first;
1597
+ while (cur && cur.id === first.id) {
1598
+ const color = cur.a["background-color"];
1599
+ links.push({ platform: cur.platform, url: cur.a.href ?? "", ...color && color !== SOCIAL_COLORS[cur.platform] ? { color } : {} });
1600
+ end += 1;
1601
+ cur = read(children[end]);
1602
+ }
1603
+ const a = first.a;
1604
+ const block = { id: this.id(first.id), type: "social", mode: "vertical", links };
1605
+ if (a.width) block.iconSize = a.width;
1606
+ if (a.padding) block.iconPadding = a.padding.split(/\s+/)[0];
1607
+ if (a["border-radius"]) block.borderRadius = a["border-radius"];
1608
+ if (a.align === "left" || a.align === "center" || a.align === "right") block.align = a.align;
1609
+ return { block, end };
1610
+ }
1611
+ // Blocks
1612
+ block(node, path) {
1613
+ const attrs = { ...node.attributes };
1614
+ switch (node.tagName) {
1615
+ case "mj-text":
1616
+ return this.text(node, attrs, path);
1617
+ case "mj-image": {
1618
+ if (!attrs.src) return null;
1619
+ const { id, classes } = this.identity(attrs, "el-image");
1620
+ const b = { id: this.id(id), type: "image", src: attrs.src };
1621
+ delete attrs.src;
1622
+ this.mapCommon(attrs, b, { alt: "alt", width: "width", height: "height", href: "href", "border-radius": "borderRadius" });
1623
+ this.mapEnum(attrs, b, "align", "align", ["left", "center", "right"]);
1624
+ this.mapPadding(attrs, b);
1625
+ return this.finish(b, attrs, classes, path, node);
1626
+ }
1627
+ case "mj-button": {
1628
+ const label = node.content ?? "";
1629
+ if (!attrs.href || label.trim() === "") return null;
1630
+ const { id, classes } = this.identity(attrs, "el-button");
1631
+ const b = { id: this.id(id), type: "button", label, href: attrs.href };
1632
+ delete attrs.href;
1633
+ this.mapCommon(attrs, b, {
1634
+ "background-color": "backgroundColor",
1635
+ color: "color",
1636
+ "border-radius": "borderRadius",
1637
+ border: "border",
1638
+ "inner-padding": "innerPadding"
1639
+ });
1640
+ this.mapEnum(attrs, b, "align", "align", ["left", "center", "right"]);
1641
+ this.mapPadding(attrs, b);
1642
+ return this.finish(b, attrs, classes, path, node);
1643
+ }
1644
+ case "mj-divider": {
1645
+ const { id, classes } = this.identity(attrs, "el-divider");
1646
+ const b = { id: this.id(id), type: "divider" };
1647
+ this.mapCommon(attrs, b, { "border-color": "borderColor", "border-width": "borderWidth", width: "width" });
1648
+ this.mapEnum(attrs, b, "border-style", "borderStyle", ["solid", "dashed", "dotted"]);
1649
+ this.mapPadding(attrs, b);
1650
+ return this.finish(b, attrs, classes, path, node);
1651
+ }
1652
+ case "mj-spacer": {
1653
+ if (!attrs.height) return null;
1654
+ const { id, classes } = this.identity(attrs, "el-spacer");
1655
+ const b = { id: this.id(id), type: "spacer", height: attrs.height };
1656
+ delete attrs.height;
1657
+ return this.finish(b, attrs, classes, path, node);
1658
+ }
1659
+ case "mj-raw": {
1660
+ if (isComment(node)) return { id: this.id(), type: "raw", html: node.content ?? "" };
1661
+ const social = /^\s*<table [^>]*data-ee-social="([A-Za-z0-9+/=]+)"/.exec(node.content ?? "");
1662
+ const decoded = decodeEditorData(social?.[1]);
1663
+ if (decoded && decoded.type === "social" && Array.isArray(decoded.links)) {
1664
+ return { ...decoded, id: this.id(decoded.id) };
1665
+ }
1666
+ const { id, classes } = this.identity(attrs, "el-raw");
1667
+ if (Object.keys(attrs).length > 0 || classes.length > 0) return null;
1668
+ return { id: this.id(id), type: "raw", html: node.content ?? "" };
1669
+ }
1670
+ case "mj-hero": {
1671
+ const { id, classes } = this.identity(attrs, "el-hero");
1672
+ if (!id || !attrs["background-url"]) return null;
1673
+ const b = { id: this.id(id), type: "hero", backgroundImage: attrs["background-url"] };
1674
+ delete attrs["background-url"];
1675
+ this.mapCommon(attrs, b, {
1676
+ "background-height": "backgroundHeight",
1677
+ "background-width": "backgroundWidth",
1678
+ "background-color": "backgroundColor"
1679
+ });
1680
+ this.mapEnum(attrs, b, "vertical-align", "verticalAlign", ["top", "middle", "bottom"]);
1681
+ this.mapEnum(attrs, b, "mode", "mode", ["fixed-height", "fluid-height"]);
1682
+ return this.finish(b, attrs, classes, path, node);
1683
+ }
1684
+ case "mj-accordion":
1685
+ return this.accordion(node, attrs, path);
1686
+ case "mj-navbar":
1687
+ return this.navbar(node, attrs, path);
1688
+ case "mj-carousel":
1689
+ return this.carousel(node, attrs, path);
1690
+ case "mj-table":
1691
+ return this.table(node, attrs, path);
1692
+ case "mj-wrapper": {
1693
+ const cls = (attrs["css-class"] ?? "").trim();
1694
+ if (cls === "el-header-wrapper") return { id: this.id(), type: "header", locked: true };
1695
+ if (cls === "el-footer-wrapper") return { id: this.id(), type: "footer", locked: true };
1696
+ return null;
1697
+ }
1698
+ default:
1699
+ return null;
1700
+ }
1701
+ }
1702
+ text(node, attrs, path) {
1703
+ const { id, classes } = this.identity(attrs, "el-text");
1704
+ const b = { id: this.id(id), type: "text", content: node.content ?? "" };
1705
+ this.mapEnum(attrs, b, "align", "align", ["left", "center", "right", "justify"]);
1706
+ this.mapCommon(attrs, b, { color: "color", "font-size": "fontSize", "font-family": "fontFamily", "line-height": "lineHeight" });
1707
+ this.mapPadding(attrs, b);
1708
+ const styles = [];
1709
+ if (b.align) styles.push(`text-align:${b.align}`);
1710
+ if (b.color) styles.push(`color:${b.color}`);
1711
+ if (b.fontSize) styles.push(`font-size:${b.fontSize}`);
1712
+ if (b.fontFamily) styles.push(`font-family:${b.fontFamily}`);
1713
+ if (b.lineHeight) styles.push(`line-height:${b.lineHeight}`);
1714
+ if (styles.length > 0) {
1715
+ const open = `<div style="${styles.join(";")}">`;
1716
+ if (b.content.startsWith(open) && b.content.endsWith("</div>")) {
1717
+ const inner = b.content.slice(open.length, -"</div>".length);
1718
+ if (!/<\/div>/i.test(inner) || balancedDivs(inner)) b.content = inner;
1719
+ }
1720
+ }
1721
+ return this.finish(b, attrs, classes, path, node);
1722
+ }
1723
+ accordion(node, attrs, path) {
1724
+ const items = [];
1725
+ for (const el of node.children) {
1726
+ if (isComment(el)) return null;
1727
+ if (el.tagName !== "mj-accordion-element" || Object.keys(el.attributes).length > 0) return null;
1728
+ const parts = el.children.filter((c) => !isComment(c));
1729
+ const title = parts.find((c) => c.tagName === "mj-accordion-title");
1730
+ const text = parts.find((c) => c.tagName === "mj-accordion-text");
1731
+ if (parts.length !== 2 || !title || !text || parts[0] !== title) return null;
1732
+ if (Object.keys(title.attributes).length > 0 || Object.keys(text.attributes).length > 0) return null;
1733
+ items.push({ title: title.content ?? "", content: text.content ?? "" });
1734
+ }
1735
+ const { id, classes } = this.identity(attrs, "el-accordion");
1736
+ const b = { id: this.id(id), type: "accordion", items };
1737
+ this.mapEnum(attrs, b, "icon-position", "iconPosition", ["left", "right"]);
1738
+ this.mapCommon(attrs, b, { border: "borderColor", "font-family": "fontFamily" });
1739
+ return this.finish(b, attrs, classes, path, node);
1740
+ }
1741
+ navbar(node, attrs, path) {
1742
+ const links = [];
1743
+ for (const el of node.children) {
1744
+ if (el.tagName !== "mj-navbar-link") return null;
1745
+ const { href, color, ...rest } = el.attributes;
1746
+ if (!href || Object.keys(rest).length > 0) return null;
1747
+ links.push({ href, label: el.content ?? "", ...color ? { color } : {} });
1748
+ }
1749
+ const { id, classes } = this.identity(attrs, "el-navbar");
1750
+ const b = { id: this.id(id), type: "navbar", links };
1751
+ if (attrs.hamburger === "hamburger") {
1752
+ b.hamburger = true;
1753
+ delete attrs.hamburger;
1754
+ }
1755
+ this.mapCommon(attrs, b, { "base-url": "baseUrl", "ico-color": "icoColor" });
1756
+ this.mapEnum(attrs, b, "align", "align", ["left", "center", "right"]);
1757
+ this.mapPadding(attrs, b);
1758
+ return this.finish(b, attrs, classes, path, node);
1759
+ }
1760
+ carousel(node, attrs, path) {
1761
+ const images = [];
1762
+ for (const el of node.children) {
1763
+ if (el.tagName !== "mj-carousel-image") return null;
1764
+ const { src, alt, href, "thumbnails-src": thumbnailSrc, ...rest } = el.attributes;
1765
+ if (!src || Object.keys(rest).length > 0) return null;
1766
+ images.push({ src, ...alt ? { alt } : {}, ...href ? { href } : {}, ...thumbnailSrc ? { thumbnailSrc } : {} });
1767
+ }
1768
+ const { id, classes } = this.identity(attrs, "el-carousel");
1769
+ const b = { id: this.id(id), type: "carousel", images };
1770
+ this.mapEnum(attrs, b, "thumbnails", "thumbnails", ["visible", "hidden"]);
1771
+ this.mapCommon(attrs, b, { "border-radius": "borderRadius", "icon-width": "iconWidth", "tb-border-radius": "tbBorderRadius" });
1772
+ this.mapPadding(attrs, b);
1773
+ return this.finish(b, attrs, classes, path, node);
1774
+ }
1775
+ /** Only the editor's own table (`el-table`), whose markup the compiler writes in one exact shape. */
1776
+ table(node, attrs, path) {
1777
+ const { id, classes } = this.identity(attrs, "el-table");
1778
+ if (!id) return null;
1779
+ const lines = (node.content ?? "").split("\n");
1780
+ const head = /^<tr style="background-color: #f5f5f5;">(.*)<\/tr>$/.exec(lines[0] ?? "");
1781
+ if (!head) return null;
1782
+ const cells = (row, tag, style) => {
1783
+ const out = [];
1784
+ const open = `<${tag} style="${style}">`;
1785
+ let rest = row;
1786
+ while (rest.length > 0) {
1787
+ if (!rest.startsWith(open)) return null;
1788
+ const close = rest.indexOf(`</${tag}>`);
1789
+ if (close < 0) return null;
1790
+ out.push(rest.slice(open.length, close));
1791
+ rest = rest.slice(close + tag.length + 3);
1792
+ }
1793
+ return out;
1794
+ };
1795
+ const headers = cells(head[1], "th", "padding: 8px; border-bottom: 1px solid #ddd; text-align: left;");
1796
+ if (!headers) return null;
1797
+ const rows = [];
1798
+ for (const line of lines.slice(1)) {
1799
+ const m = /^<tr>(.*)<\/tr>$/.exec(line);
1800
+ const row = m ? cells(m[1], "td", "padding: 8px; border-bottom: 1px solid #eee;") : null;
1801
+ if (!row) return null;
1802
+ rows.push(row);
1803
+ }
1804
+ const b = { id: this.id(id), type: "table", headers, rows };
1805
+ this.mapEnum(attrs, b, "align", "align", ["left", "center", "right"]);
1806
+ this.mapCommon(attrs, b, {
1807
+ color: "color",
1808
+ "font-family": "fontFamily",
1809
+ "font-size": "fontSize",
1810
+ cellpadding: "cellpadding",
1811
+ cellspacing: "cellspacing",
1812
+ border: "border"
1813
+ });
1814
+ this.mapPadding(attrs, b);
1815
+ return this.finish(b, attrs, classes, path, node);
1816
+ }
1817
+ // Attribute helpers
1818
+ mapCommon(attrs, target, map) {
1819
+ for (const [attr, field] of Object.entries(map)) {
1820
+ if (attrs[attr] === void 0) continue;
1821
+ target[field] = attrs[attr];
1822
+ delete attrs[attr];
1823
+ }
1824
+ }
1825
+ mapEnum(attrs, target, attr, field, allowed) {
1826
+ const v = attrs[attr];
1827
+ if (v !== void 0 && allowed.includes(v)) {
1828
+ target[field] = v;
1829
+ delete attrs[attr];
1830
+ }
1831
+ }
1832
+ mapPadding(attrs, target) {
1833
+ if (attrs.padding === void 0) return;
1834
+ const spacing = parsePadding(attrs.padding);
1835
+ if (spacing) {
1836
+ target.padding = spacing;
1837
+ delete attrs.padding;
1838
+ }
1839
+ }
1840
+ finish(block, attrs, classes, path, node) {
1841
+ const extra = this.extras(attrs, classes, path, node);
1842
+ if (extra) block.extraAttributes = extra;
1843
+ return block;
1844
+ }
1845
+ // Fallbacks: compile the whole source once, with each fallback marked, and cut them out.
1846
+ resolveFallbacks(metadata) {
1847
+ if (this.fallbacks.length === 0) return;
1848
+ const marker = (i, edge) => ({
1849
+ tagName: "mj-raw",
1850
+ attributes: {},
1851
+ content: `<!--ee-import-${i}-${edge}-->`,
1852
+ children: []
1853
+ });
1854
+ for (const [i, f] of this.fallbacks.entries()) {
1855
+ const at = f.parent.children.indexOf(f.node);
1856
+ f.parent.children.splice(at, 1, marker(i, "start"), f.node, marker(i, "end"));
1857
+ }
1858
+ let html = "";
1859
+ try {
1860
+ html = mjml2html3(serialize(this.root), { ignoreIncludes: true, validationLevel: "skip", minify: false, keepComments: true }).html;
1861
+ } catch {
1862
+ html = "";
1863
+ }
1864
+ const needed = [];
1865
+ for (const [i, f] of this.fallbacks.entries()) {
1866
+ const start = html.indexOf(`<!--ee-import-${i}-start-->`);
1867
+ const end = html.indexOf(`<!--ee-import-${i}-end-->`);
1868
+ let fragment = start >= 0 && end > start ? html.slice(start + `<!--ee-import-${i}-start-->`.length, end).trim() : "";
1869
+ if (f.unknown || fragment === "") {
1870
+ const source = serialize(f.node).replace(/--/g, "- -");
1871
+ fragment = `<!-- Imported MJML that renders nothing: ${source} -->`;
1872
+ }
1873
+ f.block.html = fragment;
1874
+ needed.push(fragment);
1875
+ }
1876
+ const css = supportingCss(html, needed.join("\n"), metadata.breakpoint);
1877
+ if (css) metadata.customCSS = metadata.customCSS ? `${metadata.customCSS}
1878
+ ${css}` : css;
1879
+ }
1880
+ summarize() {
1881
+ if (this.kept.size > 0) {
1882
+ const list = [...this.kept.entries()].sort((a, b) => b[1] - a[1]).map(([name, n]) => `${name} (${n})`).join(", ");
1883
+ this.warnings.push({
1884
+ severity: "info",
1885
+ code: "attribute_kept",
1886
+ path: "mj-body",
1887
+ message: `Attributes the editor has no control for are kept and apply to the mail as before: ${list}. The editor canvas may not show their effect.`
1888
+ });
1889
+ }
1890
+ if (this.hasOwnDefaults || this.usesMjClass) {
1891
+ this.warnings.push({
1892
+ severity: "info",
1893
+ code: "document_defaults",
1894
+ path: "mj-head > mj-attributes",
1895
+ message: "The document-wide defaults (mj-attributes, mj-class) are kept and apply to the mail. The editor canvas shows blocks without them, so the preview is the reference for how the mail looks."
1896
+ });
1897
+ }
1898
+ }
1899
+ };
1900
+ function balancedDivs(html) {
1901
+ let depth = 0;
1902
+ for (const m of html.matchAll(/<(\/?)div\b[^>]*>/gi)) {
1903
+ depth += m[1] ? -1 : 1;
1904
+ if (depth < 0) return false;
1905
+ }
1906
+ return depth === 0;
1907
+ }
1908
+ function supportingCss(fullHtml, fragments, breakpoint = "480px") {
1909
+ const out = [];
1910
+ const classes = new Set([...fragments.matchAll(/mj-column-(?:per|px)-[0-9-]+/g)].map((m) => m[0]));
1911
+ const rules = [];
1912
+ for (const cls of classes) {
1913
+ const m = new RegExp(`\\.${cls}\\s*\\{[^}]*\\}`).exec(fullHtml);
1914
+ if (m) rules.push(m[0]);
1915
+ }
1916
+ if (rules.length > 0) out.push(`@media only screen and (min-width:${breakpoint}) { ${rules.join(" ")} }`);
1917
+ const styles = [...fullHtml.matchAll(/<style type="text\/css">([\s\S]*?)<\/style>/g)].map((m) => m[1]);
1918
+ for (const token of ["mj-accordion", "mj-carousel", "mj-menu"]) {
1919
+ if (!fragments.includes(token)) continue;
1920
+ for (const s of styles) if (s.includes(token) && !out.includes(s.trim())) out.push(s.trim());
1921
+ }
1922
+ return out.join("\n");
1923
+ }
1924
+ function importMjml(source) {
1925
+ if (typeof source !== "string") throw new MjmlImportError("not_mjml", "The MJML must be a string.");
1926
+ scanMjml(source, ENDING_TAGS);
1927
+ const root = parseMjml(source);
1928
+ if (root.tagName !== "mjml") throw new MjmlImportError("not_mjml", "The document must start with <mjml>.");
1929
+ const head = root.children.find((c) => c.tagName === "mj-head");
1930
+ const body = root.children.find((c) => c.tagName === "mj-body");
1931
+ if (!body) throw new MjmlImportError("not_mjml", "The document has no <mj-body>.");
1932
+ const importer = new Importer(root);
1933
+ for (const [i, c] of root.children.entries()) {
1934
+ if (c !== head && c !== body && !isComment(c)) {
1935
+ importer.warn("stray_text", "info", `mjml > ${c.tagName}[${i + 1}]`, c, `<${c.tagName}> outside mj-head and mj-body is ignored by MJML, and by the import.`, true);
1936
+ }
1937
+ }
1938
+ const metadata = importer.head(head, body);
1939
+ const sections = importer.body(body);
1940
+ importer.resolveFallbacks(metadata);
1941
+ importer.summarize();
1942
+ const document = { version: CURRENT_TEMPLATE_VERSION, metadata, sections };
1943
+ try {
1944
+ migrateTemplate(document);
1945
+ } catch (err) {
1946
+ const detail = isTemplateMigrationError(err) ? err.message : String(err);
1947
+ throw new MjmlImportError("invalid_document", `The imported document does not pass the editor's schema: ${detail}`);
1948
+ }
1949
+ return { document, warnings: importer.warnings };
1950
+ }
1951
+ export {
1952
+ DEFAULT_MJML_ATTRIBUTES,
1953
+ EDITOR_DATA_ATTRIBUTE,
1954
+ MAX_MJML_BYTES,
1955
+ MAX_MJML_DEPTH,
1956
+ MAX_MJML_ELEMENTS,
1957
+ MJMLCompiler,
1958
+ MJMLExporter,
1959
+ MjmlImportError,
1960
+ createMJMLCompiler,
1961
+ createMJMLExporter,
1962
+ encodeEditorData,
1963
+ exportTemplate,
1964
+ importMjml,
1965
+ isMjmlImportError
1966
+ };