@templatical/import-topol 0.64.0 → 0.64.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { BUTTON_BLOCK_DEFAULTS, BUTTON_LINE_HEIGHT, COLUMN_LAYOUT_PERCENTS, DEFAULT_TEMPLATE_DEFAULTS, canonicalFontStack, columnWidthsIssue, createButtonBlock, createDefaultTemplateContent, createDividerBlock, createHtmlBlock, createImageBlock, createParagraphBlock, createSectionBlock, createSocialIconsBlock, createSpacerBlock, createTitleBlock, findOpenTagEnd, generateId, isLocaleTag, roundHundredths, sectionColumnPercents, sourceHash } from "@templatical/types";
1
+ import { BUTTON_BLOCK_DEFAULTS, BUTTON_LINE_HEIGHT, COLUMN_LAYOUT_PERCENTS, DEFAULT_TEMPLATE_DEFAULTS, canonicalFontStack, columnWidthsIssue, createButtonBlock, createDefaultTemplateContent, createDividerBlock, createHtmlBlock, createImageBlock, createParagraphBlock, createSectionBlock, createSocialIconsBlock, createSpacerBlock, createTitleBlock, findOpenTagEnd, generateId, getTagAttrValue, isLocaleTag, roundHundredths, sectionColumnPercents, sourceHash } from "@templatical/types";
2
2
  // src/localization.ts
3
3
  const seenWarnings = /* @__PURE__ */ new WeakMap();
4
4
  function warn(warnings, message) {
@@ -135,8 +135,15 @@ function rgbToHex(r, g, b) {
135
135
  const hex = (n) => clamp(n).toString(16).padStart(2, "0");
136
136
  return `#${hex(r)}${hex(g)}${hex(b)}`;
137
137
  }
138
+ const RGB_COLOR = /^rgb(a?)\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)$/;
139
+ /** Use the same parsed alpha for transparent button fills as for colors. */
140
+ function isZeroAlphaRgba(value) {
141
+ const rgb = RGB_COLOR.exec(value?.trim().toLowerCase() ?? "");
142
+ return rgb !== null && rgb[1] === "a" && rgb[5] !== void 0 && Number(rgb[5]) === 0;
143
+ }
138
144
  /**
139
- * Normalize a colour to 6-digit lowercase hex.
145
+ * Normalize an opaque colour to 6-digit lowercase hex. A partly transparent
146
+ * rgba() value stays in CSS form so its alpha is not lost.
140
147
  *
141
148
  * Returns `""` for transparent/inherit/none and for anything unrecognised —
142
149
  * the empty string is the block model's "unset", which the colour pickers
@@ -151,9 +158,15 @@ function parseColor(value) {
151
158
  const [, r, g, b] = trimmed;
152
159
  return `#${r}${r}${g}${g}${b}${b}`;
153
160
  }
154
- const rgb = trimmed.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+\s*)?\)$/);
155
- if (rgb) return rgbToHex(+rgb[1], +rgb[2], +rgb[3]);
156
- return NAMED_COLORS[trimmed] ?? "";
161
+ const rgb = RGB_COLOR.exec(trimmed);
162
+ if (rgb) {
163
+ const alpha = rgb[5] === void 0 ? 1 : Number(rgb[5]);
164
+ if (!Number.isFinite(alpha)) return "";
165
+ if (rgb[1] === "a" && alpha === 0) return "";
166
+ if (rgb[1] === "a" && alpha > 0 && alpha < 1) return trimmed;
167
+ return rgbToHex(+rgb[2], +rgb[3], +rgb[4]);
168
+ }
169
+ return Object.hasOwn(NAMED_COLORS, trimmed) ? NAMED_COLORS[trimmed] : "";
157
170
  }
158
171
  function expandShorthand(value) {
159
172
  if (!value) return {
@@ -424,11 +437,40 @@ function readMjmlBackgroundImage(read, label, boxWidth) {
424
437
  // src/content-inference.ts
425
438
  /**
426
439
  * A single heading element wrapping the whole content, captured with its level
427
- * and inner markup. Anchored at both ends so a heading with a sibling does not
428
- * match — that case is a paragraph.
440
+ * and inner markup. Anchored at both ends, so a fragment that ends on a
441
+ * different tag does not match. The inner group is greedy, so two headings of
442
+ * the same level still match and the first close sits inside that group. The
443
+ * match is a title only when the inner HTML has no earlier real close of this
444
+ * level: one heading with inline markup stays a title, and a sibling heading
445
+ * stays a paragraph.
429
446
  */
430
- const SOLE_HEADING = /^<h([1-6])(?:\s[^>]*)?>([\s\S]*)<\/h\1>$/i;
447
+ const SOLE_HEADING = /^<h([1-6])(?:\s[^>]*)?>([\s\S]*)<\/h\1\s*>$/i;
431
448
  const BLOCK_ROOT = /^<(p|h[1-6]|ul|ol|blockquote|div|table)\b/i;
449
+ const HEADING_CLOSE = /^<\/h([1-6])\s*>$/i;
450
+ /** Ignore comments and quoted attribute values while finding an earlier heading close. */
451
+ function hasEarlierHeadingClose(html, level) {
452
+ let cursor = 0;
453
+ while (cursor < html.length) {
454
+ const open = html.indexOf("<", cursor);
455
+ if (open === -1) return false;
456
+ if (html.startsWith("<!--", open)) {
457
+ const end = html.indexOf("-->", open + 4);
458
+ if (end === -1) return false;
459
+ cursor = end + 3;
460
+ continue;
461
+ }
462
+ const next = html.charCodeAt(open + 1);
463
+ if (next !== 47 && next !== 33 && !(next >= 65 && next <= 90) && !(next >= 97 && next <= 122)) {
464
+ cursor = open + 1;
465
+ continue;
466
+ }
467
+ const end = findOpenTagEnd(html, open + 1);
468
+ if (end === -1) return false;
469
+ if (HEADING_CLOSE.exec(html.slice(open, end + 1))?.[1] === level) return true;
470
+ cursor = end + 1;
471
+ }
472
+ return false;
473
+ }
432
474
  /**
433
475
  * Resolve a Topol `content` string to a Title or a Paragraph.
434
476
  *
@@ -444,7 +486,7 @@ function inferTextBlock(content) {
444
486
  html: "<p></p>"
445
487
  };
446
488
  const heading = trimmed.match(SOLE_HEADING);
447
- if (heading) {
489
+ if (heading?.[1] && !hasEarlierHeadingClose(heading[2], heading[1])) {
448
490
  const source = Number(heading[1]);
449
491
  return {
450
492
  kind: "title",
@@ -468,6 +510,24 @@ const ENTITIES = {
468
510
  "&nbsp;": " "
469
511
  };
470
512
  /**
513
+ * Named references Topol emits, plus a decimal (`&#38;`) or hex (`&#x26;`,
514
+ * `&#X26;`) numeric reference. A code point that is not a Unicode scalar —
515
+ * zero, a surrogate, or past U+10FFFF — stays literal text, because
516
+ * `String.fromCodePoint` throws on those and would abort the import. One
517
+ * pass, and only the names above: `&#38;lt;` becomes the text `&lt;`, and
518
+ * `&copy;` is left as written.
519
+ */
520
+ const TEXT_ENTITY = /&(?:amp|lt|gt|quot|#39|apos|nbsp|#[0-9]+|#[xX][0-9a-fA-F]+);/g;
521
+ function decodeTextEntity(match) {
522
+ const named = ENTITIES[match];
523
+ if (named !== void 0) return named;
524
+ const body = match.slice(1, -1);
525
+ const hex = body[1] === "x" || body[1] === "X";
526
+ const code = Number.parseInt(body.slice(hex ? 2 : 1), hex ? 16 : 10);
527
+ if (code < 1 || code > 1114111 || code >= 55296 && code <= 57343) return match;
528
+ return String.fromCodePoint(code);
529
+ }
530
+ /**
471
531
  * Remove every `<tag>` from `html`, keeping the text between them.
472
532
  *
473
533
  * A single-pass linear scan rather than `/<[^>]*>/g`: that regex is
@@ -508,7 +568,7 @@ function removeTags(html) {
508
568
  */
509
569
  function stripTags(html) {
510
570
  if (!html) return "";
511
- return removeTags(html).replace(/&(?:amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => ENTITIES[m] ?? m).replace(/\s+/g, " ").trim();
571
+ return removeTags(html).replace(TEXT_ENTITY, decodeTextEntity).replace(/\s+/g, " ").trim();
512
572
  }
513
573
  // src/global-style.ts
514
574
  /**
@@ -595,43 +655,252 @@ function resolved(node, key, ctx, selector) {
595
655
  * button's whole row in its fill colour. `buildSection` reads
596
656
  * `background-color` itself, since on `mj-section` it is the section's fill.
597
657
  */
598
- function baseStyles(node) {
658
+ function baseStyles(node, ctx) {
599
659
  const backgroundColor = parseColor(attr(node, "container-background-color"));
660
+ const localPadding = attr(node, "padding");
661
+ const side = (name) => attr(node, name) ?? tagDefault(ctx.style, node.tagName, name);
600
662
  return { styles: {
601
- padding: parsePadding(node),
663
+ padding: parsePadding({
664
+ tagName: node.tagName,
665
+ attributes: {
666
+ padding: localPadding ?? tagDefault(ctx.style, node.tagName, "padding"),
667
+ "padding-top": side("padding-top"),
668
+ "padding-right": side("padding-right"),
669
+ "padding-bottom": side("padding-bottom"),
670
+ "padding-left": side("padding-left")
671
+ }
672
+ }),
602
673
  ...backgroundColor ? { backgroundColor } : {}
603
674
  } };
604
675
  }
676
+ function readTextAlignment(node) {
677
+ const raw = attr(node, "align");
678
+ if (raw === void 0) return { value: void 0 };
679
+ const value = raw.trim().toLowerCase();
680
+ if (value === "left" || value === "center" || value === "right" || value === "justify") return { value };
681
+ return {
682
+ value: "left",
683
+ note: `Text alignment "${raw}" imported as left.`
684
+ };
685
+ }
686
+ const ALIGNABLE_TAGS = /* @__PURE__ */ new Set([
687
+ "p",
688
+ "h1",
689
+ "h2",
690
+ "h3",
691
+ "h4",
692
+ "h5",
693
+ "h6",
694
+ "li",
695
+ "ul",
696
+ "ol",
697
+ "div",
698
+ "blockquote",
699
+ "table",
700
+ "td",
701
+ "th"
702
+ ]);
703
+ const VOID_TAGS = /* @__PURE__ */ new Set([
704
+ "area",
705
+ "base",
706
+ "br",
707
+ "col",
708
+ "embed",
709
+ "hr",
710
+ "img",
711
+ "input",
712
+ "link",
713
+ "meta",
714
+ "param",
715
+ "source",
716
+ "track",
717
+ "wbr"
718
+ ]);
719
+ const COLOR_DECLARATION = /(?:^|;)\s*color\s*:/i;
720
+ const ALIGN_DECLARATION = /(?:^|;)\s*text-align\s*:/i;
721
+ /** Merge tags are text even when their expressions contain markup-like `<`. */
722
+ function nextMarkupOpen(html, from) {
723
+ let at = from;
724
+ while (at < html.length) {
725
+ if (html[at] === "{") {
726
+ const marker = html[at + 1];
727
+ const close = marker === "{" ? "}}" : marker === "%" ? "%}" : marker === "#" ? "#}" : null;
728
+ if (close !== null) {
729
+ const end = html.indexOf(close, at + 2);
730
+ if (end === -1) return -1;
731
+ at = end + 2;
732
+ continue;
733
+ }
734
+ }
735
+ if (html[at] !== "<") {
736
+ at++;
737
+ continue;
738
+ }
739
+ const next = html[at + 1];
740
+ const code = html.charCodeAt(at + 1);
741
+ if (next === "/" || next === "!" || code >= 65 && code <= 90 || code >= 97 && code <= 122) return at;
742
+ at++;
743
+ }
744
+ return -1;
745
+ }
746
+ /** Locate the first real style value, skipping quoted values of other attributes. */
747
+ function styleValueEnd(tag, from) {
748
+ const limit = tag.length - 1;
749
+ let i = from;
750
+ while (i < limit) {
751
+ while (i < limit && /[\s/]/.test(tag[i])) i++;
752
+ const nameStart = i;
753
+ while (i < limit && !/[\s=/>]/.test(tag[i])) i++;
754
+ const name = tag.slice(nameStart, i).toLowerCase();
755
+ while (i < limit && /\s/.test(tag[i])) i++;
756
+ if (tag[i] !== "=") continue;
757
+ i++;
758
+ while (i < limit && /\s/.test(tag[i])) i++;
759
+ const quote = tag[i];
760
+ if (quote === "\"" || quote === "'") {
761
+ const end = tag.indexOf(quote, i + 1);
762
+ if (name === "style") return end;
763
+ i = end + 1;
764
+ } else {
765
+ while (i < limit && !/[\s>]/.test(tag[i])) i++;
766
+ if (name === "style") return i;
767
+ }
768
+ }
769
+ return null;
770
+ }
771
+ /**
772
+ * Whether an opening tag's attributes include `href`, with or without a value
773
+ * (`<a href>` counts). Attribute names are read with their values skipped,
774
+ * quoted or not, so `title="href"` and `title= href` don't match. One pass.
775
+ */
776
+ function hasHrefAttribute(attrs) {
777
+ let i = 0;
778
+ const isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
779
+ while (i < attrs.length) {
780
+ while (i < attrs.length && (isSpace(attrs[i]) || attrs[i] === "/")) i++;
781
+ const nameStart = i;
782
+ while (i < attrs.length && !isSpace(attrs[i]) && attrs[i] !== "=" && attrs[i] !== "/") i++;
783
+ if (attrs.slice(nameStart, i).toLowerCase() === "href") return true;
784
+ while (i < attrs.length && isSpace(attrs[i])) i++;
785
+ if (attrs[i] !== "=") continue;
786
+ i++;
787
+ while (i < attrs.length && isSpace(attrs[i])) i++;
788
+ const quote = attrs[i];
789
+ if (quote === "\"" || quote === "'") {
790
+ i++;
791
+ while (i < attrs.length && attrs[i] !== quote) i++;
792
+ i++;
793
+ } else while (i < attrs.length && !isSpace(attrs[i])) i++;
794
+ }
795
+ return false;
796
+ }
797
+ /** Preserve existing inline declarations while writing Topol's text defaults onto editable nodes. */
798
+ function paragraphHtmlStyles(html, color, align, lossyAlignmentTags) {
799
+ if (!color && align === void 0) return html;
800
+ const parts = [];
801
+ const stack = [];
802
+ let cursor = 0;
803
+ let colored = false;
804
+ let aligned = false;
805
+ while (cursor < html.length) {
806
+ const open = nextMarkupOpen(html, cursor);
807
+ const textEnd = open === -1 ? html.length : open;
808
+ const run = html.slice(cursor, textEnd);
809
+ parts.push(color && !colored && run.trim() ? `<span style="color:${color}">${run}</span>` : run);
810
+ if (open === -1) break;
811
+ const terminator = html.startsWith("<!--", open) ? "-->" : html.startsWith("<![CDATA[", open) ? "]]>" : null;
812
+ if (terminator !== null) {
813
+ const markerEnd = html.indexOf(terminator, open + (terminator === "-->" ? 4 : 9));
814
+ if (markerEnd === -1) {
815
+ parts.push(html.slice(open));
816
+ break;
817
+ }
818
+ parts.push(html.slice(open, markerEnd + 3));
819
+ cursor = markerEnd + 3;
820
+ continue;
821
+ }
822
+ const end = findOpenTagEnd(html, open + 1);
823
+ if (end === -1) {
824
+ parts.push(html.slice(open));
825
+ break;
826
+ }
827
+ const tag = html.slice(open, end + 1);
828
+ const close = /^<\/([a-z][a-z0-9-]*)\s*>$/i.exec(tag);
829
+ if (close) {
830
+ parts.push(tag);
831
+ if (stack.at(-1)?.name === close[1].toLowerCase()) stack.pop();
832
+ colored = stack.at(-1)?.colored ?? false;
833
+ aligned = stack.at(-1)?.aligned ?? false;
834
+ } else {
835
+ const start = /^<([a-z][a-z0-9-]*)\b/i.exec(tag);
836
+ if (start) {
837
+ const name = start[1].toLowerCase();
838
+ const declarations = getTagAttrValue(tag.slice(start[0].length, -1), "style") ?? "";
839
+ if (align !== void 0 && ALIGNABLE_TAGS.has(name) && !aligned && !ALIGN_DECLARATION.test(declarations)) {
840
+ const insertion = `${declarations && !declarations.endsWith(";") ? ";" : ""}text-align:${align}`;
841
+ const at = styleValueEnd(tag, start[0].length);
842
+ if (at !== null) parts.push(tag.slice(0, at), insertion, tag.slice(at));
843
+ else parts.push(tag.slice(0, -1), ` style="${insertion}">`);
844
+ if (name !== "p" && !/^h[1-6]$/.test(name)) lossyAlignmentTags.add(name);
845
+ } else parts.push(tag);
846
+ if (!VOID_TAGS.has(name) && !/\/\s*>$/.test(tag)) {
847
+ const hyperlink = name === "a" && hasHrefAttribute(tag.slice(start[0].length, -1));
848
+ colored = colored || hyperlink || COLOR_DECLARATION.test(declarations);
849
+ aligned = aligned || ALIGN_DECLARATION.test(declarations);
850
+ stack.push({
851
+ name,
852
+ colored,
853
+ aligned
854
+ });
855
+ }
856
+ } else parts.push(tag);
857
+ }
858
+ cursor = end + 1;
859
+ }
860
+ return parts.join("");
861
+ }
605
862
  function convertText(node, ctx) {
606
863
  const inferred = inferTextBlock(node.content);
607
- if (inferred.kind === "paragraph") return {
608
- block: createParagraphBlock({
609
- content: inferred.html,
610
- ...baseStyles(node)
611
- }),
612
- entry: {
613
- sourceTag: "mj-text",
614
- templaticalBlockType: "paragraph",
615
- status: "converted"
616
- }
617
- };
864
+ const alignment = readTextAlignment(node);
865
+ if (inferred.kind === "paragraph") {
866
+ const color = parseColor(resolved(node, "color", ctx));
867
+ const lossyAlignmentTags = /* @__PURE__ */ new Set();
868
+ const content = paragraphHtmlStyles(inferred.html, color, alignment.value, lossyAlignmentTags);
869
+ const lossyAlignmentNote = lossyAlignmentTags.size ? `Node alignment on ${[...lossyAlignmentTags].map((tag) => `<${tag}>`).join(", ")} is lost after the first editor edit; the paragraph editor keeps alignment only on paragraphs.` : void 0;
870
+ const notes = [alignment.note, lossyAlignmentNote].filter((note) => note !== void 0);
871
+ return {
872
+ block: createParagraphBlock({
873
+ content,
874
+ ...baseStyles(node, ctx)
875
+ }),
876
+ entry: {
877
+ sourceTag: "mj-text",
878
+ templaticalBlockType: "paragraph",
879
+ status: notes.length ? "approximated" : "converted",
880
+ ...notes.length ? { note: notes.join(" ") } : {}
881
+ }
882
+ };
883
+ }
618
884
  const selector = `h${inferred.level}`;
619
885
  const color = parseColor(resolved(node, "color", ctx, selector));
620
886
  const fontFamily = canonicalFontStack(resolved(node, "font-family", ctx, selector));
887
+ const titleAlignment = alignment.value === "justify" ? "left" : alignment.value ?? "left";
888
+ const titleAlignmentNote = alignment.value === "justify" ? "Title alignment \"justify\" imported as left — titles support left, center and right." : alignment.note;
889
+ const notes = [...inferred.clampedFrom ? [`Heading level h${inferred.clampedFrom} clamped to 4 — Templatical titles support h1-h4.`] : [], ...titleAlignmentNote ? [titleAlignmentNote] : []];
621
890
  return {
622
891
  block: createTitleBlock({
623
892
  content: inferred.inner,
624
893
  level: inferred.level,
625
- textAlign: parseAlignment(attr(node, "align"), "left"),
894
+ textAlign: titleAlignment,
626
895
  ...color ? { color } : {},
627
896
  ...fontFamily ? { fontFamily } : {},
628
- ...baseStyles(node)
897
+ ...baseStyles(node, ctx)
629
898
  }),
630
899
  entry: {
631
900
  sourceTag: "mj-text",
632
901
  templaticalBlockType: "title",
633
- status: inferred.clampedFrom ? "approximated" : "converted",
634
- ...inferred.clampedFrom ? { note: `Heading level h${inferred.clampedFrom} clamped to 4 — Templatical titles support h1-h4.` } : {}
902
+ status: notes.length ? "approximated" : "converted",
903
+ ...notes.length ? { note: notes.join(" ") } : {}
635
904
  }
636
905
  };
637
906
  }
@@ -666,7 +935,9 @@ function readButtonLineHeight(value, fontSize, notes) {
666
935
  function convertButton(node, ctx) {
667
936
  const text = stripTags(node.content);
668
937
  if (!text) return null;
669
- const backgroundColor = parseColor(resolved(node, "background-color", ctx, "button"));
938
+ const rawBackground = resolved(node, "background-color", ctx, "button");
939
+ const backgroundColor = parseColor(rawBackground);
940
+ const transparentFill = rawBackground?.trim().toLowerCase() === "transparent" || isZeroAlphaRgba(rawBackground);
670
941
  const textColor = parseColor(resolved(node, "color", ctx, "button"));
671
942
  const fontFamily = canonicalFontStack(resolved(node, "font-family", ctx, "button"));
672
943
  const factorySize = Number(BUTTON_BLOCK_DEFAULTS.fontSize);
@@ -681,14 +952,14 @@ function convertButton(node, ctx) {
681
952
  block: createButtonBlock({
682
953
  text,
683
954
  url: attr(node, "href") ?? "",
684
- ...backgroundColor ? { backgroundColor } : {},
955
+ ...transparentFill ? { backgroundColor: "transparent" } : backgroundColor ? { backgroundColor } : {},
685
956
  ...textColor ? { textColor } : {},
686
957
  ...fontFamily ? { fontFamily } : {},
687
958
  ...fontSize !== void 0 ? { fontSize } : {},
688
959
  ...lineHeight !== void 0 ? { lineHeight } : {},
689
960
  ...radiusRaw === void 0 ? {} : { borderRadius: parsePxValue(radiusRaw) },
690
961
  align: parseAlignment(attr(node, "align"), "center"),
691
- ...baseStyles(node)
962
+ ...baseStyles(node, ctx)
692
963
  }),
693
964
  entry: {
694
965
  sourceTag: node.tagName,
@@ -704,7 +975,7 @@ function convertImage(node, ctx, sourceTag) {
704
975
  const widthPercent = numAttr(node, "widthPercent");
705
976
  const pxWidth = numAttr(node, "width");
706
977
  const href = attr(node, "href");
707
- const base = baseStyles(node);
978
+ const base = baseStyles(node, ctx);
708
979
  const room = ctx.columnWidth - base.styles.padding.left - base.styles.padding.right;
709
980
  const width = widthPercent === 100 || pxWidth === void 0 || pxWidth >= room ? "full" : Math.round(pxWidth);
710
981
  const isGif = sourceTag === "mj-gif";
@@ -725,12 +996,12 @@ function convertImage(node, ctx, sourceTag) {
725
996
  }
726
997
  };
727
998
  }
728
- function convertSpacer(node) {
999
+ function convertSpacer(node, ctx) {
729
1000
  const height = attr(node, "height");
730
1001
  return {
731
1002
  block: createSpacerBlock({
732
1003
  ...height === void 0 ? {} : { height: parsePxValue(height) },
733
- ...baseStyles(node)
1004
+ ...baseStyles(node, ctx)
734
1005
  }),
735
1006
  entry: {
736
1007
  sourceTag: "mj-spacer",
@@ -739,7 +1010,7 @@ function convertSpacer(node) {
739
1010
  }
740
1011
  };
741
1012
  }
742
- function convertDivider(node) {
1013
+ function convertDivider(node, ctx) {
743
1014
  const color = parseColor(attr(node, "border-color"));
744
1015
  const thickness = attr(node, "border-width");
745
1016
  return {
@@ -747,7 +1018,7 @@ function convertDivider(node) {
747
1018
  lineStyle: parseBorderStyle(attr(node, "border-style")),
748
1019
  ...color ? { color } : {},
749
1020
  ...thickness === void 0 ? {} : { thickness: parsePxValue(thickness) },
750
- ...baseStyles(node)
1021
+ ...baseStyles(node, ctx)
751
1022
  }),
752
1023
  entry: {
753
1024
  sourceTag: "mj-divider",
@@ -769,12 +1040,12 @@ function convertLeaf(node, ctx) {
769
1040
  case "mj-button": return convertButton(node, ctx);
770
1041
  case "mj-image": return convertImage(node, ctx, "mj-image");
771
1042
  case "mj-gif": return convertImage(node, ctx, "mj-gif");
772
- case "mj-spacer": return convertSpacer(node);
773
- case "mj-divider": return convertDivider(node);
1043
+ case "mj-spacer": return convertSpacer(node, ctx);
1044
+ case "mj-divider": return convertDivider(node, ctx);
774
1045
  default: return {
775
1046
  block: createHtmlBlock({
776
1047
  content: JSON.stringify(node),
777
- ...baseStyles(node)
1048
+ ...baseStyles(node, ctx)
778
1049
  }),
779
1050
  entry: {
780
1051
  sourceTag: node.tagName,
@@ -834,8 +1105,8 @@ const STYLE_ALIASES = { outlinedbw: {
834
1105
  function normalizePlatform(raw) {
835
1106
  const cleaned = raw.trim().toLowerCase();
836
1107
  if (!cleaned) return null;
837
- if (ALIASES[cleaned]) return ALIASES[cleaned];
838
- return cleaned in KNOWN_PLATFORMS ? cleaned : null;
1108
+ if (Object.hasOwn(ALIASES, cleaned)) return ALIASES[cleaned];
1109
+ return Object.hasOwn(KNOWN_PLATFORMS, cleaned) ? cleaned : null;
839
1110
  }
840
1111
  function nearestSize(px) {
841
1112
  let best = ICON_SIZES[1];
@@ -857,7 +1128,7 @@ function styleFromBaseUrl(baseUrl) {
857
1128
  if (!baseUrl) return void 0;
858
1129
  const segment = baseUrl.split("?")[0].split("/").filter(Boolean).at(-1) ?? "";
859
1130
  if (KNOWN_STYLES.has(segment)) return { style: segment };
860
- return STYLE_ALIASES[segment];
1131
+ return Object.hasOwn(STYLE_ALIASES, segment) ? STYLE_ALIASES[segment] : void 0;
861
1132
  }
862
1133
  /**
863
1134
  * Convert Topol's MJML v3 social block.
@@ -910,7 +1181,7 @@ function convertSocial(node, _ctx) {
910
1181
  ...iconSize ? { iconSize } : {},
911
1182
  ...fromBaseUrl ? { iconStyle: fromBaseUrl.style } : {},
912
1183
  ...fromBaseUrl?.tone ? { iconTone: fromBaseUrl.tone } : {},
913
- ...baseStyles(node)
1184
+ ...baseStyles(node, _ctx)
914
1185
  }),
915
1186
  entry: {
916
1187
  sourceTag: "mj-social",
@@ -941,6 +1212,12 @@ const WIDTH_TOLERANCE = 2;
941
1212
  * are that preset.
942
1213
  */
943
1214
  const SCALED_TOLERANCE = .01 + 1e-9;
1215
+ /** Half a point. A float sum of shares that already are 100 still fills the row. */
1216
+ const TOTAL_SLACK = .5;
1217
+ function totalsFullWidth(percents) {
1218
+ const total = percents.reduce((sum, share) => sum + share, 0);
1219
+ return Math.abs(total - 100) <= TOTAL_SLACK;
1220
+ }
944
1221
  function evenLayout(count) {
945
1222
  if (count === 3) return "3";
946
1223
  if (count === 4) return "4";
@@ -1000,17 +1277,19 @@ function columnPixels(layout, container, columnWidths) {
1000
1277
  * Resolve `mj-column` widths, as percentages of the section's inner box, to
1001
1278
  * a layout. Topol renders through MJML, so MJML's rules apply.
1002
1279
  *
1003
- * A width list within `WIDTH_TOLERANCE` of a preset keeps that preset. An
1004
- * absent width is `mj-column`'s default, the parent width divided by the
1005
- * column count, whatever its siblings state, so a row with no widths is
1006
- * the even preset. One column is `"1"`: exact at 100%, approximated
1007
- * otherwise. Two, three or four columns that fit no preset are scaled to
1008
- * 100: scaled shares equal to a preset keep that preset, any others keep
1009
- * the even preset of that count plus `columnWidths`. Either is exact when
1010
- * the widths already total 100 within half a point; otherwise scaling
1011
- * changed the source layout. A width that cannot be stored (not above 0)
1012
- * keeps the even preset, approximated. Five or more columns fold onto
1013
- * `"4"`, approximated.
1280
+ * A width list within `WIDTH_TOLERANCE` of a preset keeps that preset,
1281
+ * exact only when those widths already total 100 within half a point. A
1282
+ * near preset that does not fill the row is approximated, because the
1283
+ * preset still changes the column sizes. An absent width is `mj-column`'s
1284
+ * default, the parent width divided by the column count, whatever its
1285
+ * siblings state, so a row with no widths is the even preset. One column
1286
+ * is `"1"`: exact at 100%, approximated otherwise. Two, three or four
1287
+ * columns that fit no preset are scaled to 100: scaled shares equal to a
1288
+ * preset keep that preset, any others keep the even preset of that count
1289
+ * plus `columnWidths`. The scaled row uses the same total check;
1290
+ * otherwise scaling changed the source layout. A width that cannot be
1291
+ * stored (not above 0) keeps the even preset, approximated. Five or more
1292
+ * columns fold onto `"4"`, approximated.
1014
1293
  */
1015
1294
  function matchColumnLayout(percents) {
1016
1295
  const count = percents.length;
@@ -1026,7 +1305,7 @@ function matchColumnLayout(percents) {
1026
1305
  const preset = presetWithin(resolved, WIDTH_TOLERANCE);
1027
1306
  if (preset) return {
1028
1307
  layout: preset,
1029
- exact: true
1308
+ exact: totalsFullWidth(resolved)
1030
1309
  };
1031
1310
  if (count === 1) return {
1032
1311
  layout: "1",
@@ -1040,8 +1319,7 @@ function matchColumnLayout(percents) {
1040
1319
  layout,
1041
1320
  exact: false
1042
1321
  };
1043
- const total = resolved.reduce((sum, share) => sum + share, 0);
1044
- const exact = Math.abs(total - 100) <= .5;
1322
+ const exact = totalsFullWidth(resolved);
1045
1323
  const scaled = sectionColumnPercents({
1046
1324
  columns: layout,
1047
1325
  columnWidths: resolved
@@ -1179,7 +1457,8 @@ function convertTopolTemplate(design, options = {}) {
1179
1457
  const style = readGlobalStyle(topolDesign, container, warnings);
1180
1458
  const languages = topolDesign.langs ?? [];
1181
1459
  const primary = languages.find((language) => language.primary) ?? languages[0];
1182
- style.settings.locale = (primary ? localeTag(primary.key, warnings) : null) ?? defaultLocaleOption(options.defaultLocale, warnings) ?? "en";
1460
+ const sourcePrimaryLocale = primary ? localeTag(primary.key, warnings) : null;
1461
+ style.settings.locale = sourcePrimaryLocale ?? defaultLocaleOption(options.defaultLocale, warnings) ?? "en";
1183
1462
  const uidMap = /* @__PURE__ */ new Map();
1184
1463
  const ctx = {
1185
1464
  uidMap,
@@ -1198,7 +1477,15 @@ function convertTopolTemplate(design, options = {}) {
1198
1477
  };
1199
1478
  const preview = primary?.translations?.["mj-preview"]?.content;
1200
1479
  if (typeof preview === "string") content.settings.preheaderText = preview;
1201
- for (const language of languages) {
1480
+ let languageOrder = languages;
1481
+ if (sourcePrimaryLocale === null) {
1482
+ const fallbackLanguages = [];
1483
+ const otherLanguages = [];
1484
+ for (const language of languages) if (localeTag(language.key, warnings) === content.settings.locale) fallbackLanguages.push(language);
1485
+ else otherLanguages.push(language);
1486
+ languageOrder = [...fallbackLanguages, ...otherLanguages];
1487
+ }
1488
+ for (const language of languageOrder) {
1202
1489
  const locale = localeTag(language.key, warnings);
1203
1490
  if (!locale) continue;
1204
1491
  for (const [uid, translation] of Object.entries(language.translations ?? {})) {
@@ -1206,9 +1493,13 @@ function convertTopolTemplate(design, options = {}) {
1206
1493
  warn(warnings, `Dropped language "${locale}" mj-subject: the host owns this field.`);
1207
1494
  continue;
1208
1495
  }
1209
- if (locale === content.settings.locale) continue;
1496
+ if (locale === content.settings.locale && sourcePrimaryLocale !== null) continue;
1497
+ const ontoBase = locale === content.settings.locale;
1210
1498
  if (uid === "mj-preview") {
1211
- if (typeof translation.content === "string") text(content.settings, locale, "preheaderText", content.settings.preheaderText, translation.content);
1499
+ if (typeof translation.content === "string") {
1500
+ if (ontoBase) content.settings.preheaderText = translation.content;
1501
+ else text(content.settings, locale, "preheaderText", content.settings.preheaderText, translation.content);
1502
+ }
1212
1503
  continue;
1213
1504
  }
1214
1505
  const target = uidMap.get(uid);
@@ -1222,17 +1513,29 @@ function convertTopolTemplate(design, options = {}) {
1222
1513
  ...target.node,
1223
1514
  content: translation.content
1224
1515
  }, ctx)?.block;
1225
- if ((block.type === "title" || block.type === "paragraph") && converted && (converted.type === "title" || converted.type === "paragraph")) text(block, locale, "content", block.content, converted.content);
1226
- else if (block.type === "button" && converted?.type === "button") text(block, locale, "text", block.text, converted.text);
1227
- else warn(warnings, `Dropped language "${locale}" content for uid "${uid}": no language mapping for this format.`);
1516
+ if ((block.type === "title" || block.type === "paragraph") && converted && (converted.type === "title" || converted.type === "paragraph")) {
1517
+ if (ontoBase) block.content = converted.content;
1518
+ else text(block, locale, "content", block.content, converted.content);
1519
+ } else if (block.type === "button" && converted?.type === "button") {
1520
+ if (ontoBase) block.text = converted.text;
1521
+ else text(block, locale, "text", block.text, converted.text);
1522
+ } else warn(warnings, `Dropped language "${locale}" content for uid "${uid}": no language mapping for this format.`);
1228
1523
  }
1229
1524
  for (const [key, value] of Object.entries(translation.attributes ?? {})) {
1230
1525
  if (typeof value !== "string") continue;
1231
- if (key === "alt" && block.type === "image") text(block, locale, "alt", block.alt, value);
1232
- else if (key === "href" && block.type === "button") set(block, locale, "url", value);
1233
- else if (key === "href" && block.type === "image") set(block, locale, "linkUrl", value);
1234
- else if (key === "src" && block.type === "image") set(block, locale, "src", value);
1235
- else warn(warnings, `Dropped language "${locale}" attribute "${key}" for uid "${uid}": no language mapping for this format.`);
1526
+ if (key === "alt" && block.type === "image") {
1527
+ if (ontoBase) block.alt = value;
1528
+ else text(block, locale, "alt", block.alt, value);
1529
+ } else if (key === "href" && block.type === "button") {
1530
+ if (ontoBase) block.url = value;
1531
+ else set(block, locale, "url", value);
1532
+ } else if (key === "href" && block.type === "image") {
1533
+ if (ontoBase) block.linkUrl = value;
1534
+ else set(block, locale, "linkUrl", value);
1535
+ } else if (key === "src" && block.type === "image") {
1536
+ if (ontoBase) block.src = value;
1537
+ else set(block, locale, "src", value);
1538
+ } else warn(warnings, `Dropped language "${locale}" attribute "${key}" for uid "${uid}": no language mapping for this format.`);
1236
1539
  }
1237
1540
  }
1238
1541
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/localization.ts","../src/attribute-parser.ts","../src/content-inference.ts","../src/global-style.ts","../src/block-mapper.ts","../src/social-mapper.ts","../src/section-builder.ts","../src/converter.ts"],"sourcesContent":["import { isLocaleTag, sourceHash } from \"@templatical/types\";\nimport type {\n Block,\n BlockLocaleLayer,\n TemplateContent,\n} from \"@templatical/types\";\n\ntype Target = { l10n?: Record<string, BlockLocaleLayer> };\n\n// Callers also push to `warnings` directly, so each set catches up on the\n// entries appended since the last call instead of being the only record.\nconst seenWarnings = new WeakMap<\n string[],\n { set: Set<string>; size: number }\n>();\n\nexport function warn(warnings: string[], message: string): void {\n let seen = seenWarnings.get(warnings);\n if (!seen || seen.size > warnings.length) {\n seen = { set: new Set(), size: 0 };\n seenWarnings.set(warnings, seen);\n }\n for (; seen.size < warnings.length; seen.size++) {\n seen.set.add(warnings[seen.size]);\n }\n if (seen.set.has(message)) return;\n warnings.push(message);\n seen.set.add(message);\n seen.size++;\n}\n\nexport function localeTag(value: string, warnings: string[]): string | null {\n const locale = value.replaceAll(\"_\", \"-\");\n if (isLocaleTag(locale)) return locale;\n warn(warnings, `Dropped language \"${value}\": unsupported language tag.`);\n return null;\n}\n\n/** The `defaultLocale` option as a tag; `null`, with a warning, when it isn't one. */\nexport function defaultLocaleOption(\n value: string | undefined,\n warnings: string[],\n): string | null {\n if (!value) return null;\n const locale = value.replaceAll(\"_\", \"-\");\n if (isLocaleTag(locale)) return locale;\n warn(\n warnings,\n `Ignored defaultLocale \"${value}\": unsupported language tag. Used \"en\".`,\n );\n return null;\n}\n\nexport function text(\n target: Target,\n locale: string,\n path: string,\n base: string | undefined,\n value: string,\n): void {\n if (base === undefined) {\n set(target, locale, path, value);\n return;\n }\n const layer = ((target.l10n ??= {})[locale] ??= {});\n (layer.text ??= {})[path] = { value, sourceHash: sourceHash(base) };\n}\n\nexport function set(\n target: Target,\n locale: string,\n path: string,\n value: unknown,\n): void {\n const layer = ((target.l10n ??= {})[locale] ??= {});\n (layer.set ??= {})[path] = value;\n}\n\n/** Register only non-default versions, leaving single-language imports unchanged. */\nexport function registerLocales(content: TemplateContent): void {\n const locales = new Set<string>();\n const visit = (target: Target) => {\n if (!target.l10n) return;\n delete target.l10n[content.settings.locale];\n for (const locale of Object.keys(target.l10n)) locales.add(locale);\n if (Object.keys(target.l10n).length === 0) delete target.l10n;\n };\n visit(content.settings);\n const walk = (blocks: Block[]) => {\n for (const block of blocks) {\n visit(block);\n if (block.type === \"section\") block.children.forEach(walk);\n }\n };\n walk(content.blocks);\n if (locales.size) content.settings.locales = [...locales];\n}\n","import type {\n BackgroundImage,\n BackgroundPositionX,\n BackgroundPositionY,\n BackgroundSize,\n SpacingValue,\n} from \"@templatical/types\";\nimport type { TopolNode } from \"./types\";\n\n/**\n * Read one attribute as a string, treating Topol's explicit `null` — and an\n * empty string — as absent.\n *\n * Topol writes literal `null` for an unset attribute rather than omitting the\n * key, so a `!== undefined` check would report it as present and write a null\n * into the block. Every optional-field read goes through here.\n */\nexport function attr(node: TopolNode, key: string): string | undefined {\n const raw = node.attributes?.[key];\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"object\") return undefined;\n const value = String(raw);\n return value === \"\" ? undefined : value;\n}\n\n/** Read one attribute as a number, or `undefined` when unset or non-numeric. */\nexport function numAttr(node: TopolNode, key: string): number | undefined {\n const value = attr(node, key);\n if (value === undefined) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a px-like value into a rounded integer. Returns 0 for a missing value\n * and for units the block model cannot express (em, rem, %).\n *\n * Trims first, then matches with no `\\s*` on either side of the optional\n * `px` unit. A trailing run of spaces can otherwise be claimed by either the\n * surrounding `\\s*` or by backtracking out of the digit/unit match, and a\n * *failing* match (no `px`, no digits — anything not shaped like a length)\n * retries every such split before giving up: `\"0\" + \" \".repeat(n) + \"x\"` is\n * polynomial in `n` against that pattern. Trimming first removes the only\n * whitespace the pattern needs to tolerate, so the match itself has nothing\n * ambiguous left to backtrack over.\n */\nexport function parsePxValue(value: string | number | undefined): number {\n if (value === undefined || value === null || value === \"\") return 0;\n if (typeof value === \"number\") return Math.round(value);\n const trimmed = value.trim();\n const match = /^(-?\\d+(?:\\.\\d+)?)(?:px)?$/.exec(trimmed);\n return match ? Math.round(parseFloat(match[1])) : 0;\n}\n\nconst NAMED_COLORS: Record<string, string> = {\n black: \"#000000\",\n white: \"#ffffff\",\n red: \"#ff0000\",\n green: \"#008000\",\n blue: \"#0000ff\",\n yellow: \"#ffff00\",\n cyan: \"#00ffff\",\n magenta: \"#ff00ff\",\n gray: \"#808080\",\n grey: \"#808080\",\n silver: \"#c0c0c0\",\n maroon: \"#800000\",\n olive: \"#808000\",\n lime: \"#00ff00\",\n aqua: \"#00ffff\",\n teal: \"#008080\",\n navy: \"#000080\",\n fuchsia: \"#ff00ff\",\n purple: \"#800080\",\n orange: \"#ffa500\",\n pink: \"#ffc0cb\",\n};\n\nfunction rgbToHex(r: number, g: number, b: number): string {\n const clamp = (n: number) => Math.max(0, Math.min(255, Math.round(n)));\n const hex = (n: number) => clamp(n).toString(16).padStart(2, \"0\");\n return `#${hex(r)}${hex(g)}${hex(b)}`;\n}\n\n/**\n * Normalize a colour to 6-digit lowercase hex.\n *\n * Returns `\"\"` for transparent/inherit/none and for anything unrecognised —\n * the empty string is the block model's \"unset\", which the colour pickers\n * clear to, so it is meaningfully different from returning a default.\n */\nexport function parseColor(value: string | undefined): string {\n if (!value) return \"\";\n const trimmed = value.trim().toLowerCase();\n if (trimmed === \"transparent\" || trimmed === \"inherit\" || trimmed === \"none\")\n return \"\";\n if (/^#[0-9a-f]{6}$/.test(trimmed)) return trimmed;\n if (/^#[0-9a-f]{3}$/.test(trimmed)) {\n const [, r, g, b] = trimmed;\n return `#${r}${r}${g}${g}${b}${b}`;\n }\n const rgb = trimmed.match(\n /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*[\\d.]+\\s*)?\\)$/,\n );\n if (rgb) return rgbToHex(+rgb[1], +rgb[2], +rgb[3]);\n return NAMED_COLORS[trimmed] ?? \"\";\n}\n\nfunction expandShorthand(value: string | undefined): SpacingValue {\n if (!value) return { top: 0, right: 0, bottom: 0, left: 0 };\n const v = value\n .trim()\n .split(/\\s+/)\n .map((p) => parsePxValue(p));\n switch (v.length) {\n case 1:\n return { top: v[0], right: v[0], bottom: v[0], left: v[0] };\n case 2:\n return { top: v[0], right: v[1], bottom: v[0], left: v[1] };\n case 3:\n return { top: v[0], right: v[1], bottom: v[2], left: v[1] };\n default:\n return { top: v[0], right: v[1], bottom: v[2], left: v[3] };\n }\n}\n\n/**\n * Read a node's padding, handling both forms Topol emits: a shorthand string\n * (`\"9px 9px 9px 9px\"`, used by most leaves) and four separate bare-number\n * keys (`padding-top: 24`, used by `mj-divider`). A separate key wins over the\n * shorthand for its own side.\n */\nexport function parsePadding(node: TopolNode): SpacingValue {\n const base = expandShorthand(attr(node, \"padding\"));\n const side = (key: string, fallback: number) => {\n const value = attr(node, key);\n return value === undefined ? fallback : parsePxValue(value);\n };\n return {\n top: side(\"padding-top\", base.top),\n right: side(\"padding-right\", base.right),\n bottom: side(\"padding-bottom\", base.bottom),\n left: side(\"padding-left\", base.left),\n };\n}\n\n/**\n * Read a percentage. Returns `null` when the value is not a percentage, so a\n * caller can tell \"no width given\" from \"0%\" — column matching depends on that\n * distinction.\n */\nexport function parsePercent(\n value: string | number | undefined,\n): number | null {\n if (value === undefined || value === null || value === \"\") return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*%$/);\n return match ? parseFloat(match[1]) : null;\n}\n\n/** Narrow an alignment to the three the block model accepts. */\nexport function parseAlignment(\n value: string | undefined,\n fallback: \"left\" | \"center\" | \"right\" = \"left\",\n): \"left\" | \"center\" | \"right\" {\n const v = (value ?? \"\").trim().toLowerCase();\n return v === \"left\" || v === \"center\" || v === \"right\" ? v : fallback;\n}\n\n/** Narrow a border style to the three `DividerBlock.lineStyle` accepts. */\nexport function parseBorderStyle(\n value: string | undefined,\n): \"solid\" | \"dashed\" | \"dotted\" {\n const v = (value ?? \"\").trim().toLowerCase();\n return v === \"dashed\" || v === \"dotted\" ? v : \"solid\";\n}\n\n/** A background image read from the source, with a note for each value that had no exact keyword. */\nexport interface ReadBackgroundImage {\n image: BackgroundImage;\n notes: string[];\n}\n\nconst X_GRID = [\"left\", \"center\", \"right\"] as const;\nconst Y_GRID = [\"top\", \"center\", \"bottom\"] as const;\nconst PERCENT = /^(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))%$/;\nconst LENGTH = /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)[a-z]*$/;\n\n/** What MJML paints for a `background-*` attribute an `mj-section` / `mj-wrapper` leaves out. */\nconst MJML_BACKGROUND_DEFAULTS = {\n size: \"auto\",\n x: \"center\",\n y: \"top\",\n repeat: true,\n} as const;\n\n/**\n * `background-size` as a keyword. A size with a side at 100%, or a px width\n * spanning the box, fills it as `cover` does; any other length or percentage\n * draws the image at a size of its own, which `auto` is closest to.\n */\nfunction backgroundSizeKeyword(\n raw: string,\n boxWidth: number | undefined,\n): { size: BackgroundSize; exact: boolean } {\n const parts = raw.toLowerCase().split(/\\s+/);\n const [first] = parts;\n if (parts.length === 1 && (first === \"cover\" || first === \"contain\")) {\n return { size: first, exact: true };\n }\n if (parts.every((part) => part === \"auto\")) {\n return { size: \"auto\", exact: true };\n }\n const px = /^(\\d+(?:\\.\\d+)?|\\.\\d+)px$/.exec(first);\n const fills =\n parts.includes(\"100%\") ||\n (px !== null && boxWidth !== undefined && Number(px[1]) >= boxWidth);\n return { size: fills ? \"cover\" : \"auto\", exact: false };\n}\n\n/**\n * `background-position` split into x and y the way MJML and CSS read it: a\n * lone `top` / `bottom` names y and centres x, any other lone value is x\n * with y centred, and a pair is x then y unless it leads with `top` /\n * `bottom` (or with `center` before `left` / `right`). Three- and four-value\n * edge offsets keep their edge keywords only.\n */\nfunction splitBackgroundPosition(raw: string): {\n x: string;\n y: string;\n exact: boolean;\n} {\n const parts = raw.toLowerCase().split(/\\s+/);\n if (parts.length === 1) {\n const [only] = parts;\n return only === \"top\" || only === \"bottom\"\n ? { x: \"center\", y: only, exact: true }\n : { x: only, y: \"center\", exact: true };\n }\n if (parts.length === 2) {\n const [a, b] = parts;\n const yFirst =\n a === \"top\" ||\n a === \"bottom\" ||\n (a === \"center\" && (b === \"left\" || b === \"right\"));\n return yFirst ? { x: b, y: a, exact: true } : { x: a, y: b, exact: true };\n }\n return {\n x: parts.find((part) => part === \"left\" || part === \"right\") ?? \"center\",\n y: parts.find((part) => part === \"top\" || part === \"bottom\") ?? \"center\",\n exact: false,\n };\n}\n\n/**\n * One axis as a grid point: its keyword; the point nearest a percentage,\n * ties going to the centre; or the start edge for a length, which is an\n * offset from it. `null` when the token is unreadable.\n */\nfunction backgroundAxisPoint<T extends string>(\n token: string,\n grid: readonly [T, T, T],\n): { point: T; exact: boolean } | null {\n const keyword = grid.find((point) => point === token);\n if (keyword) return { point: keyword, exact: true };\n const percent = PERCENT.exec(token);\n if (percent) {\n const n = Number(percent[1]);\n return {\n point: n < 25 ? grid[0] : n > 75 ? grid[2] : grid[1],\n exact: n === 0 || n === 50 || n === 100,\n };\n }\n if (LENGTH.test(token)) {\n return { point: grid[0], exact: parseFloat(token) === 0 };\n }\n return null;\n}\n\n/**\n * `background-repeat`: unrepeated only when every axis is `no-repeat`.\n * Anything but plain `repeat` tiles too, inexactly.\n */\nfunction backgroundRepeatFlag(raw: string): {\n repeat: boolean;\n exact: boolean;\n} {\n const parts = raw.toLowerCase().split(/\\s+/);\n if (parts.every((part) => part === \"no-repeat\")) {\n return { repeat: false, exact: true };\n }\n return { repeat: true, exact: parts.every((part) => part === \"repeat\") };\n}\n\n/**\n * An `mj-section` / `mj-wrapper` background image, `null` when\n * `background-url` is absent or blank. `read` returns an attribute's\n * resolved value. Unset attributes take MJML's own defaults, so the import\n * paints what MJML painted; a value with no exact keyword takes the nearest\n * one and adds a note naming it. `label` names the element in each note, and\n * a px `background-size` is measured against `boxWidth`.\n */\nexport function readMjmlBackgroundImage(\n read: (name: string) => string | undefined,\n label: string,\n boxWidth: number | undefined,\n): ReadBackgroundImage | null {\n const url = (read(\"background-url\") ?? \"\").trim();\n if (!url) return null;\n\n const notes: string[] = [];\n const lossy = (name: string, raw: string, shown: string): void => {\n notes.push(\n `${label} ${name} \"${raw}\" has no exact Templatical equivalent; imported as \"${shown}\".`,\n );\n };\n\n let size: BackgroundSize = MJML_BACKGROUND_DEFAULTS.size;\n const rawSize = read(\"background-size\")?.trim();\n if (rawSize) {\n const parsed = backgroundSizeKeyword(rawSize, boxWidth);\n size = parsed.size;\n if (!parsed.exact) lossy(\"background-size\", rawSize, size);\n }\n\n let x: BackgroundPositionX = MJML_BACKGROUND_DEFAULTS.x;\n let y: BackgroundPositionY = MJML_BACKGROUND_DEFAULTS.y;\n let lossyX = false;\n let lossyY = false;\n const rawPosition = read(\"background-position\")?.trim();\n if (rawPosition) {\n const split = splitBackgroundPosition(rawPosition);\n const readX = backgroundAxisPoint(split.x, X_GRID);\n const readY = backgroundAxisPoint(split.y, Y_GRID);\n x = readX?.point ?? x;\n y = readY?.point ?? y;\n lossyX = !split.exact || !readX?.exact;\n lossyY = !split.exact || !readY?.exact;\n }\n // A readable `-x` / `-y` replaces its axis, and with it whatever the\n // position lost there; the position's note then names what was imported.\n const rawX = read(\"background-position-x\")?.trim();\n const overrideX = rawX\n ? backgroundAxisPoint(rawX.toLowerCase(), X_GRID)\n : null;\n if (overrideX) {\n x = overrideX.point;\n lossyX = false;\n }\n const rawY = read(\"background-position-y\")?.trim();\n const overrideY = rawY\n ? backgroundAxisPoint(rawY.toLowerCase(), Y_GRID)\n : null;\n if (overrideY) {\n y = overrideY.point;\n lossyY = false;\n }\n if (rawPosition && (lossyX || lossyY)) {\n lossy(\"background-position\", rawPosition, `${x} ${y}`);\n }\n if (rawX && !overrideX?.exact) lossy(\"background-position-x\", rawX, x);\n if (rawY && !overrideY?.exact) lossy(\"background-position-y\", rawY, y);\n\n let repeat: boolean = MJML_BACKGROUND_DEFAULTS.repeat;\n const rawRepeat = read(\"background-repeat\")?.trim();\n if (rawRepeat) {\n const parsed = backgroundRepeatFlag(rawRepeat);\n repeat = parsed.repeat;\n if (!parsed.exact) {\n lossy(\"background-repeat\", rawRepeat, repeat ? \"repeat\" : \"no-repeat\");\n }\n }\n\n return { image: { url, size, position: { x, y }, repeat }, notes };\n}\n","import { findOpenTagEnd } from \"@templatical/types\";\nimport type { HeadingLevel } from \"@templatical/types\";\n\nexport type InferredText =\n | { kind: \"title\"; level: HeadingLevel; inner: string; clampedFrom?: number }\n | { kind: \"paragraph\"; html: string };\n\n/**\n * A single heading element wrapping the whole content, captured with its level\n * and inner markup. Anchored at both ends so a heading with a sibling does not\n * match — that case is a paragraph.\n */\nconst SOLE_HEADING = /^<h([1-6])(?:\\s[^>]*)?>([\\s\\S]*)<\\/h\\1>$/i;\n\nconst BLOCK_ROOT = /^<(p|h[1-6]|ul|ol|blockquote|div|table)\\b/i;\n\n/**\n * Resolve a Topol `content` string to a Title or a Paragraph.\n *\n * Topol has no menu or table construct, so this is a two-way choice — the MJML\n * importer needs four arms because `mj-text` is the output of four different\n * block renderers there. Paragraph is the terminal arm and always reachable,\n * so this function is total.\n */\nexport function inferTextBlock(content: string | undefined): InferredText {\n const trimmed = (content ?? \"\").trim();\n if (trimmed === \"\") return { kind: \"paragraph\", html: \"<p></p>\" };\n\n const heading = trimmed.match(SOLE_HEADING);\n if (heading) {\n const source = Number(heading[1]);\n const level = Math.min(source, 4) as HeadingLevel;\n return {\n kind: \"title\",\n level,\n inner: heading[2].trim(),\n ...(source > 4 ? { clampedFrom: source } : {}),\n };\n }\n\n return {\n kind: \"paragraph\",\n html: BLOCK_ROOT.test(trimmed) ? trimmed : `<p>${trimmed}</p>`,\n };\n}\n\nconst ENTITIES: Record<string, string> = {\n \"&amp;\": \"&\",\n \"&lt;\": \"<\",\n \"&gt;\": \">\",\n \"&quot;\": '\"',\n \"&#39;\": \"'\",\n \"&apos;\": \"'\",\n \"&nbsp;\": \" \",\n};\n\n/**\n * Remove every `<tag>` from `html`, keeping the text between them.\n *\n * A single-pass linear scan rather than `/<[^>]*>/g`: that regex is\n * polynomial over input with many `<` starts and no closing `>`, since\n * `[^>]*` backtracks at every one of them — `\"<\".repeat(n)` is quadratic in\n * `n`. `findOpenTagEnd` (from `@templatical/types`) resolves each `<` with a\n * bounded, quote-aware forward scan instead, so the walk stays O(n): every\n * character is visited at most once by `indexOf` and once by\n * `findOpenTagEnd`, because the cursor only moves forward and an\n * unterminated tag ends the walk rather than retrying from inside it. On\n * that unterminated case the remainder of the string — the dangling `<`\n * included — is emitted as-is, matching what `/<[^>]*>/g` does with\n * malformed markup: it can never complete a match without a `>`, so the\n * text is left untouched from that point on.\n */\nfunction removeTags(html: string): string {\n let out = \"\";\n let i = 0;\n while (i < html.length) {\n const open = html.indexOf(\"<\", i);\n if (open === -1) {\n out += html.substring(i);\n break;\n }\n out += html.substring(i, open);\n const tagEnd = findOpenTagEnd(html, open + 1);\n if (tagEnd === -1) {\n out += html.substring(open);\n break;\n }\n i = tagEnd + 1;\n }\n return out;\n}\n\n/**\n * The visible text of a markup fragment, for a button label — `ButtonBlock.text`\n * is a plain string, so the markup Topol stores in `content` cannot travel.\n */\nexport function stripTags(html: string | undefined): string {\n if (!html) return \"\";\n const text = removeTags(html);\n const decoded = text.replace(\n /&(?:amp|lt|gt|quot|#39|apos|nbsp);/g,\n (m) => ENTITIES[m] ?? m,\n );\n return decoded.replace(/\\s+/g, \" \").trim();\n}\n","import {\n canonicalFontStack,\n DEFAULT_TEMPLATE_DEFAULTS,\n} from \"@templatical/types\";\nimport type { TemplateContent, TemplateSettings } from \"@templatical/types\";\nimport { attr, parseColor, parsePxValue } from \"./attribute-parser\";\nimport type { TopolDesign, TopolNode } from \"./types\";\n\n/**\n * `DEFAULT_TEMPLATE_DEFAULTS` is typed `Partial<TemplateSettings>` so a\n * consumer can override any subset, but its own literal always sets the six\n * required fields. Narrowing once here is what lets each read come out as\n * `number`/`string`/`boolean` rather than `| undefined`. A plain typed\n * assignment cannot substitute: `Partial<T>` is not assignable to\n * `Required<Pick<T, …>>`, so `tsc` rejects it outright.\n */\nconst REQUIRED_DEFAULTS = DEFAULT_TEMPLATE_DEFAULTS as Required<\n Pick<\n TemplateSettings,\n | \"width\"\n | \"backgroundColor\"\n | \"textColor\"\n | \"linkUnderline\"\n | \"fontFamily\"\n | \"locale\"\n >\n>;\n\nexport interface GlobalStyle {\n settings: TemplateContent[\"settings\"];\n /** From nested objects like `\"mj-text\": { … }`. */\n tagDefaults: Record<string, Record<string, string>>;\n /** From flat `<selector>:<property>` keys; the bare selector is `\"\"`. */\n selectorDefaults: Record<string, Record<string, string>>;\n}\n\n/** A per-tag default, or undefined when the design sets none. */\nexport function tagDefault(\n style: GlobalStyle,\n tag: string,\n key: string,\n): string | undefined {\n return style.tagDefaults[tag]?.[key];\n}\n\n/** A per-selector default (`\"\"` is the document default), or undefined. */\nexport function selectorDefault(\n style: GlobalStyle,\n selector: string,\n key: string,\n): string | undefined {\n return style.selectorDefaults[selector]?.[key];\n}\n\n/**\n * Split the root's `attributes` into settings, per-tag defaults and\n * per-selector defaults.\n *\n * The root mixes two idioms: `<selector>:<property>` flat keys (`:color`,\n * `a:color`, `h1:font-family`) and `<tag>: { … }` nested objects, which are\n * the analogue of MJML's `mj-attributes`.\n */\nexport function readGlobalStyle(\n root: TopolDesign,\n container: TopolNode | undefined,\n warnings: string[],\n): GlobalStyle {\n const tagDefaults: Record<string, Record<string, string>> = Object.create(\n null,\n );\n const selectorDefaults: Record<\n string,\n Record<string, string>\n > = Object.create(null);\n\n for (const [key, value] of Object.entries(root.attributes ?? {})) {\n if (value !== null && typeof value === \"object\") {\n const bucket = (tagDefaults[key] ??= Object.create(null));\n for (const [k, v] of Object.entries(value)) {\n if (v !== null && v !== undefined) bucket[k] = String(v);\n }\n continue;\n }\n\n const colon = key.indexOf(\":\");\n // No colon means a root-level setting rather than a selector default —\n // `containerWidth` and `fonts` are the two real cases, and both are read\n // directly by name below instead of through the caches built here.\n if (colon === -1) continue;\n const selector = key.slice(0, colon);\n const property = key.slice(colon + 1);\n if (value === null || value === undefined) continue;\n const bucket = (selectorDefaults[selector] ??= Object.create(null));\n bucket[property] = String(value);\n }\n\n // containerWidth is authored only here, on the root. It is also denormalised\n // onto every leaf as the enclosing column's computed width (600/300/150 in\n // one template), so no other module may read it.\n const width =\n parsePxValue(attr(root, \"containerWidth\")) || REQUIRED_DEFAULTS.width;\n\n const backgroundColor =\n (container ? parseColor(attr(container, \"background-color\")) : \"\") ||\n REQUIRED_DEFAULTS.backgroundColor;\n\n const textColor =\n parseColor(selectorDefaults[\"\"]?.color) || REQUIRED_DEFAULTS.textColor;\n\n const fontFamily =\n canonicalFontStack(selectorDefaults[\"\"]?.[\"font-family\"]) ||\n canonicalFontStack(attr(root, \"fonts\")) ||\n REQUIRED_DEFAULTS.fontFamily;\n\n const linkColor = parseColor(selectorDefaults[\"a\"]?.color);\n\n const lineHeight = selectorDefaults[\"\"]?.[\"line-height\"];\n if (lineHeight !== undefined) {\n warnings.push(\n `Dropped the document line-height (${lineHeight}) — Templatical has no document-level line-height setting.`,\n );\n }\n\n const settings: TemplateContent[\"settings\"] = {\n width,\n backgroundColor,\n textColor,\n linkUnderline: REQUIRED_DEFAULTS.linkUnderline,\n fontFamily,\n locale: REQUIRED_DEFAULTS.locale,\n ...(linkColor ? { linkColor } : {}),\n };\n\n return { settings, tagDefaults, selectorDefaults };\n}\n","import {\n BUTTON_BLOCK_DEFAULTS,\n BUTTON_LINE_HEIGHT,\n canonicalFontStack,\n createButtonBlock,\n createDividerBlock,\n createHtmlBlock,\n createImageBlock,\n createParagraphBlock,\n createSpacerBlock,\n createTitleBlock,\n roundHundredths,\n} from \"@templatical/types\";\nimport type { Block, BlockStyles } from \"@templatical/types\";\nimport {\n attr,\n numAttr,\n parseAlignment,\n parseBorderStyle,\n parseColor,\n parsePadding,\n parsePxValue,\n} from \"./attribute-parser\";\nimport { inferTextBlock, stripTags } from \"./content-inference\";\nimport { selectorDefault, tagDefault, type GlobalStyle } from \"./global-style\";\nimport type { ImportReportEntry, TopolNode } from \"./types\";\n\nexport interface MapContext {\n uidMap?: Map<string, { node: TopolNode; block: Block | null }>;\n style: GlobalStyle;\n /** The rendered width of the column holding this node, for `width: \"full\"`. */\n columnWidth: number;\n}\n\nexport interface Converted {\n block: Block | null;\n entry: ImportReportEntry;\n}\n\n/**\n * Read a node's own attribute, falling back to the design's per-tag then\n * per-selector default. Returns undefined when nothing sets it, so the caller\n * can omit the field and let the block factory's default stand.\n */\nfunction resolved(\n node: TopolNode,\n key: string,\n ctx: MapContext,\n selector?: string,\n): string | undefined {\n return (\n attr(node, key) ??\n tagDefault(ctx.style, node.tagName, key) ??\n (selector === undefined\n ? undefined\n : selectorDefault(ctx.style, selector, key))\n );\n}\n\n/**\n * The `styles` every leaf block shares.\n *\n * The block background is the row behind the element, which MJML reads from\n * `container-background-color` on every leaf and which the renderer writes\n * `styles.backgroundColor` back out as. A leaf's `background-color` must not\n * feed it: on `mj-button` it is the button face (`backgroundColor`, read in\n * `convertButton`), on `mj-text` MJML never paints it, and on image, spacer,\n * divider and social it is invalid and dropped. Reading it here paints a\n * button's whole row in its fill colour. `buildSection` reads\n * `background-color` itself, since on `mj-section` it is the section's fill.\n */\nexport function baseStyles(node: TopolNode): { styles: BlockStyles } {\n const backgroundColor = parseColor(attr(node, \"container-background-color\"));\n return {\n styles: {\n padding: parsePadding(node),\n ...(backgroundColor ? { backgroundColor } : {}),\n },\n };\n}\n\nfunction convertText(node: TopolNode, ctx: MapContext): Converted {\n const inferred = inferTextBlock(node.content);\n\n if (inferred.kind === \"paragraph\") {\n return {\n block: createParagraphBlock({\n content: inferred.html,\n ...baseStyles(node),\n }),\n entry: {\n sourceTag: \"mj-text\",\n templaticalBlockType: \"paragraph\",\n status: \"converted\",\n },\n };\n }\n\n const selector = `h${inferred.level}`;\n const color = parseColor(resolved(node, \"color\", ctx, selector));\n const fontFamily = canonicalFontStack(\n resolved(node, \"font-family\", ctx, selector),\n );\n\n const block = createTitleBlock({\n content: inferred.inner,\n level: inferred.level,\n textAlign: parseAlignment(attr(node, \"align\"), \"left\"),\n ...(color ? { color } : {}),\n ...(fontFamily ? { fontFamily } : {}),\n ...baseStyles(node),\n });\n\n return {\n block,\n entry: {\n sourceTag: \"mj-text\",\n templaticalBlockType: \"title\",\n status: inferred.clampedFrom ? \"approximated\" : \"converted\",\n ...(inferred.clampedFrom\n ? {\n note: `Heading level h${inferred.clampedFrom} clamped to 4 — Templatical titles support h1-h4.`,\n }\n : {}),\n },\n };\n}\n\n/**\n * A button's line height as `ButtonBlock.lineHeight`, a multiple of\n * `fontSize`. A percentage is that number over 100, a unitless number is\n * itself, a px length is that many pixels over `fontSize`, and an `em`\n * length is the number itself. A leading dot (`.5`) is read. Rounded to two\n * decimals. A missing value, `normal`, and a value that rounds to 1.2 stay\n * unset, so the label keeps `BUTTON_LINE_HEIGHT`. Any other value that\n * cannot be kept stays unset and pushes a note.\n */\nfunction readButtonLineHeight(\n value: unknown,\n fontSize: number,\n notes: string[],\n): number | undefined {\n const trimmed = String(value ?? \"\").trim();\n if (trimmed === \"\" || /^normal$/i.test(trimmed)) return undefined;\n\n const percent = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))\\s*%$/.exec(trimmed);\n const unitless = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))$/.exec(trimmed);\n const px = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))\\s*px$/i.exec(trimmed);\n const em = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))\\s*em$/i.exec(trimmed);\n let ratio = Number.NaN;\n if (percent) ratio = Number(percent[1]) / 100;\n else if (unitless) ratio = Number(unitless[1]);\n else if (px) ratio = Number(px[1]) / fontSize;\n else if (em) ratio = Number(em[1]);\n\n const rounded = roundHundredths(ratio);\n if (!Number.isFinite(rounded) || !(rounded > 0)) {\n notes.push(\n `Button line-height \"${trimmed}\" could not be read; imported at 1.2.`,\n );\n return undefined;\n }\n return rounded === BUTTON_LINE_HEIGHT ? undefined : rounded;\n}\n\nfunction convertButton(node: TopolNode, ctx: MapContext): Converted | null {\n const text = stripTags(node.content);\n if (!text) return null;\n\n const backgroundColor = parseColor(\n resolved(node, \"background-color\", ctx, \"button\"),\n );\n const textColor = parseColor(resolved(node, \"color\", ctx, \"button\"));\n const fontFamily = canonicalFontStack(\n resolved(node, \"font-family\", ctx, \"button\"),\n );\n // A stated font size that is not px, not finite, or not above 0, leaves the\n // factory size with a note, and a px line height is measured against the\n // size the label renders at.\n const factorySize = Number(BUTTON_BLOCK_DEFAULTS.fontSize);\n const statedFontSize = String(resolved(node, \"font-size\", ctx) ?? \"\").trim();\n const parsedFontSize = parsePxValue(statedFontSize);\n const fontSize =\n Number.isFinite(parsedFontSize) && parsedFontSize > 0\n ? parsedFontSize\n : undefined;\n const radiusRaw = resolved(node, \"border-radius\", ctx);\n const notes: string[] = [];\n if (statedFontSize !== \"\" && fontSize === undefined) {\n notes.push(\n `Button font-size \"${statedFontSize}\" could not be read; imported at ${factorySize}px.`,\n );\n }\n const lineHeight = readButtonLineHeight(\n resolved(node, \"line-height\", ctx, \"button\"),\n fontSize ?? factorySize,\n notes,\n );\n\n return {\n block: createButtonBlock({\n text,\n url: attr(node, \"href\") ?? \"\",\n ...(backgroundColor ? { backgroundColor } : {}),\n ...(textColor ? { textColor } : {}),\n ...(fontFamily ? { fontFamily } : {}),\n ...(fontSize !== undefined ? { fontSize } : {}),\n ...(lineHeight !== undefined ? { lineHeight } : {}),\n ...(radiusRaw === undefined\n ? {}\n : { borderRadius: parsePxValue(radiusRaw) }),\n align: parseAlignment(attr(node, \"align\"), \"center\"),\n ...baseStyles(node),\n }),\n entry: {\n sourceTag: node.tagName,\n templaticalBlockType: \"button\",\n status: notes.length > 0 ? \"approximated\" : \"converted\",\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n },\n };\n}\n\nfunction convertImage(\n node: TopolNode,\n ctx: MapContext,\n sourceTag: string,\n): Converted | null {\n const src = attr(node, \"src\");\n if (!src) return null;\n\n const widthPercent = numAttr(node, \"widthPercent\");\n const pxWidth = numAttr(node, \"width\");\n const href = attr(node, \"href\");\n const base = baseStyles(node);\n // MJML caps an image at its column less its own side padding, so a px width\n // that reaches that renders as \"full\" does.\n const room =\n ctx.columnWidth - base.styles.padding.left - base.styles.padding.right;\n\n const width =\n widthPercent === 100 || pxWidth === undefined || pxWidth >= room\n ? (\"full\" as const)\n : Math.round(pxWidth);\n\n const isGif = sourceTag === \"mj-gif\";\n\n return {\n block: createImageBlock({\n src,\n alt: attr(node, \"alt\") ?? \"\",\n width,\n align: parseAlignment(attr(node, \"align\"), \"center\"),\n ...(href ? { linkUrl: href } : {}),\n ...base,\n }),\n entry: {\n sourceTag,\n templaticalBlockType: \"image\",\n status: isGif ? \"approximated\" : \"converted\",\n ...(isGif\n ? {\n note: \"<mj-gif> imported as an image block; Templatical has no dedicated GIF block.\",\n }\n : {}),\n },\n };\n}\n\nfunction convertSpacer(node: TopolNode): Converted {\n const height = attr(node, \"height\");\n return {\n block: createSpacerBlock({\n ...(height === undefined ? {} : { height: parsePxValue(height) }),\n ...baseStyles(node),\n }),\n entry: {\n sourceTag: \"mj-spacer\",\n templaticalBlockType: \"spacer\",\n status: \"converted\",\n },\n };\n}\n\nfunction convertDivider(node: TopolNode): Converted {\n const color = parseColor(attr(node, \"border-color\"));\n const thickness = attr(node, \"border-width\");\n return {\n block: createDividerBlock({\n lineStyle: parseBorderStyle(attr(node, \"border-style\")),\n ...(color ? { color } : {}),\n ...(thickness === undefined\n ? {}\n : { thickness: parsePxValue(thickness) }),\n ...baseStyles(node),\n }),\n entry: {\n sourceTag: \"mj-divider\",\n templaticalBlockType: \"divider\",\n status: \"converted\",\n },\n };\n}\n\n/**\n * Convert one leaf node to a block.\n *\n * Returns `null` for a node that produces nothing *and* warrants no report\n * entry — an image with no `src`, a button with no label. `mj-social` is not\n * handled here; the converter routes it to `convertSocial`.\n */\nexport function convertLeaf(\n node: TopolNode,\n ctx: MapContext,\n): Converted | null {\n switch (node.tagName) {\n case \"mj-text\":\n return convertText(node, ctx);\n case \"mj-button\":\n return convertButton(node, ctx);\n case \"mj-image\":\n return convertImage(node, ctx, \"mj-image\");\n case \"mj-gif\":\n return convertImage(node, ctx, \"mj-gif\");\n case \"mj-spacer\":\n return convertSpacer(node);\n case \"mj-divider\":\n return convertDivider(node);\n default:\n return {\n block: createHtmlBlock({\n content: JSON.stringify(node),\n ...baseStyles(node),\n }),\n entry: {\n sourceTag: node.tagName,\n templaticalBlockType: \"html\",\n status: \"html-fallback\",\n note: `<${node.tagName}> has no Templatical block equivalent; the original node is preserved as JSON.`,\n },\n };\n }\n}\n","import { createSocialIconsBlock, generateId } from \"@templatical/types\";\nimport type {\n SocialIcon,\n SocialIconTone,\n SocialIconSize,\n SocialIconStyle,\n BuiltInSocialPlatform,\n} from \"@templatical/types\";\nimport { attr, parseAlignment, parsePxValue } from \"./attribute-parser\";\nimport { baseStyles, type Converted, type MapContext } from \"./block-mapper\";\nimport type { TopolNode } from \"./types\";\n\n/**\n * Exhaustive over `BuiltInSocialPlatform` on purpose: adding a member to that union\n * without adding it here is a compile error, so this cannot silently fall back\n * to \"website\" for a platform the block model gained.\n */\nconst KNOWN_PLATFORMS: Record<BuiltInSocialPlatform, true> = {\n facebook: true,\n twitter: true,\n instagram: true,\n linkedin: true,\n xing: true,\n youtube: true,\n tiktok: true,\n pinterest: true,\n email: true,\n whatsapp: true,\n telegram: true,\n discord: true,\n snapchat: true,\n reddit: true,\n github: true,\n dribbble: true,\n behance: true,\n website: true,\n};\n\nconst ALIASES: Record<string, BuiltInSocialPlatform> = {\n x: \"twitter\",\n \"x-twitter\": \"twitter\",\n};\n\nconst ICON_SIZES: Array<[number, SocialIconSize]> = [\n [24, \"small\"],\n [32, \"medium\"],\n [48, \"large\"],\n];\n\nconst KNOWN_STYLES = new Set<string>([\n \"solid\",\n \"outlined\",\n \"rounded\",\n \"square\",\n \"circle\",\n]);\n\n// Topol ships icon sets whose folder name is not a Templatical style name.\n// `outlinedbw` is the outlined set in black and white, so it imports as\n// outlined in the dark tone; mapping it to the `solid` fallback would import\n// an outlined icon set as filled. Measured: both `/social-icos/outlined/` and\n// `/social-icos/outlinedbw/` appear across the reference exports.\nconst STYLE_ALIASES: Record<\n string,\n { style: SocialIconStyle; tone: SocialIconTone }\n> = {\n outlinedbw: { style: \"outlined\", tone: \"dark\" },\n};\n\nfunction normalizePlatform(raw: string): BuiltInSocialPlatform | null {\n const cleaned = raw.trim().toLowerCase();\n if (!cleaned) return null;\n if (ALIASES[cleaned]) return ALIASES[cleaned];\n return cleaned in KNOWN_PLATFORMS ? (cleaned as BuiltInSocialPlatform) : null;\n}\n\nfunction nearestSize(px: number): { size: SocialIconSize; exact: boolean } {\n let best = ICON_SIZES[1];\n let gap = Infinity;\n for (const candidate of ICON_SIZES) {\n const d = Math.abs(candidate[0] - px);\n if (d < gap) {\n gap = d;\n best = candidate;\n }\n }\n return { size: best[1], exact: gap === 0 };\n}\n\n/** The style (and tone) the segment of `https://…/social-icos/<style>/` names. */\nfunction styleFromBaseUrl(\n baseUrl: string | undefined,\n): { style: SocialIconStyle; tone?: SocialIconTone } | undefined {\n if (!baseUrl) return undefined;\n const segment = baseUrl.split(\"?\")[0].split(\"/\").filter(Boolean).at(-1) ?? \"\";\n if (KNOWN_STYLES.has(segment)) return { style: segment as SocialIconStyle };\n return STYLE_ALIASES[segment];\n}\n\n/**\n * Convert Topol's MJML v3 social block.\n *\n * `display` decides which icons render and in what order; a platform with\n * `*-href` set but absent from `display` was not shown in the email and is\n * not imported.\n */\nexport function convertSocial(\n node: TopolNode,\n _ctx: MapContext,\n): Converted | null {\n const display = attr(node, \"display\");\n if (!display) return null;\n\n const notes: string[] = [];\n const icons: SocialIcon[] = [];\n const seen = new Set<string>();\n const repeated = new Map<string, number>();\n\n for (const token of display.trim().split(/\\s+/)) {\n const rawName = token.split(\":\")[0];\n if (!rawName) continue;\n\n const url = attr(node, `${rawName}-href`);\n if (!url) continue;\n\n const platform = normalizePlatform(rawName);\n const key = JSON.stringify([platform ?? \"website\", url]);\n if (seen.has(key)) {\n const name = platform ?? \"website\";\n repeated.set(name, (repeated.get(name) ?? 0) + 1);\n continue;\n }\n seen.add(key);\n if (!platform) {\n notes.push(\n `Unrecognised social platform \"${rawName}\" mapped to \"website\".`,\n );\n }\n\n icons.push({ id: generateId(), platform: platform ?? \"website\", url });\n }\n for (const [platform, count] of repeated) {\n notes.push(\n `Dropped ${count} repeated \"${platform}\" ${count === 1 ? \"icon\" : \"icons\"}.`,\n );\n }\n\n if (icons.length === 0) return null;\n\n const fromBaseUrl = styleFromBaseUrl(attr(node, \"base-url\"));\n\n const declaredSize = attr(node, \"icon-size\");\n let iconSize: SocialIconSize | undefined;\n if (declaredSize !== undefined) {\n const px = parsePxValue(declaredSize);\n const resolved = nearestSize(px);\n iconSize = resolved.size;\n if (!resolved.exact) {\n notes.push(\n `Icon size ${declaredSize} is not one of 24/32/48px; resolved to \"${resolved.size}\".`,\n );\n }\n }\n\n return {\n block: createSocialIconsBlock({\n icons,\n align: parseAlignment(attr(node, \"align\"), \"center\"),\n ...(iconSize ? { iconSize } : {}),\n ...(fromBaseUrl ? { iconStyle: fromBaseUrl.style } : {}),\n ...(fromBaseUrl?.tone ? { iconTone: fromBaseUrl.tone } : {}),\n ...baseStyles(node),\n }),\n entry: {\n sourceTag: \"mj-social\",\n templaticalBlockType: \"social\",\n status: notes.length > 0 ? \"approximated\" : \"converted\",\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n },\n };\n}\n","import {\n COLUMN_LAYOUT_PERCENTS,\n columnWidthsIssue,\n createSectionBlock,\n sectionColumnPercents,\n} from \"@templatical/types\";\nimport type { Block, ColumnLayout } from \"@templatical/types\";\nimport {\n attr,\n parseColor,\n parsePadding,\n parsePercent,\n readMjmlBackgroundImage,\n} from \"./attribute-parser\";\nimport { convertLeaf, type MapContext } from \"./block-mapper\";\nimport { convertSocial } from \"./social-mapper\";\nimport type { ImportReportEntry, TopolNode } from \"./types\";\n\n/** Preset match order. The first preset within the tolerance wins. */\nconst LAYOUT_MATCH_ORDER: readonly ColumnLayout[] = [\n \"1\",\n \"2\",\n \"1-2\",\n \"2-1\",\n \"1-3\",\n \"3-1\",\n \"3\",\n \"1-2-1\",\n \"4\",\n];\n\n/** Percentage points of drift tolerated per column before a match is inexact. */\nconst WIDTH_TOLERANCE = 2;\n\n/**\n * One hundredth, the step `sectionColumnPercents` rounds to, plus the float\n * error of subtracting two hundredths. Scaled shares this close to a preset\n * are that preset.\n */\nconst SCALED_TOLERANCE = 0.01 + 1e-9;\n\nfunction evenLayout(count: number): ColumnLayout {\n if (count === 3) return \"3\";\n if (count === 4) return \"4\";\n return \"2\";\n}\n\n/** The first preset with one share per value, each within `tolerance`. */\nfunction presetWithin(\n percents: readonly number[],\n tolerance: number,\n): ColumnLayout | undefined {\n return LAYOUT_MATCH_ORDER.find((layout) => {\n const target = COLUMN_LAYOUT_PERCENTS[layout];\n return (\n target.length === percents.length &&\n target.every(\n (share, index) => Math.abs(share - percents[index]!) <= tolerance,\n )\n );\n });\n}\n\nconst COLUMN_COUNT: Record<ColumnLayout, number> = {\n \"1\": 1,\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"2-1\": 2,\n \"1-2\": 2,\n \"3-1\": 2,\n \"1-3\": 2,\n \"1-2-1\": 3,\n};\n\n/**\n * Each column's px width in `container`: the preset's shares, a third for\n * `\"3\"`, `\"1-2\"` and `\"2-1\"`, or the `columnWidths` percentages when the\n * section has them.\n */\nfunction columnPixels(\n layout: ColumnLayout,\n container: number,\n columnWidths: readonly number[] | undefined,\n): number[] {\n if (columnWidths) {\n return columnWidths.map((percent) => (container * percent) / 100);\n }\n switch (layout) {\n case \"2\":\n return [container / 2, container / 2];\n case \"3\":\n return [container / 3, container / 3, container / 3];\n case \"1-2\":\n return [container / 3, (container * 2) / 3];\n case \"2-1\":\n return [(container * 2) / 3, container / 3];\n case \"1-3\":\n return [container / 4, (container * 3) / 4];\n case \"3-1\":\n return [(container * 3) / 4, container / 4];\n case \"1-2-1\":\n return [container / 4, container / 2, container / 4];\n case \"4\":\n return [container / 4, container / 4, container / 4, container / 4];\n default:\n return [container];\n }\n}\n\n/**\n * Resolve `mj-column` widths, as percentages of the section's inner box, to\n * a layout. Topol renders through MJML, so MJML's rules apply.\n *\n * A width list within `WIDTH_TOLERANCE` of a preset keeps that preset. An\n * absent width is `mj-column`'s default, the parent width divided by the\n * column count, whatever its siblings state, so a row with no widths is\n * the even preset. One column is `\"1\"`: exact at 100%, approximated\n * otherwise. Two, three or four columns that fit no preset are scaled to\n * 100: scaled shares equal to a preset keep that preset, any others keep\n * the even preset of that count plus `columnWidths`. Either is exact when\n * the widths already total 100 within half a point; otherwise scaling\n * changed the source layout. A width that cannot be stored (not above 0)\n * keeps the even preset, approximated. Five or more columns fold onto\n * `\"4\"`, approximated.\n */\nexport function matchColumnLayout(percents: Array<number | null>): {\n layout: ColumnLayout;\n exact: boolean;\n columnWidths?: number[];\n} {\n const count = percents.length;\n if (count === 0) return { layout: \"1\", exact: true };\n if (count > 4) return { layout: \"4\", exact: false };\n\n const resolved = percents.map((percent) => percent ?? 100 / count);\n const preset = presetWithin(resolved, WIDTH_TOLERANCE);\n if (preset) return { layout: preset, exact: true };\n if (count === 1) return { layout: \"1\", exact: false };\n\n const layout = evenLayout(count);\n if (columnWidthsIssue({ columns: layout, columnWidths: resolved }) !== null) {\n return { layout, exact: false };\n }\n // Half a point treats a float sum of shares that already are 100 as exact.\n const total = resolved.reduce((sum, share) => sum + share, 0);\n const exact = Math.abs(total - 100) <= 0.5;\n const scaled = sectionColumnPercents({\n columns: layout,\n columnWidths: resolved,\n });\n const scaledPreset = presetWithin(scaled, SCALED_TOLERANCE);\n if (scaledPreset) return { layout: scaledPreset, exact };\n return { layout, exact, columnWidths: scaled };\n}\n\nconst PX_WIDTH = /^(\\d+(?:\\.\\d+)?)\\s*px$/i;\n\n/**\n * A column's `width` as a percentage of `innerWidth`, or `null` when it\n * states none. A percentage is read as written. A px width is that many\n * pixels of the inner box, the email width less the section's side\n * padding, which is the box MJML sizes columns against.\n */\nfunction columnPercent(\n value: string | undefined,\n innerWidth: number,\n): number | null {\n const percent = parsePercent(value);\n if (percent !== null) return percent;\n const px = PX_WIDTH.exec((value ?? \"\").trim());\n if (!px || innerWidth <= 0) return null;\n return (Number(px[1]) / innerWidth) * 100;\n}\n\nfunction convertColumnChildren(\n column: TopolNode,\n ctx: MapContext,\n entries: ImportReportEntry[],\n): Block[] {\n const blocks: Block[] = [];\n for (const child of column.children ?? []) {\n const converted =\n child.tagName === \"mj-social\"\n ? convertSocial(child, ctx)\n : convertLeaf(child, ctx);\n if (child.uid)\n ctx.uidMap?.set(child.uid, {\n node: child,\n block: converted?.block ?? null,\n });\n if (!converted) continue;\n entries.push(converted.entry);\n if (converted.block) blocks.push(converted.block);\n }\n return blocks;\n}\n\n/**\n * Build a `SectionBlock` from an `mj-section`. Returns an array so the caller\n * can treat an empty section (no columns) as producing nothing.\n *\n * Reads `attributes` only. The node's top-level camelCase keys\n * (`backgroundColor`, `paddingTop`, …) are stale editor state that disagrees\n * with `attributes` in every measured case.\n */\nexport function buildSection(\n node: TopolNode,\n ctx: MapContext,\n entries: ImportReportEntry[],\n): Block[] {\n const columns = (node.children ?? []).filter(\n (c) => c.tagName === \"mj-column\",\n );\n if (columns.length === 0) return [];\n\n const padding = parsePadding(node);\n const innerWidth = ctx.style.settings.width - padding.left - padding.right;\n const rawWidths = columns.map((c) => attr(c, \"width\"));\n const percents = rawWidths.map((w) => columnPercent(w, innerWidth));\n const matched = matchColumnLayout(percents);\n const { layout, columnWidths } = matched;\n // With no inner box a px width has nothing to be a share of, so it is\n // dropped and the row's ratio is lost.\n const pxDropped =\n innerWidth <= 0 &&\n rawWidths.some((w) => w !== undefined && PX_WIDTH.test(w.trim()));\n const exact = matched.exact && !pxDropped;\n\n const slots = COLUMN_COUNT[layout];\n // MJML lays the columns out in the inner box, so each column's room is\n // its share of that box, not of the email width.\n const pixels = columnPixels(layout, Math.max(0, innerWidth), columnWidths);\n const children: Block[][] = Array.from({ length: slots }, () => []);\n\n const background = readMjmlBackgroundImage(\n (name) => attr(node, name),\n \"Section\",\n ctx.style.settings.width,\n );\n const notes = [\n ...(exact\n ? []\n : [\n `Column widths ${rawWidths.map((w) => w ?? \"auto\").join(\", \")} have no exact Templatical layout; resolved to \"${layout}\".${columns.length > 4 ? \" Templatical supports up to four columns.\" : \"\"}`,\n ]),\n ...(background?.notes ?? []),\n ];\n entries.push({\n sourceTag: \"mj-section\",\n templaticalBlockType: \"section\",\n status: notes.length > 0 ? \"approximated\" : \"converted\",\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n });\n\n columns.forEach((column, index) => {\n const slot = Math.min(index, slots - 1);\n const columnCtx: MapContext = {\n ...ctx,\n columnWidth: Math.round(pixels[slot] ?? ctx.style.settings.width),\n };\n children[slot].push(...convertColumnChildren(column, columnCtx, entries));\n });\n\n const backgroundColor = parseColor(attr(node, \"background-color\"));\n // `full-width=\"full-width\"` makes this section's own background the\n // viewport band. The section stays transparent over it.\n const fullWidth =\n attr(node, \"full-width\") === \"full-width\" &&\n Boolean(backgroundColor || background);\n\n return [\n createSectionBlock({\n columns: layout,\n ...(columnWidths ? { columnWidths } : {}),\n children,\n styles: {\n padding,\n ...(!fullWidth && backgroundColor ? { backgroundColor } : {}),\n },\n ...(!fullWidth && background\n ? { backgroundImage: background.image }\n : {}),\n ...(fullWidth\n ? {\n wrapper: {\n ...(backgroundColor ? { backgroundColor } : {}),\n ...(background ? { backgroundImage: background.image } : {}),\n fullWidth: true,\n },\n }\n : {}),\n }),\n ];\n}\n","import {\n defaultLocaleOption,\n localeTag,\n registerLocales,\n set,\n text,\n warn,\n} from \"./localization\";\nimport { convertLeaf } from \"./block-mapper\";\nimport { createDefaultTemplateContent } from \"@templatical/types\";\nimport type { Block, TemplateContent } from \"@templatical/types\";\nimport { readGlobalStyle } from \"./global-style\";\nimport { buildSection } from \"./section-builder\";\nimport type { MapContext } from \"./block-mapper\";\nimport type {\n ImportReport,\n ImportReportEntry,\n ImportResult,\n TopolDesign,\n} from \"./types\";\n\nexport interface ConvertTopolOptions {\n /** Used when the source declares no default language. */\n defaultLocale?: string;\n}\n\nconst ROOT_TAG = \"mj-global-style\";\n// Designs saved by Topol's editor hold their sections under either tag.\nconst CONTAINER_TAGS = new Set([\"mj-container\", \"mj-body\"]);\n\nconst INVALID_DESIGN_MESSAGE =\n 'Invalid Topol template: expected the design JSON object — Topol hands you this directly from its editor\\'s onSave callback, or under \"definition\" (template API) or \"json\" (predefined-templates API) in its API response.';\n\nconst EMPTY_DESIGN_WARNING =\n \"No convertible content was found in the Topol design. Check that its mj-container (or mj-body) holds at least one mj-section.\";\n\n/**\n * Convert a Topol.io design into a Templatical template.\n *\n * The input is the design object itself — the node whose `tagName` is\n * `mj-global-style`, not a whole API response. Topol's editor hands it to\n * you directly as the first argument to `onSave`; its REST APIs wrap it\n * instead, under `definition` on the template-retrieval endpoint or `json`\n * (alongside `html`) on the predefined-templates endpoint. That is\n * documented rather than sniffed: guessing which field holds the design\n * risks importing an envelope's `html`, which belongs to a different\n * package entirely.\n *\n * @example\n * ```ts\n * const { content, report } = convertTopolTemplate(design);\n * const editor = init({ container: '#editor', content });\n * console.log(report.summary);\n * ```\n */\nexport function convertTopolTemplate(\n design: TopolDesign | string,\n options: ConvertTopolOptions = {},\n): ImportResult {\n const root: unknown = typeof design === \"string\" ? safeParse(design) : design;\n\n if (typeof root !== \"object\" || root === null || Array.isArray(root)) {\n throw new Error(INVALID_DESIGN_MESSAGE);\n }\n\n const topolDesign = root as TopolDesign;\n\n if (topolDesign.tagName !== ROOT_TAG) {\n // Topol's REST APIs wrap the design rather than returning it bare: the\n // template-retrieval endpoint uses \"definition\", the predefined/premade\n // templates endpoint uses \"json\" (alongside \"html\"). A response object\n // passed here by mistake still carries one of those keys, so that\n // mistake is named directly instead of falling through to the generic\n // wrong-tagName message below.\n if (\"json\" in topolDesign || \"definition\" in topolDesign) {\n throw new Error(INVALID_DESIGN_MESSAGE);\n }\n throw new Error(\n `Invalid Topol template: expected a root node with tagName \"${ROOT_TAG}\".`,\n );\n }\n\n const container = (topolDesign.children ?? []).find((child) =>\n CONTAINER_TAGS.has(child.tagName),\n );\n\n const entries: ImportReportEntry[] = [];\n const warnings: string[] = [];\n const blocks: Block[] = [];\n\n const style = readGlobalStyle(topolDesign, container, warnings);\n const languages = topolDesign.langs ?? [];\n const primary =\n languages.find((language) => language.primary) ?? languages[0];\n style.settings.locale =\n (primary ? localeTag(primary.key, warnings) : null) ??\n defaultLocaleOption(options.defaultLocale, warnings) ??\n \"en\";\n const uidMap: NonNullable<MapContext[\"uidMap\"]> = new Map();\n\n const ctx: MapContext = {\n uidMap,\n style,\n columnWidth: style.settings.width,\n };\n\n for (const child of container?.children ?? []) {\n if (child.tagName !== \"mj-section\") continue;\n blocks.push(...buildSection(child, ctx, entries));\n }\n\n if (blocks.length === 0) {\n warnings.push(EMPTY_DESIGN_WARNING);\n }\n\n const content: TemplateContent = {\n ...createDefaultTemplateContent(),\n blocks,\n settings: style.settings,\n };\n\n const preview = primary?.translations?.[\"mj-preview\"]?.content;\n if (typeof preview === \"string\") content.settings.preheaderText = preview;\n for (const language of languages) {\n const locale = localeTag(language.key, warnings);\n if (!locale) continue;\n for (const [uid, translation] of Object.entries(\n language.translations ?? {},\n )) {\n if (uid === \"mj-subject\") {\n warn(\n warnings,\n `Dropped language \"${locale}\" mj-subject: the host owns this field.`,\n );\n continue;\n }\n if (locale === content.settings.locale) continue;\n if (uid === \"mj-preview\") {\n if (typeof translation.content === \"string\")\n text(\n content.settings,\n locale,\n \"preheaderText\",\n content.settings.preheaderText,\n translation.content,\n );\n continue;\n }\n const target = uidMap.get(uid);\n const block = target?.block;\n if (!block || block.type === \"html\") {\n warn(\n warnings,\n `Dropped language \"${locale}\" translation for uid \"${uid}\": target converted to ${block ? \"HTML fallback\" : \"null\"}.`,\n );\n continue;\n }\n if (typeof translation.content === \"string\") {\n const converted = convertLeaf(\n { ...target.node, content: translation.content },\n ctx,\n )?.block;\n if (\n (block.type === \"title\" || block.type === \"paragraph\") &&\n converted &&\n (converted.type === \"title\" || converted.type === \"paragraph\")\n )\n text(block, locale, \"content\", block.content, converted.content);\n else if (block.type === \"button\" && converted?.type === \"button\")\n text(block, locale, \"text\", block.text, converted.text);\n else\n warn(\n warnings,\n `Dropped language \"${locale}\" content for uid \"${uid}\": no language mapping for this format.`,\n );\n }\n for (const [key, value] of Object.entries(translation.attributes ?? {})) {\n if (typeof value !== \"string\") continue;\n if (key === \"alt\" && block.type === \"image\")\n text(block, locale, \"alt\", block.alt, value);\n else if (key === \"href\" && block.type === \"button\")\n set(block, locale, \"url\", value);\n else if (key === \"href\" && block.type === \"image\")\n set(block, locale, \"linkUrl\", value);\n else if (key === \"src\" && block.type === \"image\")\n set(block, locale, \"src\", value);\n else\n warn(\n warnings,\n `Dropped language \"${locale}\" attribute \"${key}\" for uid \"${uid}\": no language mapping for this format.`,\n );\n }\n }\n }\n registerLocales(content);\n const versions = languages\n .map((language) => localeTag(language.key, warnings))\n .filter(\n (locale): locale is string =>\n locale !== null && locale !== content.settings.locale,\n );\n if (versions.length) content.settings.locales = [...new Set(versions)];\n\n const summary = {\n total: entries.length,\n converted: entries.filter((e) => e.status === \"converted\").length,\n approximated: entries.filter((e) => e.status === \"approximated\").length,\n htmlFallback: entries.filter((e) => e.status === \"html-fallback\").length,\n skipped: entries.filter((e) => e.status === \"skipped\").length,\n };\n\n const report: ImportReport = { entries, warnings, summary };\n\n return { content, report };\n}\n\nfunction safeParse(source: string): unknown {\n try {\n return JSON.parse(source);\n } catch {\n throw new Error(INVALID_DESIGN_MESSAGE);\n }\n}\n"],"mappings":";;AAWA,MAAM,+BAAe,IAAI,QAGvB;AAEF,SAAgB,KAAK,UAAoB,SAAu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/content-inference.ts","../src/global-style.ts","../src/block-mapper.ts","../src/social-mapper.ts","../src/section-builder.ts","../src/converter.ts"],"sourcesContent":["import { isLocaleTag, sourceHash } from \"@templatical/types\";\nimport type {\n Block,\n BlockLocaleLayer,\n TemplateContent,\n} from \"@templatical/types\";\n\ntype Target = { l10n?: Record<string, BlockLocaleLayer> };\n\n// Callers also push to `warnings` directly, so each set catches up on the\n// entries appended since the last call instead of being the only record.\nconst seenWarnings = new WeakMap<\n string[],\n { set: Set<string>; size: number }\n>();\n\nexport function warn(warnings: string[], message: string): void {\n let seen = seenWarnings.get(warnings);\n if (!seen || seen.size > warnings.length) {\n seen = { set: new Set(), size: 0 };\n seenWarnings.set(warnings, seen);\n }\n for (; seen.size < warnings.length; seen.size++) {\n seen.set.add(warnings[seen.size]);\n }\n if (seen.set.has(message)) return;\n warnings.push(message);\n seen.set.add(message);\n seen.size++;\n}\n\nexport function localeTag(value: string, warnings: string[]): string | null {\n const locale = value.replaceAll(\"_\", \"-\");\n if (isLocaleTag(locale)) return locale;\n warn(warnings, `Dropped language \"${value}\": unsupported language tag.`);\n return null;\n}\n\n/** The `defaultLocale` option as a tag; `null`, with a warning, when it isn't one. */\nexport function defaultLocaleOption(\n value: string | undefined,\n warnings: string[],\n): string | null {\n if (!value) return null;\n const locale = value.replaceAll(\"_\", \"-\");\n if (isLocaleTag(locale)) return locale;\n warn(\n warnings,\n `Ignored defaultLocale \"${value}\": unsupported language tag. Used \"en\".`,\n );\n return null;\n}\n\nexport function text(\n target: Target,\n locale: string,\n path: string,\n base: string | undefined,\n value: string,\n): void {\n if (base === undefined) {\n set(target, locale, path, value);\n return;\n }\n const layer = ((target.l10n ??= {})[locale] ??= {});\n (layer.text ??= {})[path] = { value, sourceHash: sourceHash(base) };\n}\n\nexport function set(\n target: Target,\n locale: string,\n path: string,\n value: unknown,\n): void {\n const layer = ((target.l10n ??= {})[locale] ??= {});\n (layer.set ??= {})[path] = value;\n}\n\n/** Register only non-default versions, leaving single-language imports unchanged. */\nexport function registerLocales(content: TemplateContent): void {\n const locales = new Set<string>();\n const visit = (target: Target) => {\n if (!target.l10n) return;\n delete target.l10n[content.settings.locale];\n for (const locale of Object.keys(target.l10n)) locales.add(locale);\n if (Object.keys(target.l10n).length === 0) delete target.l10n;\n };\n visit(content.settings);\n const walk = (blocks: Block[]) => {\n for (const block of blocks) {\n visit(block);\n if (block.type === \"section\") block.children.forEach(walk);\n }\n };\n walk(content.blocks);\n if (locales.size) content.settings.locales = [...locales];\n}\n","import type {\n BackgroundImage,\n BackgroundPositionX,\n BackgroundPositionY,\n BackgroundSize,\n SpacingValue,\n} from \"@templatical/types\";\nimport type { TopolNode } from \"./types\";\n\n/**\n * Read one attribute as a string, treating Topol's explicit `null` — and an\n * empty string — as absent.\n *\n * Topol writes literal `null` for an unset attribute rather than omitting the\n * key, so a `!== undefined` check would report it as present and write a null\n * into the block. Every optional-field read goes through here.\n */\nexport function attr(node: TopolNode, key: string): string | undefined {\n const raw = node.attributes?.[key];\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"object\") return undefined;\n const value = String(raw);\n return value === \"\" ? undefined : value;\n}\n\n/** Read one attribute as a number, or `undefined` when unset or non-numeric. */\nexport function numAttr(node: TopolNode, key: string): number | undefined {\n const value = attr(node, key);\n if (value === undefined) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a px-like value into a rounded integer. Returns 0 for a missing value\n * and for units the block model cannot express (em, rem, %).\n *\n * Trims first, then matches with no `\\s*` on either side of the optional\n * `px` unit. A trailing run of spaces can otherwise be claimed by either the\n * surrounding `\\s*` or by backtracking out of the digit/unit match, and a\n * *failing* match (no `px`, no digits — anything not shaped like a length)\n * retries every such split before giving up: `\"0\" + \" \".repeat(n) + \"x\"` is\n * polynomial in `n` against that pattern. Trimming first removes the only\n * whitespace the pattern needs to tolerate, so the match itself has nothing\n * ambiguous left to backtrack over.\n */\nexport function parsePxValue(value: string | number | undefined): number {\n if (value === undefined || value === null || value === \"\") return 0;\n if (typeof value === \"number\") return Math.round(value);\n const trimmed = value.trim();\n const match = /^(-?\\d+(?:\\.\\d+)?)(?:px)?$/.exec(trimmed);\n return match ? Math.round(parseFloat(match[1])) : 0;\n}\n\nconst NAMED_COLORS: Record<string, string> = {\n black: \"#000000\",\n white: \"#ffffff\",\n red: \"#ff0000\",\n green: \"#008000\",\n blue: \"#0000ff\",\n yellow: \"#ffff00\",\n cyan: \"#00ffff\",\n magenta: \"#ff00ff\",\n gray: \"#808080\",\n grey: \"#808080\",\n silver: \"#c0c0c0\",\n maroon: \"#800000\",\n olive: \"#808000\",\n lime: \"#00ff00\",\n aqua: \"#00ffff\",\n teal: \"#008080\",\n navy: \"#000080\",\n fuchsia: \"#ff00ff\",\n purple: \"#800080\",\n orange: \"#ffa500\",\n pink: \"#ffc0cb\",\n};\n\nfunction rgbToHex(r: number, g: number, b: number): string {\n const clamp = (n: number) => Math.max(0, Math.min(255, Math.round(n)));\n const hex = (n: number) => clamp(n).toString(16).padStart(2, \"0\");\n return `#${hex(r)}${hex(g)}${hex(b)}`;\n}\n\nconst RGB_COLOR =\n /^rgb(a?)\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+)\\s*)?\\)$/;\n\n/** Use the same parsed alpha for transparent button fills as for colors. */\nexport function isZeroAlphaRgba(value: string | undefined): boolean {\n const rgb = RGB_COLOR.exec(value?.trim().toLowerCase() ?? \"\");\n return (\n rgb !== null &&\n rgb[1] === \"a\" &&\n rgb[5] !== undefined &&\n Number(rgb[5]) === 0\n );\n}\n\n/**\n * Normalize an opaque colour to 6-digit lowercase hex. A partly transparent\n * rgba() value stays in CSS form so its alpha is not lost.\n *\n * Returns `\"\"` for transparent/inherit/none and for anything unrecognised —\n * the empty string is the block model's \"unset\", which the colour pickers\n * clear to, so it is meaningfully different from returning a default.\n */\nexport function parseColor(value: string | undefined): string {\n if (!value) return \"\";\n const trimmed = value.trim().toLowerCase();\n if (trimmed === \"transparent\" || trimmed === \"inherit\" || trimmed === \"none\")\n return \"\";\n if (/^#[0-9a-f]{6}$/.test(trimmed)) return trimmed;\n if (/^#[0-9a-f]{3}$/.test(trimmed)) {\n const [, r, g, b] = trimmed;\n return `#${r}${r}${g}${g}${b}${b}`;\n }\n const rgb = RGB_COLOR.exec(trimmed);\n if (rgb) {\n const alpha = rgb[5] === undefined ? 1 : Number(rgb[5]);\n if (!Number.isFinite(alpha)) return \"\";\n if (rgb[1] === \"a\" && alpha === 0) return \"\";\n if (rgb[1] === \"a\" && alpha > 0 && alpha < 1) return trimmed;\n return rgbToHex(+rgb[2], +rgb[3], +rgb[4]);\n }\n return Object.hasOwn(NAMED_COLORS, trimmed) ? NAMED_COLORS[trimmed] : \"\";\n}\n\nfunction expandShorthand(value: string | undefined): SpacingValue {\n if (!value) return { top: 0, right: 0, bottom: 0, left: 0 };\n const v = value\n .trim()\n .split(/\\s+/)\n .map((p) => parsePxValue(p));\n switch (v.length) {\n case 1:\n return { top: v[0], right: v[0], bottom: v[0], left: v[0] };\n case 2:\n return { top: v[0], right: v[1], bottom: v[0], left: v[1] };\n case 3:\n return { top: v[0], right: v[1], bottom: v[2], left: v[1] };\n default:\n return { top: v[0], right: v[1], bottom: v[2], left: v[3] };\n }\n}\n\n/**\n * Read a node's padding, handling both forms Topol emits: a shorthand string\n * (`\"9px 9px 9px 9px\"`, used by most leaves) and four separate bare-number\n * keys (`padding-top: 24`, used by `mj-divider`). A separate key wins over the\n * shorthand for its own side.\n */\nexport function parsePadding(node: TopolNode): SpacingValue {\n const base = expandShorthand(attr(node, \"padding\"));\n const side = (key: string, fallback: number) => {\n const value = attr(node, key);\n return value === undefined ? fallback : parsePxValue(value);\n };\n return {\n top: side(\"padding-top\", base.top),\n right: side(\"padding-right\", base.right),\n bottom: side(\"padding-bottom\", base.bottom),\n left: side(\"padding-left\", base.left),\n };\n}\n\n/**\n * Read a percentage. Returns `null` when the value is not a percentage, so a\n * caller can tell \"no width given\" from \"0%\" — column matching depends on that\n * distinction.\n */\nexport function parsePercent(\n value: string | number | undefined,\n): number | null {\n if (value === undefined || value === null || value === \"\") return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*%$/);\n return match ? parseFloat(match[1]) : null;\n}\n\n/** Narrow an alignment to the three the block model accepts. */\nexport function parseAlignment(\n value: string | undefined,\n fallback: \"left\" | \"center\" | \"right\" = \"left\",\n): \"left\" | \"center\" | \"right\" {\n const v = (value ?? \"\").trim().toLowerCase();\n return v === \"left\" || v === \"center\" || v === \"right\" ? v : fallback;\n}\n\n/** Narrow a border style to the three `DividerBlock.lineStyle` accepts. */\nexport function parseBorderStyle(\n value: string | undefined,\n): \"solid\" | \"dashed\" | \"dotted\" {\n const v = (value ?? \"\").trim().toLowerCase();\n return v === \"dashed\" || v === \"dotted\" ? v : \"solid\";\n}\n\n/** A background image read from the source, with a note for each value that had no exact keyword. */\nexport interface ReadBackgroundImage {\n image: BackgroundImage;\n notes: string[];\n}\n\nconst X_GRID = [\"left\", \"center\", \"right\"] as const;\nconst Y_GRID = [\"top\", \"center\", \"bottom\"] as const;\nconst PERCENT = /^(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))%$/;\nconst LENGTH = /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)[a-z]*$/;\n\n/** What MJML paints for a `background-*` attribute an `mj-section` / `mj-wrapper` leaves out. */\nconst MJML_BACKGROUND_DEFAULTS = {\n size: \"auto\",\n x: \"center\",\n y: \"top\",\n repeat: true,\n} as const;\n\n/**\n * `background-size` as a keyword. A size with a side at 100%, or a px width\n * spanning the box, fills it as `cover` does; any other length or percentage\n * draws the image at a size of its own, which `auto` is closest to.\n */\nfunction backgroundSizeKeyword(\n raw: string,\n boxWidth: number | undefined,\n): { size: BackgroundSize; exact: boolean } {\n const parts = raw.toLowerCase().split(/\\s+/);\n const [first] = parts;\n if (parts.length === 1 && (first === \"cover\" || first === \"contain\")) {\n return { size: first, exact: true };\n }\n if (parts.every((part) => part === \"auto\")) {\n return { size: \"auto\", exact: true };\n }\n const px = /^(\\d+(?:\\.\\d+)?|\\.\\d+)px$/.exec(first);\n const fills =\n parts.includes(\"100%\") ||\n (px !== null && boxWidth !== undefined && Number(px[1]) >= boxWidth);\n return { size: fills ? \"cover\" : \"auto\", exact: false };\n}\n\n/**\n * `background-position` split into x and y the way MJML and CSS read it: a\n * lone `top` / `bottom` names y and centres x, any other lone value is x\n * with y centred, and a pair is x then y unless it leads with `top` /\n * `bottom` (or with `center` before `left` / `right`). Three- and four-value\n * edge offsets keep their edge keywords only.\n */\nfunction splitBackgroundPosition(raw: string): {\n x: string;\n y: string;\n exact: boolean;\n} {\n const parts = raw.toLowerCase().split(/\\s+/);\n if (parts.length === 1) {\n const [only] = parts;\n return only === \"top\" || only === \"bottom\"\n ? { x: \"center\", y: only, exact: true }\n : { x: only, y: \"center\", exact: true };\n }\n if (parts.length === 2) {\n const [a, b] = parts;\n const yFirst =\n a === \"top\" ||\n a === \"bottom\" ||\n (a === \"center\" && (b === \"left\" || b === \"right\"));\n return yFirst ? { x: b, y: a, exact: true } : { x: a, y: b, exact: true };\n }\n return {\n x: parts.find((part) => part === \"left\" || part === \"right\") ?? \"center\",\n y: parts.find((part) => part === \"top\" || part === \"bottom\") ?? \"center\",\n exact: false,\n };\n}\n\n/**\n * One axis as a grid point: its keyword; the point nearest a percentage,\n * ties going to the centre; or the start edge for a length, which is an\n * offset from it. `null` when the token is unreadable.\n */\nfunction backgroundAxisPoint<T extends string>(\n token: string,\n grid: readonly [T, T, T],\n): { point: T; exact: boolean } | null {\n const keyword = grid.find((point) => point === token);\n if (keyword) return { point: keyword, exact: true };\n const percent = PERCENT.exec(token);\n if (percent) {\n const n = Number(percent[1]);\n return {\n point: n < 25 ? grid[0] : n > 75 ? grid[2] : grid[1],\n exact: n === 0 || n === 50 || n === 100,\n };\n }\n if (LENGTH.test(token)) {\n return { point: grid[0], exact: parseFloat(token) === 0 };\n }\n return null;\n}\n\n/**\n * `background-repeat`: unrepeated only when every axis is `no-repeat`.\n * Anything but plain `repeat` tiles too, inexactly.\n */\nfunction backgroundRepeatFlag(raw: string): {\n repeat: boolean;\n exact: boolean;\n} {\n const parts = raw.toLowerCase().split(/\\s+/);\n if (parts.every((part) => part === \"no-repeat\")) {\n return { repeat: false, exact: true };\n }\n return { repeat: true, exact: parts.every((part) => part === \"repeat\") };\n}\n\n/**\n * An `mj-section` / `mj-wrapper` background image, `null` when\n * `background-url` is absent or blank. `read` returns an attribute's\n * resolved value. Unset attributes take MJML's own defaults, so the import\n * paints what MJML painted; a value with no exact keyword takes the nearest\n * one and adds a note naming it. `label` names the element in each note, and\n * a px `background-size` is measured against `boxWidth`.\n */\nexport function readMjmlBackgroundImage(\n read: (name: string) => string | undefined,\n label: string,\n boxWidth: number | undefined,\n): ReadBackgroundImage | null {\n const url = (read(\"background-url\") ?? \"\").trim();\n if (!url) return null;\n\n const notes: string[] = [];\n const lossy = (name: string, raw: string, shown: string): void => {\n notes.push(\n `${label} ${name} \"${raw}\" has no exact Templatical equivalent; imported as \"${shown}\".`,\n );\n };\n\n let size: BackgroundSize = MJML_BACKGROUND_DEFAULTS.size;\n const rawSize = read(\"background-size\")?.trim();\n if (rawSize) {\n const parsed = backgroundSizeKeyword(rawSize, boxWidth);\n size = parsed.size;\n if (!parsed.exact) lossy(\"background-size\", rawSize, size);\n }\n\n let x: BackgroundPositionX = MJML_BACKGROUND_DEFAULTS.x;\n let y: BackgroundPositionY = MJML_BACKGROUND_DEFAULTS.y;\n let lossyX = false;\n let lossyY = false;\n const rawPosition = read(\"background-position\")?.trim();\n if (rawPosition) {\n const split = splitBackgroundPosition(rawPosition);\n const readX = backgroundAxisPoint(split.x, X_GRID);\n const readY = backgroundAxisPoint(split.y, Y_GRID);\n x = readX?.point ?? x;\n y = readY?.point ?? y;\n lossyX = !split.exact || !readX?.exact;\n lossyY = !split.exact || !readY?.exact;\n }\n // A readable `-x` / `-y` replaces its axis, and with it whatever the\n // position lost there; the position's note then names what was imported.\n const rawX = read(\"background-position-x\")?.trim();\n const overrideX = rawX\n ? backgroundAxisPoint(rawX.toLowerCase(), X_GRID)\n : null;\n if (overrideX) {\n x = overrideX.point;\n lossyX = false;\n }\n const rawY = read(\"background-position-y\")?.trim();\n const overrideY = rawY\n ? backgroundAxisPoint(rawY.toLowerCase(), Y_GRID)\n : null;\n if (overrideY) {\n y = overrideY.point;\n lossyY = false;\n }\n if (rawPosition && (lossyX || lossyY)) {\n lossy(\"background-position\", rawPosition, `${x} ${y}`);\n }\n if (rawX && !overrideX?.exact) lossy(\"background-position-x\", rawX, x);\n if (rawY && !overrideY?.exact) lossy(\"background-position-y\", rawY, y);\n\n let repeat: boolean = MJML_BACKGROUND_DEFAULTS.repeat;\n const rawRepeat = read(\"background-repeat\")?.trim();\n if (rawRepeat) {\n const parsed = backgroundRepeatFlag(rawRepeat);\n repeat = parsed.repeat;\n if (!parsed.exact) {\n lossy(\"background-repeat\", rawRepeat, repeat ? \"repeat\" : \"no-repeat\");\n }\n }\n\n return { image: { url, size, position: { x, y }, repeat }, notes };\n}\n","import { findOpenTagEnd } from \"@templatical/types\";\nimport type { HeadingLevel } from \"@templatical/types\";\n\nexport type InferredText =\n | { kind: \"title\"; level: HeadingLevel; inner: string; clampedFrom?: number }\n | { kind: \"paragraph\"; html: string };\n\n/**\n * A single heading element wrapping the whole content, captured with its level\n * and inner markup. Anchored at both ends, so a fragment that ends on a\n * different tag does not match. The inner group is greedy, so two headings of\n * the same level still match and the first close sits inside that group. The\n * match is a title only when the inner HTML has no earlier real close of this\n * level: one heading with inline markup stays a title, and a sibling heading\n * stays a paragraph.\n */\nconst SOLE_HEADING = /^<h([1-6])(?:\\s[^>]*)?>([\\s\\S]*)<\\/h\\1\\s*>$/i;\n\nconst BLOCK_ROOT = /^<(p|h[1-6]|ul|ol|blockquote|div|table)\\b/i;\nconst HEADING_CLOSE = /^<\\/h([1-6])\\s*>$/i;\n\n/** Ignore comments and quoted attribute values while finding an earlier heading close. */\nfunction hasEarlierHeadingClose(html: string, level: string): boolean {\n let cursor = 0;\n while (cursor < html.length) {\n const open = html.indexOf(\"<\", cursor);\n if (open === -1) return false;\n if (html.startsWith(\"<!--\", open)) {\n const end = html.indexOf(\"-->\", open + 4);\n if (end === -1) return false;\n cursor = end + 3;\n continue;\n }\n const next = html.charCodeAt(open + 1);\n if (\n next !== 47 && // /\n next !== 33 && // !\n !(next >= 65 && next <= 90) &&\n !(next >= 97 && next <= 122)\n ) {\n cursor = open + 1;\n continue;\n }\n const end = findOpenTagEnd(html, open + 1);\n if (end === -1) return false;\n const close = HEADING_CLOSE.exec(html.slice(open, end + 1));\n if (close?.[1] === level) return true;\n cursor = end + 1;\n }\n return false;\n}\n\n/**\n * Resolve a Topol `content` string to a Title or a Paragraph.\n *\n * Topol has no menu or table construct, so this is a two-way choice — the MJML\n * importer needs four arms because `mj-text` is the output of four different\n * block renderers there. Paragraph is the terminal arm and always reachable,\n * so this function is total.\n */\nexport function inferTextBlock(content: string | undefined): InferredText {\n const trimmed = (content ?? \"\").trim();\n if (trimmed === \"\") return { kind: \"paragraph\", html: \"<p></p>\" };\n\n const heading = trimmed.match(SOLE_HEADING);\n // Same-level siblings end on the same tag, so the greedy match above\n // swallows both. The first close has to end the fragment.\n if (heading?.[1] && !hasEarlierHeadingClose(heading[2], heading[1])) {\n const source = Number(heading[1]);\n const level = Math.min(source, 4) as HeadingLevel;\n return {\n kind: \"title\",\n level,\n inner: heading[2].trim(),\n ...(source > 4 ? { clampedFrom: source } : {}),\n };\n }\n\n return {\n kind: \"paragraph\",\n html: BLOCK_ROOT.test(trimmed) ? trimmed : `<p>${trimmed}</p>`,\n };\n}\n\nconst ENTITIES: Record<string, string> = {\n \"&amp;\": \"&\",\n \"&lt;\": \"<\",\n \"&gt;\": \">\",\n \"&quot;\": '\"',\n \"&#39;\": \"'\",\n \"&apos;\": \"'\",\n \"&nbsp;\": \" \",\n};\n\n/**\n * Named references Topol emits, plus a decimal (`&#38;`) or hex (`&#x26;`,\n * `&#X26;`) numeric reference. A code point that is not a Unicode scalar —\n * zero, a surrogate, or past U+10FFFF — stays literal text, because\n * `String.fromCodePoint` throws on those and would abort the import. One\n * pass, and only the names above: `&#38;lt;` becomes the text `&lt;`, and\n * `&copy;` is left as written.\n */\nconst TEXT_ENTITY =\n /&(?:amp|lt|gt|quot|#39|apos|nbsp|#[0-9]+|#[xX][0-9a-fA-F]+);/g;\n\nfunction decodeTextEntity(match: string): string {\n const named = ENTITIES[match];\n if (named !== undefined) return named;\n const body = match.slice(1, -1);\n const hex = body[1] === \"x\" || body[1] === \"X\";\n const code = Number.parseInt(body.slice(hex ? 2 : 1), hex ? 16 : 10);\n if (code < 1 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff))\n return match;\n return String.fromCodePoint(code);\n}\n\n/**\n * Remove every `<tag>` from `html`, keeping the text between them.\n *\n * A single-pass linear scan rather than `/<[^>]*>/g`: that regex is\n * polynomial over input with many `<` starts and no closing `>`, since\n * `[^>]*` backtracks at every one of them — `\"<\".repeat(n)` is quadratic in\n * `n`. `findOpenTagEnd` (from `@templatical/types`) resolves each `<` with a\n * bounded, quote-aware forward scan instead, so the walk stays O(n): every\n * character is visited at most once by `indexOf` and once by\n * `findOpenTagEnd`, because the cursor only moves forward and an\n * unterminated tag ends the walk rather than retrying from inside it. On\n * that unterminated case the remainder of the string — the dangling `<`\n * included — is emitted as-is, matching what `/<[^>]*>/g` does with\n * malformed markup: it can never complete a match without a `>`, so the\n * text is left untouched from that point on.\n */\nfunction removeTags(html: string): string {\n let out = \"\";\n let i = 0;\n while (i < html.length) {\n const open = html.indexOf(\"<\", i);\n if (open === -1) {\n out += html.substring(i);\n break;\n }\n out += html.substring(i, open);\n const tagEnd = findOpenTagEnd(html, open + 1);\n if (tagEnd === -1) {\n out += html.substring(open);\n break;\n }\n i = tagEnd + 1;\n }\n return out;\n}\n\n/**\n * The visible text of a markup fragment, for a button label — `ButtonBlock.text`\n * is a plain string, so the markup Topol stores in `content` cannot travel.\n */\nexport function stripTags(html: string | undefined): string {\n if (!html) return \"\";\n const text = removeTags(html);\n const decoded = text.replace(TEXT_ENTITY, decodeTextEntity);\n return decoded.replace(/\\s+/g, \" \").trim();\n}\n","import {\n canonicalFontStack,\n DEFAULT_TEMPLATE_DEFAULTS,\n} from \"@templatical/types\";\nimport type { TemplateContent, TemplateSettings } from \"@templatical/types\";\nimport { attr, parseColor, parsePxValue } from \"./attribute-parser\";\nimport type { TopolDesign, TopolNode } from \"./types\";\n\n/**\n * `DEFAULT_TEMPLATE_DEFAULTS` is typed `Partial<TemplateSettings>` so a\n * consumer can override any subset, but its own literal always sets the six\n * required fields. Narrowing once here is what lets each read come out as\n * `number`/`string`/`boolean` rather than `| undefined`. A plain typed\n * assignment cannot substitute: `Partial<T>` is not assignable to\n * `Required<Pick<T, …>>`, so `tsc` rejects it outright.\n */\nconst REQUIRED_DEFAULTS = DEFAULT_TEMPLATE_DEFAULTS as Required<\n Pick<\n TemplateSettings,\n | \"width\"\n | \"backgroundColor\"\n | \"textColor\"\n | \"linkUnderline\"\n | \"fontFamily\"\n | \"locale\"\n >\n>;\n\nexport interface GlobalStyle {\n settings: TemplateContent[\"settings\"];\n /** From nested objects like `\"mj-text\": { … }`. */\n tagDefaults: Record<string, Record<string, string>>;\n /** From flat `<selector>:<property>` keys; the bare selector is `\"\"`. */\n selectorDefaults: Record<string, Record<string, string>>;\n}\n\n/** A per-tag default, or undefined when the design sets none. */\nexport function tagDefault(\n style: GlobalStyle,\n tag: string,\n key: string,\n): string | undefined {\n return style.tagDefaults[tag]?.[key];\n}\n\n/** A per-selector default (`\"\"` is the document default), or undefined. */\nexport function selectorDefault(\n style: GlobalStyle,\n selector: string,\n key: string,\n): string | undefined {\n return style.selectorDefaults[selector]?.[key];\n}\n\n/**\n * Split the root's `attributes` into settings, per-tag defaults and\n * per-selector defaults.\n *\n * The root mixes two idioms: `<selector>:<property>` flat keys (`:color`,\n * `a:color`, `h1:font-family`) and `<tag>: { … }` nested objects, which are\n * the analogue of MJML's `mj-attributes`.\n */\nexport function readGlobalStyle(\n root: TopolDesign,\n container: TopolNode | undefined,\n warnings: string[],\n): GlobalStyle {\n const tagDefaults: Record<string, Record<string, string>> = Object.create(\n null,\n );\n const selectorDefaults: Record<\n string,\n Record<string, string>\n > = Object.create(null);\n\n for (const [key, value] of Object.entries(root.attributes ?? {})) {\n if (value !== null && typeof value === \"object\") {\n const bucket = (tagDefaults[key] ??= Object.create(null));\n for (const [k, v] of Object.entries(value)) {\n if (v !== null && v !== undefined) bucket[k] = String(v);\n }\n continue;\n }\n\n const colon = key.indexOf(\":\");\n // No colon means a root-level setting rather than a selector default —\n // `containerWidth` and `fonts` are the two real cases, and both are read\n // directly by name below instead of through the caches built here.\n if (colon === -1) continue;\n const selector = key.slice(0, colon);\n const property = key.slice(colon + 1);\n if (value === null || value === undefined) continue;\n const bucket = (selectorDefaults[selector] ??= Object.create(null));\n bucket[property] = String(value);\n }\n\n // containerWidth is authored only here, on the root. It is also denormalised\n // onto every leaf as the enclosing column's computed width (600/300/150 in\n // one template), so no other module may read it.\n const width =\n parsePxValue(attr(root, \"containerWidth\")) || REQUIRED_DEFAULTS.width;\n\n const backgroundColor =\n (container ? parseColor(attr(container, \"background-color\")) : \"\") ||\n REQUIRED_DEFAULTS.backgroundColor;\n\n const textColor =\n parseColor(selectorDefaults[\"\"]?.color) || REQUIRED_DEFAULTS.textColor;\n\n const fontFamily =\n canonicalFontStack(selectorDefaults[\"\"]?.[\"font-family\"]) ||\n canonicalFontStack(attr(root, \"fonts\")) ||\n REQUIRED_DEFAULTS.fontFamily;\n\n const linkColor = parseColor(selectorDefaults[\"a\"]?.color);\n\n const lineHeight = selectorDefaults[\"\"]?.[\"line-height\"];\n if (lineHeight !== undefined) {\n warnings.push(\n `Dropped the document line-height (${lineHeight}) — Templatical has no document-level line-height setting.`,\n );\n }\n\n const settings: TemplateContent[\"settings\"] = {\n width,\n backgroundColor,\n textColor,\n linkUnderline: REQUIRED_DEFAULTS.linkUnderline,\n fontFamily,\n locale: REQUIRED_DEFAULTS.locale,\n ...(linkColor ? { linkColor } : {}),\n };\n\n return { settings, tagDefaults, selectorDefaults };\n}\n","import {\n BUTTON_BLOCK_DEFAULTS,\n BUTTON_LINE_HEIGHT,\n canonicalFontStack,\n createButtonBlock,\n createDividerBlock,\n createHtmlBlock,\n createImageBlock,\n createParagraphBlock,\n createSpacerBlock,\n createTitleBlock,\n findOpenTagEnd,\n getTagAttrValue,\n roundHundredths,\n} from \"@templatical/types\";\nimport type { Block, BlockStyles } from \"@templatical/types\";\nimport {\n attr,\n isZeroAlphaRgba,\n numAttr,\n parseAlignment,\n parseBorderStyle,\n parseColor,\n parsePadding,\n parsePxValue,\n} from \"./attribute-parser\";\nimport { inferTextBlock, stripTags } from \"./content-inference\";\nimport { selectorDefault, tagDefault, type GlobalStyle } from \"./global-style\";\nimport type { ImportReportEntry, TopolNode } from \"./types\";\n\nexport interface MapContext {\n uidMap?: Map<string, { node: TopolNode; block: Block | null }>;\n style: GlobalStyle;\n /** The rendered width of the column holding this node, for `width: \"full\"`. */\n columnWidth: number;\n}\n\nexport interface Converted {\n block: Block | null;\n entry: ImportReportEntry;\n}\n\n/**\n * Read a node's own attribute, falling back to the design's per-tag then\n * per-selector default. Returns undefined when nothing sets it, so the caller\n * can omit the field and let the block factory's default stand.\n */\nfunction resolved(\n node: TopolNode,\n key: string,\n ctx: MapContext,\n selector?: string,\n): string | undefined {\n return (\n attr(node, key) ??\n tagDefault(ctx.style, node.tagName, key) ??\n (selector === undefined\n ? undefined\n : selectorDefault(ctx.style, selector, key))\n );\n}\n\n/**\n * The `styles` every leaf block shares.\n *\n * The block background is the row behind the element, which MJML reads from\n * `container-background-color` on every leaf and which the renderer writes\n * `styles.backgroundColor` back out as. A leaf's `background-color` must not\n * feed it: on `mj-button` it is the button face (`backgroundColor`, read in\n * `convertButton`), on `mj-text` MJML never paints it, and on image, spacer,\n * divider and social it is invalid and dropped. Reading it here paints a\n * button's whole row in its fill colour. `buildSection` reads\n * `background-color` itself, since on `mj-section` it is the section's fill.\n */\nexport function baseStyles(\n node: TopolNode,\n ctx: MapContext,\n): { styles: BlockStyles } {\n const backgroundColor = parseColor(attr(node, \"container-background-color\"));\n const localPadding = attr(node, \"padding\");\n const side = (name: string) =>\n attr(node, name) ?? tagDefault(ctx.style, node.tagName, name);\n const padding = parsePadding({\n tagName: node.tagName,\n attributes: {\n padding: localPadding ?? tagDefault(ctx.style, node.tagName, \"padding\"),\n \"padding-top\": side(\"padding-top\"),\n \"padding-right\": side(\"padding-right\"),\n \"padding-bottom\": side(\"padding-bottom\"),\n \"padding-left\": side(\"padding-left\"),\n },\n });\n return {\n styles: {\n padding,\n ...(backgroundColor ? { backgroundColor } : {}),\n },\n };\n}\n\ntype TextAlignment = \"left\" | \"center\" | \"right\" | \"justify\";\n\nfunction readTextAlignment(node: TopolNode): {\n value: TextAlignment | undefined;\n note?: string;\n} {\n const raw = attr(node, \"align\");\n if (raw === undefined) return { value: undefined };\n const value = raw.trim().toLowerCase();\n if (\n value === \"left\" ||\n value === \"center\" ||\n value === \"right\" ||\n value === \"justify\"\n )\n return { value };\n return {\n value: \"left\",\n note: `Text alignment \"${raw}\" imported as left.`,\n };\n}\n\nconst ALIGNABLE_TAGS = new Set([\n \"p\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"li\",\n \"ul\",\n \"ol\",\n \"div\",\n \"blockquote\",\n \"table\",\n \"td\",\n \"th\",\n]);\nconst VOID_TAGS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\nconst COLOR_DECLARATION = /(?:^|;)\\s*color\\s*:/i;\nconst ALIGN_DECLARATION = /(?:^|;)\\s*text-align\\s*:/i;\n\n/** Merge tags are text even when their expressions contain markup-like `<`. */\nfunction nextMarkupOpen(html: string, from: number): number {\n let at = from;\n while (at < html.length) {\n if (html[at] === \"{\") {\n const marker = html[at + 1];\n const close =\n marker === \"{\"\n ? \"}}\"\n : marker === \"%\"\n ? \"%}\"\n : marker === \"#\"\n ? \"#}\"\n : null;\n if (close !== null) {\n const end = html.indexOf(close, at + 2);\n if (end === -1) return -1;\n at = end + 2;\n continue;\n }\n }\n if (html[at] !== \"<\") {\n at++;\n continue;\n }\n const next = html[at + 1];\n const code = html.charCodeAt(at + 1);\n if (\n next === \"/\" ||\n next === \"!\" ||\n (code >= 65 && code <= 90) ||\n (code >= 97 && code <= 122)\n )\n return at;\n at++;\n }\n return -1;\n}\n\n/** Locate the first real style value, skipping quoted values of other attributes. */\nfunction styleValueEnd(tag: string, from: number): number | null {\n const limit = tag.length - 1;\n let i = from;\n while (i < limit) {\n while (i < limit && /[\\s/]/.test(tag[i])) i++;\n const nameStart = i;\n while (i < limit && !/[\\s=/>]/.test(tag[i])) i++;\n const name = tag.slice(nameStart, i).toLowerCase();\n while (i < limit && /\\s/.test(tag[i])) i++;\n if (tag[i] !== \"=\") continue;\n i++;\n while (i < limit && /\\s/.test(tag[i])) i++;\n const quote = tag[i];\n if (quote === '\"' || quote === \"'\") {\n // findOpenTagEnd already established that this quoted value closes.\n const end = tag.indexOf(quote, i + 1);\n if (name === \"style\") return end;\n i = end + 1;\n } else {\n while (i < limit && !/[\\s>]/.test(tag[i])) i++;\n if (name === \"style\") return i;\n }\n }\n return null;\n}\n\n/**\n * Whether an opening tag's attributes include `href`, with or without a value\n * (`<a href>` counts). Attribute names are read with their values skipped,\n * quoted or not, so `title=\"href\"` and `title= href` don't match. One pass.\n */\nfunction hasHrefAttribute(attrs: string): boolean {\n let i = 0;\n const isSpace = (c: string) =>\n c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\" || c === \"\\f\";\n while (i < attrs.length) {\n while (i < attrs.length && (isSpace(attrs[i]) || attrs[i] === \"/\")) i++;\n const nameStart = i;\n while (\n i < attrs.length &&\n !isSpace(attrs[i]) &&\n attrs[i] !== \"=\" &&\n attrs[i] !== \"/\"\n )\n i++;\n if (attrs.slice(nameStart, i).toLowerCase() === \"href\") return true;\n while (i < attrs.length && isSpace(attrs[i])) i++;\n if (attrs[i] !== \"=\") continue;\n i++;\n while (i < attrs.length && isSpace(attrs[i])) i++;\n const quote = attrs[i];\n if (quote === '\"' || quote === \"'\") {\n i++;\n while (i < attrs.length && attrs[i] !== quote) i++;\n i++;\n } else {\n while (i < attrs.length && !isSpace(attrs[i])) i++;\n }\n }\n return false;\n}\n\n/** Preserve existing inline declarations while writing Topol's text defaults onto editable nodes. */\nfunction paragraphHtmlStyles(\n html: string,\n color: string,\n align: TextAlignment | undefined,\n lossyAlignmentTags: Set<string>,\n): string {\n if (!color && align === undefined) return html;\n const parts: string[] = [];\n const stack: Array<{ name: string; colored: boolean; aligned: boolean }> = [];\n let cursor = 0;\n let colored = false;\n let aligned = false;\n while (cursor < html.length) {\n const open = nextMarkupOpen(html, cursor);\n const textEnd = open === -1 ? html.length : open;\n const run = html.slice(cursor, textEnd);\n parts.push(\n color && !colored && run.trim()\n ? `<span style=\"color:${color}\">${run}</span>`\n : run,\n );\n if (open === -1) break;\n const terminator = html.startsWith(\"<!--\", open)\n ? \"-->\"\n : html.startsWith(\"<![CDATA[\", open)\n ? \"]]>\"\n : null;\n if (terminator !== null) {\n const markerEnd = html.indexOf(\n terminator,\n open + (terminator === \"-->\" ? 4 : 9),\n );\n if (markerEnd === -1) {\n parts.push(html.slice(open));\n break;\n }\n parts.push(html.slice(open, markerEnd + 3));\n cursor = markerEnd + 3;\n continue;\n }\n const end = findOpenTagEnd(html, open + 1);\n if (end === -1) {\n parts.push(html.slice(open));\n break;\n }\n const tag = html.slice(open, end + 1);\n const close = /^<\\/([a-z][a-z0-9-]*)\\s*>$/i.exec(tag);\n if (close) {\n parts.push(tag);\n if (stack.at(-1)?.name === close[1].toLowerCase()) stack.pop();\n colored = stack.at(-1)?.colored ?? false;\n aligned = stack.at(-1)?.aligned ?? false;\n } else {\n const start = /^<([a-z][a-z0-9-]*)\\b/i.exec(tag);\n if (start) {\n const name = start[1].toLowerCase();\n const declarations =\n getTagAttrValue(tag.slice(start[0].length, -1), \"style\") ?? \"\";\n if (\n align !== undefined &&\n ALIGNABLE_TAGS.has(name) &&\n !aligned &&\n !ALIGN_DECLARATION.test(declarations)\n ) {\n const insertion = `${declarations && !declarations.endsWith(\";\") ? \";\" : \"\"}text-align:${align}`;\n const at = styleValueEnd(tag, start[0].length);\n if (at !== null) {\n parts.push(tag.slice(0, at), insertion, tag.slice(at));\n } else {\n parts.push(tag.slice(0, -1), ` style=\"${insertion}\">`);\n }\n if (name !== \"p\" && !/^h[1-6]$/.test(name))\n lossyAlignmentTags.add(name);\n } else {\n parts.push(tag);\n }\n if (!VOID_TAGS.has(name) && !/\\/\\s*>$/.test(tag)) {\n // A hyperlink (an `<a>` with an `href`, empty included) keeps the\n // link colour; an anchor without one is ordinary text.\n const hyperlink =\n name === \"a\" && hasHrefAttribute(tag.slice(start[0].length, -1));\n colored =\n colored || hyperlink || COLOR_DECLARATION.test(declarations);\n // Only source declarations block the node default on descendants.\n aligned = aligned || ALIGN_DECLARATION.test(declarations);\n stack.push({ name, colored, aligned });\n }\n } else {\n parts.push(tag);\n }\n }\n cursor = end + 1;\n }\n return parts.join(\"\");\n}\n\nfunction convertText(node: TopolNode, ctx: MapContext): Converted {\n const inferred = inferTextBlock(node.content);\n const alignment = readTextAlignment(node);\n\n if (inferred.kind === \"paragraph\") {\n const color = parseColor(resolved(node, \"color\", ctx));\n const lossyAlignmentTags = new Set<string>();\n const content = paragraphHtmlStyles(\n inferred.html,\n color,\n alignment.value,\n lossyAlignmentTags,\n );\n const lossyAlignmentNote = lossyAlignmentTags.size\n ? `Node alignment on ${[...lossyAlignmentTags].map((tag) => `<${tag}>`).join(\", \")} is lost after the first editor edit; the paragraph editor keeps alignment only on paragraphs.`\n : undefined;\n const notes = [alignment.note, lossyAlignmentNote].filter(\n (note): note is string => note !== undefined,\n );\n return {\n block: createParagraphBlock({\n content,\n ...baseStyles(node, ctx),\n }),\n entry: {\n sourceTag: \"mj-text\",\n templaticalBlockType: \"paragraph\",\n status: notes.length ? \"approximated\" : \"converted\",\n ...(notes.length ? { note: notes.join(\" \") } : {}),\n },\n };\n }\n\n const selector = `h${inferred.level}`;\n const color = parseColor(resolved(node, \"color\", ctx, selector));\n const fontFamily = canonicalFontStack(\n resolved(node, \"font-family\", ctx, selector),\n );\n\n const titleAlignment =\n alignment.value === \"justify\" ? \"left\" : (alignment.value ?? \"left\");\n const titleAlignmentNote =\n alignment.value === \"justify\"\n ? 'Title alignment \"justify\" imported as left — titles support left, center and right.'\n : alignment.note;\n const notes = [\n ...(inferred.clampedFrom\n ? [\n `Heading level h${inferred.clampedFrom} clamped to 4 — Templatical titles support h1-h4.`,\n ]\n : []),\n ...(titleAlignmentNote ? [titleAlignmentNote] : []),\n ];\n const block = createTitleBlock({\n content: inferred.inner,\n level: inferred.level,\n textAlign: titleAlignment,\n ...(color ? { color } : {}),\n ...(fontFamily ? { fontFamily } : {}),\n ...baseStyles(node, ctx),\n });\n\n return {\n block,\n entry: {\n sourceTag: \"mj-text\",\n templaticalBlockType: \"title\",\n status: notes.length ? \"approximated\" : \"converted\",\n ...(notes.length ? { note: notes.join(\" \") } : {}),\n },\n };\n}\n\n/**\n * A button's line height as `ButtonBlock.lineHeight`, a multiple of\n * `fontSize`. A percentage is that number over 100, a unitless number is\n * itself, a px length is that many pixels over `fontSize`, and an `em`\n * length is the number itself. A leading dot (`.5`) is read. Rounded to two\n * decimals. A missing value, `normal`, and a value that rounds to 1.2 stay\n * unset, so the label keeps `BUTTON_LINE_HEIGHT`. Any other value that\n * cannot be kept stays unset and pushes a note.\n */\nfunction readButtonLineHeight(\n value: unknown,\n fontSize: number,\n notes: string[],\n): number | undefined {\n const trimmed = String(value ?? \"\").trim();\n if (trimmed === \"\" || /^normal$/i.test(trimmed)) return undefined;\n\n const percent = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))\\s*%$/.exec(trimmed);\n const unitless = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))$/.exec(trimmed);\n const px = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))\\s*px$/i.exec(trimmed);\n const em = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+))\\s*em$/i.exec(trimmed);\n let ratio = Number.NaN;\n if (percent) ratio = Number(percent[1]) / 100;\n else if (unitless) ratio = Number(unitless[1]);\n else if (px) ratio = Number(px[1]) / fontSize;\n else if (em) ratio = Number(em[1]);\n\n const rounded = roundHundredths(ratio);\n if (!Number.isFinite(rounded) || !(rounded > 0)) {\n notes.push(\n `Button line-height \"${trimmed}\" could not be read; imported at 1.2.`,\n );\n return undefined;\n }\n return rounded === BUTTON_LINE_HEIGHT ? undefined : rounded;\n}\n\nfunction convertButton(node: TopolNode, ctx: MapContext): Converted | null {\n const text = stripTags(node.content);\n if (!text) return null;\n\n const rawBackground = resolved(node, \"background-color\", ctx, \"button\");\n const backgroundColor = parseColor(rawBackground);\n // The button factory has an opaque default, so an explicitly transparent\n // source fill must be written as the block model's transparent keyword.\n const transparentFill =\n rawBackground?.trim().toLowerCase() === \"transparent\" ||\n isZeroAlphaRgba(rawBackground);\n const textColor = parseColor(resolved(node, \"color\", ctx, \"button\"));\n const fontFamily = canonicalFontStack(\n resolved(node, \"font-family\", ctx, \"button\"),\n );\n // A stated font size that is not px, not finite, or not above 0, leaves the\n // factory size with a note, and a px line height is measured against the\n // size the label renders at.\n const factorySize = Number(BUTTON_BLOCK_DEFAULTS.fontSize);\n const statedFontSize = String(resolved(node, \"font-size\", ctx) ?? \"\").trim();\n const parsedFontSize = parsePxValue(statedFontSize);\n const fontSize =\n Number.isFinite(parsedFontSize) && parsedFontSize > 0\n ? parsedFontSize\n : undefined;\n const radiusRaw = resolved(node, \"border-radius\", ctx);\n const notes: string[] = [];\n if (statedFontSize !== \"\" && fontSize === undefined) {\n notes.push(\n `Button font-size \"${statedFontSize}\" could not be read; imported at ${factorySize}px.`,\n );\n }\n const lineHeight = readButtonLineHeight(\n resolved(node, \"line-height\", ctx, \"button\"),\n fontSize ?? factorySize,\n notes,\n );\n\n return {\n block: createButtonBlock({\n text,\n url: attr(node, \"href\") ?? \"\",\n ...(transparentFill\n ? { backgroundColor: \"transparent\" }\n : backgroundColor\n ? { backgroundColor }\n : {}),\n ...(textColor ? { textColor } : {}),\n ...(fontFamily ? { fontFamily } : {}),\n ...(fontSize !== undefined ? { fontSize } : {}),\n ...(lineHeight !== undefined ? { lineHeight } : {}),\n ...(radiusRaw === undefined\n ? {}\n : { borderRadius: parsePxValue(radiusRaw) }),\n align: parseAlignment(attr(node, \"align\"), \"center\"),\n ...baseStyles(node, ctx),\n }),\n entry: {\n sourceTag: node.tagName,\n templaticalBlockType: \"button\",\n status: notes.length > 0 ? \"approximated\" : \"converted\",\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n },\n };\n}\n\nfunction convertImage(\n node: TopolNode,\n ctx: MapContext,\n sourceTag: string,\n): Converted | null {\n const src = attr(node, \"src\");\n if (!src) return null;\n\n const widthPercent = numAttr(node, \"widthPercent\");\n const pxWidth = numAttr(node, \"width\");\n const href = attr(node, \"href\");\n const base = baseStyles(node, ctx);\n // MJML caps an image at its column less its own side padding, so a px width\n // that reaches that renders as \"full\" does.\n const room =\n ctx.columnWidth - base.styles.padding.left - base.styles.padding.right;\n\n const width =\n widthPercent === 100 || pxWidth === undefined || pxWidth >= room\n ? (\"full\" as const)\n : Math.round(pxWidth);\n\n const isGif = sourceTag === \"mj-gif\";\n\n return {\n block: createImageBlock({\n src,\n alt: attr(node, \"alt\") ?? \"\",\n width,\n align: parseAlignment(attr(node, \"align\"), \"center\"),\n ...(href ? { linkUrl: href } : {}),\n ...base,\n }),\n entry: {\n sourceTag,\n templaticalBlockType: \"image\",\n status: isGif ? \"approximated\" : \"converted\",\n ...(isGif\n ? {\n note: \"<mj-gif> imported as an image block; Templatical has no dedicated GIF block.\",\n }\n : {}),\n },\n };\n}\n\nfunction convertSpacer(node: TopolNode, ctx: MapContext): Converted {\n const height = attr(node, \"height\");\n return {\n block: createSpacerBlock({\n ...(height === undefined ? {} : { height: parsePxValue(height) }),\n ...baseStyles(node, ctx),\n }),\n entry: {\n sourceTag: \"mj-spacer\",\n templaticalBlockType: \"spacer\",\n status: \"converted\",\n },\n };\n}\n\nfunction convertDivider(node: TopolNode, ctx: MapContext): Converted {\n const color = parseColor(attr(node, \"border-color\"));\n const thickness = attr(node, \"border-width\");\n return {\n block: createDividerBlock({\n lineStyle: parseBorderStyle(attr(node, \"border-style\")),\n ...(color ? { color } : {}),\n ...(thickness === undefined\n ? {}\n : { thickness: parsePxValue(thickness) }),\n ...baseStyles(node, ctx),\n }),\n entry: {\n sourceTag: \"mj-divider\",\n templaticalBlockType: \"divider\",\n status: \"converted\",\n },\n };\n}\n\n/**\n * Convert one leaf node to a block.\n *\n * Returns `null` for a node that produces nothing *and* warrants no report\n * entry — an image with no `src`, a button with no label. `mj-social` is not\n * handled here; the converter routes it to `convertSocial`.\n */\nexport function convertLeaf(\n node: TopolNode,\n ctx: MapContext,\n): Converted | null {\n switch (node.tagName) {\n case \"mj-text\":\n return convertText(node, ctx);\n case \"mj-button\":\n return convertButton(node, ctx);\n case \"mj-image\":\n return convertImage(node, ctx, \"mj-image\");\n case \"mj-gif\":\n return convertImage(node, ctx, \"mj-gif\");\n case \"mj-spacer\":\n return convertSpacer(node, ctx);\n case \"mj-divider\":\n return convertDivider(node, ctx);\n default:\n return {\n block: createHtmlBlock({\n content: JSON.stringify(node),\n ...baseStyles(node, ctx),\n }),\n entry: {\n sourceTag: node.tagName,\n templaticalBlockType: \"html\",\n status: \"html-fallback\",\n note: `<${node.tagName}> has no Templatical block equivalent; the original node is preserved as JSON.`,\n },\n };\n }\n}\n","import { createSocialIconsBlock, generateId } from \"@templatical/types\";\nimport type {\n SocialIcon,\n SocialIconTone,\n SocialIconSize,\n SocialIconStyle,\n BuiltInSocialPlatform,\n} from \"@templatical/types\";\nimport { attr, parseAlignment, parsePxValue } from \"./attribute-parser\";\nimport { baseStyles, type Converted, type MapContext } from \"./block-mapper\";\nimport type { TopolNode } from \"./types\";\n\n/**\n * Exhaustive over `BuiltInSocialPlatform` on purpose: adding a member to that union\n * without adding it here is a compile error, so this cannot silently fall back\n * to \"website\" for a platform the block model gained.\n */\nconst KNOWN_PLATFORMS: Record<BuiltInSocialPlatform, true> = {\n facebook: true,\n twitter: true,\n instagram: true,\n linkedin: true,\n xing: true,\n youtube: true,\n tiktok: true,\n pinterest: true,\n email: true,\n whatsapp: true,\n telegram: true,\n discord: true,\n snapchat: true,\n reddit: true,\n github: true,\n dribbble: true,\n behance: true,\n website: true,\n};\n\nconst ALIASES: Record<string, BuiltInSocialPlatform> = {\n x: \"twitter\",\n \"x-twitter\": \"twitter\",\n};\n\nconst ICON_SIZES: Array<[number, SocialIconSize]> = [\n [24, \"small\"],\n [32, \"medium\"],\n [48, \"large\"],\n];\n\nconst KNOWN_STYLES = new Set<string>([\n \"solid\",\n \"outlined\",\n \"rounded\",\n \"square\",\n \"circle\",\n]);\n\n// Topol ships icon sets whose folder name is not a Templatical style name.\n// `outlinedbw` is the outlined set in black and white, so it imports as\n// outlined in the dark tone; mapping it to the `solid` fallback would import\n// an outlined icon set as filled. Measured: both `/social-icos/outlined/` and\n// `/social-icos/outlinedbw/` appear across the reference exports.\nconst STYLE_ALIASES: Record<\n string,\n { style: SocialIconStyle; tone: SocialIconTone }\n> = {\n outlinedbw: { style: \"outlined\", tone: \"dark\" },\n};\n\nfunction normalizePlatform(raw: string): BuiltInSocialPlatform | null {\n const cleaned = raw.trim().toLowerCase();\n if (!cleaned) return null;\n if (Object.hasOwn(ALIASES, cleaned)) return ALIASES[cleaned];\n return Object.hasOwn(KNOWN_PLATFORMS, cleaned)\n ? (cleaned as BuiltInSocialPlatform)\n : null;\n}\n\nfunction nearestSize(px: number): { size: SocialIconSize; exact: boolean } {\n let best = ICON_SIZES[1];\n let gap = Infinity;\n for (const candidate of ICON_SIZES) {\n const d = Math.abs(candidate[0] - px);\n if (d < gap) {\n gap = d;\n best = candidate;\n }\n }\n return { size: best[1], exact: gap === 0 };\n}\n\n/** The style (and tone) the segment of `https://…/social-icos/<style>/` names. */\nfunction styleFromBaseUrl(\n baseUrl: string | undefined,\n): { style: SocialIconStyle; tone?: SocialIconTone } | undefined {\n if (!baseUrl) return undefined;\n const segment = baseUrl.split(\"?\")[0].split(\"/\").filter(Boolean).at(-1) ?? \"\";\n if (KNOWN_STYLES.has(segment)) return { style: segment as SocialIconStyle };\n return Object.hasOwn(STYLE_ALIASES, segment)\n ? STYLE_ALIASES[segment]\n : undefined;\n}\n\n/**\n * Convert Topol's MJML v3 social block.\n *\n * `display` decides which icons render and in what order; a platform with\n * `*-href` set but absent from `display` was not shown in the email and is\n * not imported.\n */\nexport function convertSocial(\n node: TopolNode,\n _ctx: MapContext,\n): Converted | null {\n const display = attr(node, \"display\");\n if (!display) return null;\n\n const notes: string[] = [];\n const icons: SocialIcon[] = [];\n const seen = new Set<string>();\n const repeated = new Map<string, number>();\n\n for (const token of display.trim().split(/\\s+/)) {\n const rawName = token.split(\":\")[0];\n if (!rawName) continue;\n\n const url = attr(node, `${rawName}-href`);\n if (!url) continue;\n\n const platform = normalizePlatform(rawName);\n const key = JSON.stringify([platform ?? \"website\", url]);\n if (seen.has(key)) {\n const name = platform ?? \"website\";\n repeated.set(name, (repeated.get(name) ?? 0) + 1);\n continue;\n }\n seen.add(key);\n if (!platform) {\n notes.push(\n `Unrecognised social platform \"${rawName}\" mapped to \"website\".`,\n );\n }\n\n icons.push({ id: generateId(), platform: platform ?? \"website\", url });\n }\n for (const [platform, count] of repeated) {\n notes.push(\n `Dropped ${count} repeated \"${platform}\" ${count === 1 ? \"icon\" : \"icons\"}.`,\n );\n }\n\n if (icons.length === 0) return null;\n\n const fromBaseUrl = styleFromBaseUrl(attr(node, \"base-url\"));\n\n const declaredSize = attr(node, \"icon-size\");\n let iconSize: SocialIconSize | undefined;\n if (declaredSize !== undefined) {\n const px = parsePxValue(declaredSize);\n const resolved = nearestSize(px);\n iconSize = resolved.size;\n if (!resolved.exact) {\n notes.push(\n `Icon size ${declaredSize} is not one of 24/32/48px; resolved to \"${resolved.size}\".`,\n );\n }\n }\n\n return {\n block: createSocialIconsBlock({\n icons,\n align: parseAlignment(attr(node, \"align\"), \"center\"),\n ...(iconSize ? { iconSize } : {}),\n ...(fromBaseUrl ? { iconStyle: fromBaseUrl.style } : {}),\n ...(fromBaseUrl?.tone ? { iconTone: fromBaseUrl.tone } : {}),\n ...baseStyles(node, _ctx),\n }),\n entry: {\n sourceTag: \"mj-social\",\n templaticalBlockType: \"social\",\n status: notes.length > 0 ? \"approximated\" : \"converted\",\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n },\n };\n}\n","import {\n COLUMN_LAYOUT_PERCENTS,\n columnWidthsIssue,\n createSectionBlock,\n sectionColumnPercents,\n} from \"@templatical/types\";\nimport type { Block, ColumnLayout } from \"@templatical/types\";\nimport {\n attr,\n parseColor,\n parsePadding,\n parsePercent,\n readMjmlBackgroundImage,\n} from \"./attribute-parser\";\nimport { convertLeaf, type MapContext } from \"./block-mapper\";\nimport { convertSocial } from \"./social-mapper\";\nimport type { ImportReportEntry, TopolNode } from \"./types\";\n\n/** Preset match order. The first preset within the tolerance wins. */\nconst LAYOUT_MATCH_ORDER: readonly ColumnLayout[] = [\n \"1\",\n \"2\",\n \"1-2\",\n \"2-1\",\n \"1-3\",\n \"3-1\",\n \"3\",\n \"1-2-1\",\n \"4\",\n];\n\n/** Percentage points of drift tolerated per column before a match is inexact. */\nconst WIDTH_TOLERANCE = 2;\n\n/**\n * One hundredth, the step `sectionColumnPercents` rounds to, plus the float\n * error of subtracting two hundredths. Scaled shares this close to a preset\n * are that preset.\n */\nconst SCALED_TOLERANCE = 0.01 + 1e-9;\n\n/** Half a point. A float sum of shares that already are 100 still fills the row. */\nconst TOTAL_SLACK = 0.5;\n\nfunction totalsFullWidth(percents: readonly number[]): boolean {\n const total = percents.reduce((sum, share) => sum + share, 0);\n return Math.abs(total - 100) <= TOTAL_SLACK;\n}\n\nfunction evenLayout(count: number): ColumnLayout {\n if (count === 3) return \"3\";\n if (count === 4) return \"4\";\n return \"2\";\n}\n\n/** The first preset with one share per value, each within `tolerance`. */\nfunction presetWithin(\n percents: readonly number[],\n tolerance: number,\n): ColumnLayout | undefined {\n return LAYOUT_MATCH_ORDER.find((layout) => {\n const target = COLUMN_LAYOUT_PERCENTS[layout];\n return (\n target.length === percents.length &&\n target.every(\n (share, index) => Math.abs(share - percents[index]!) <= tolerance,\n )\n );\n });\n}\n\nconst COLUMN_COUNT: Record<ColumnLayout, number> = {\n \"1\": 1,\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"2-1\": 2,\n \"1-2\": 2,\n \"3-1\": 2,\n \"1-3\": 2,\n \"1-2-1\": 3,\n};\n\n/**\n * Each column's px width in `container`: the preset's shares, a third for\n * `\"3\"`, `\"1-2\"` and `\"2-1\"`, or the `columnWidths` percentages when the\n * section has them.\n */\nfunction columnPixels(\n layout: ColumnLayout,\n container: number,\n columnWidths: readonly number[] | undefined,\n): number[] {\n if (columnWidths) {\n return columnWidths.map((percent) => (container * percent) / 100);\n }\n switch (layout) {\n case \"2\":\n return [container / 2, container / 2];\n case \"3\":\n return [container / 3, container / 3, container / 3];\n case \"1-2\":\n return [container / 3, (container * 2) / 3];\n case \"2-1\":\n return [(container * 2) / 3, container / 3];\n case \"1-3\":\n return [container / 4, (container * 3) / 4];\n case \"3-1\":\n return [(container * 3) / 4, container / 4];\n case \"1-2-1\":\n return [container / 4, container / 2, container / 4];\n case \"4\":\n return [container / 4, container / 4, container / 4, container / 4];\n default:\n return [container];\n }\n}\n\n/**\n * Resolve `mj-column` widths, as percentages of the section's inner box, to\n * a layout. Topol renders through MJML, so MJML's rules apply.\n *\n * A width list within `WIDTH_TOLERANCE` of a preset keeps that preset,\n * exact only when those widths already total 100 within half a point. A\n * near preset that does not fill the row is approximated, because the\n * preset still changes the column sizes. An absent width is `mj-column`'s\n * default, the parent width divided by the column count, whatever its\n * siblings state, so a row with no widths is the even preset. One column\n * is `\"1\"`: exact at 100%, approximated otherwise. Two, three or four\n * columns that fit no preset are scaled to 100: scaled shares equal to a\n * preset keep that preset, any others keep the even preset of that count\n * plus `columnWidths`. The scaled row uses the same total check;\n * otherwise scaling changed the source layout. A width that cannot be\n * stored (not above 0) keeps the even preset, approximated. Five or more\n * columns fold onto `\"4\"`, approximated.\n */\nexport function matchColumnLayout(percents: Array<number | null>): {\n layout: ColumnLayout;\n exact: boolean;\n columnWidths?: number[];\n} {\n const count = percents.length;\n if (count === 0) return { layout: \"1\", exact: true };\n if (count > 4) return { layout: \"4\", exact: false };\n\n const resolved = percents.map((percent) => percent ?? 100 / count);\n const preset = presetWithin(resolved, WIDTH_TOLERANCE);\n if (preset) return { layout: preset, exact: totalsFullWidth(resolved) };\n if (count === 1) return { layout: \"1\", exact: false };\n\n const layout = evenLayout(count);\n if (columnWidthsIssue({ columns: layout, columnWidths: resolved }) !== null) {\n return { layout, exact: false };\n }\n const exact = totalsFullWidth(resolved);\n const scaled = sectionColumnPercents({\n columns: layout,\n columnWidths: resolved,\n });\n const scaledPreset = presetWithin(scaled, SCALED_TOLERANCE);\n if (scaledPreset) return { layout: scaledPreset, exact };\n return { layout, exact, columnWidths: scaled };\n}\n\nconst PX_WIDTH = /^(\\d+(?:\\.\\d+)?)\\s*px$/i;\n\n/**\n * A column's `width` as a percentage of `innerWidth`, or `null` when it\n * states none. A percentage is read as written. A px width is that many\n * pixels of the inner box, the email width less the section's side\n * padding, which is the box MJML sizes columns against.\n */\nfunction columnPercent(\n value: string | undefined,\n innerWidth: number,\n): number | null {\n const percent = parsePercent(value);\n if (percent !== null) return percent;\n const px = PX_WIDTH.exec((value ?? \"\").trim());\n if (!px || innerWidth <= 0) return null;\n return (Number(px[1]) / innerWidth) * 100;\n}\n\nfunction convertColumnChildren(\n column: TopolNode,\n ctx: MapContext,\n entries: ImportReportEntry[],\n): Block[] {\n const blocks: Block[] = [];\n for (const child of column.children ?? []) {\n const converted =\n child.tagName === \"mj-social\"\n ? convertSocial(child, ctx)\n : convertLeaf(child, ctx);\n if (child.uid)\n ctx.uidMap?.set(child.uid, {\n node: child,\n block: converted?.block ?? null,\n });\n if (!converted) continue;\n entries.push(converted.entry);\n if (converted.block) blocks.push(converted.block);\n }\n return blocks;\n}\n\n/**\n * Build a `SectionBlock` from an `mj-section`. Returns an array so the caller\n * can treat an empty section (no columns) as producing nothing.\n *\n * Reads `attributes` only. The node's top-level camelCase keys\n * (`backgroundColor`, `paddingTop`, …) are stale editor state that disagrees\n * with `attributes` in every measured case.\n */\nexport function buildSection(\n node: TopolNode,\n ctx: MapContext,\n entries: ImportReportEntry[],\n): Block[] {\n const columns = (node.children ?? []).filter(\n (c) => c.tagName === \"mj-column\",\n );\n if (columns.length === 0) return [];\n\n const padding = parsePadding(node);\n const innerWidth = ctx.style.settings.width - padding.left - padding.right;\n const rawWidths = columns.map((c) => attr(c, \"width\"));\n const percents = rawWidths.map((w) => columnPercent(w, innerWidth));\n const matched = matchColumnLayout(percents);\n const { layout, columnWidths } = matched;\n // With no inner box a px width has nothing to be a share of, so it is\n // dropped and the row's ratio is lost.\n const pxDropped =\n innerWidth <= 0 &&\n rawWidths.some((w) => w !== undefined && PX_WIDTH.test(w.trim()));\n const exact = matched.exact && !pxDropped;\n\n const slots = COLUMN_COUNT[layout];\n // MJML lays the columns out in the inner box, so each column's room is\n // its share of that box, not of the email width.\n const pixels = columnPixels(layout, Math.max(0, innerWidth), columnWidths);\n const children: Block[][] = Array.from({ length: slots }, () => []);\n\n const background = readMjmlBackgroundImage(\n (name) => attr(node, name),\n \"Section\",\n ctx.style.settings.width,\n );\n const notes = [\n ...(exact\n ? []\n : [\n `Column widths ${rawWidths.map((w) => w ?? \"auto\").join(\", \")} have no exact Templatical layout; resolved to \"${layout}\".${columns.length > 4 ? \" Templatical supports up to four columns.\" : \"\"}`,\n ]),\n ...(background?.notes ?? []),\n ];\n entries.push({\n sourceTag: \"mj-section\",\n templaticalBlockType: \"section\",\n status: notes.length > 0 ? \"approximated\" : \"converted\",\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n });\n\n columns.forEach((column, index) => {\n const slot = Math.min(index, slots - 1);\n const columnCtx: MapContext = {\n ...ctx,\n columnWidth: Math.round(pixels[slot] ?? ctx.style.settings.width),\n };\n children[slot].push(...convertColumnChildren(column, columnCtx, entries));\n });\n\n const backgroundColor = parseColor(attr(node, \"background-color\"));\n // `full-width=\"full-width\"` makes this section's own background the\n // viewport band. The section stays transparent over it.\n const fullWidth =\n attr(node, \"full-width\") === \"full-width\" &&\n Boolean(backgroundColor || background);\n\n return [\n createSectionBlock({\n columns: layout,\n ...(columnWidths ? { columnWidths } : {}),\n children,\n styles: {\n padding,\n ...(!fullWidth && backgroundColor ? { backgroundColor } : {}),\n },\n ...(!fullWidth && background\n ? { backgroundImage: background.image }\n : {}),\n ...(fullWidth\n ? {\n wrapper: {\n ...(backgroundColor ? { backgroundColor } : {}),\n ...(background ? { backgroundImage: background.image } : {}),\n fullWidth: true,\n },\n }\n : {}),\n }),\n ];\n}\n","import {\n defaultLocaleOption,\n localeTag,\n registerLocales,\n set,\n text,\n warn,\n} from \"./localization\";\nimport { convertLeaf } from \"./block-mapper\";\nimport { createDefaultTemplateContent } from \"@templatical/types\";\nimport type { Block, TemplateContent } from \"@templatical/types\";\nimport { readGlobalStyle } from \"./global-style\";\nimport { buildSection } from \"./section-builder\";\nimport type { MapContext } from \"./block-mapper\";\nimport type {\n ImportReport,\n ImportReportEntry,\n ImportResult,\n TopolDesign,\n} from \"./types\";\n\nexport interface ConvertTopolOptions {\n /** Used when the source declares no default language. */\n defaultLocale?: string;\n}\n\nconst ROOT_TAG = \"mj-global-style\";\n// Designs saved by Topol's editor hold their sections under either tag.\nconst CONTAINER_TAGS = new Set([\"mj-container\", \"mj-body\"]);\n\nconst INVALID_DESIGN_MESSAGE =\n 'Invalid Topol template: expected the design JSON object — Topol hands you this directly from its editor\\'s onSave callback, or under \"definition\" (template API) or \"json\" (predefined-templates API) in its API response.';\n\nconst EMPTY_DESIGN_WARNING =\n \"No convertible content was found in the Topol design. Check that its mj-container (or mj-body) holds at least one mj-section.\";\n\n/**\n * Convert a Topol.io design into a Templatical template.\n *\n * The input is the design object itself — the node whose `tagName` is\n * `mj-global-style`, not a whole API response. Topol's editor hands it to\n * you directly as the first argument to `onSave`; its REST APIs wrap it\n * instead, under `definition` on the template-retrieval endpoint or `json`\n * (alongside `html`) on the predefined-templates endpoint. That is\n * documented rather than sniffed: guessing which field holds the design\n * risks importing an envelope's `html`, which belongs to a different\n * package entirely.\n *\n * @example\n * ```ts\n * const { content, report } = convertTopolTemplate(design);\n * const editor = init({ container: '#editor', content });\n * console.log(report.summary);\n * ```\n */\nexport function convertTopolTemplate(\n design: TopolDesign | string,\n options: ConvertTopolOptions = {},\n): ImportResult {\n const root: unknown = typeof design === \"string\" ? safeParse(design) : design;\n\n if (typeof root !== \"object\" || root === null || Array.isArray(root)) {\n throw new Error(INVALID_DESIGN_MESSAGE);\n }\n\n const topolDesign = root as TopolDesign;\n\n if (topolDesign.tagName !== ROOT_TAG) {\n // Topol's REST APIs wrap the design rather than returning it bare: the\n // template-retrieval endpoint uses \"definition\", the predefined/premade\n // templates endpoint uses \"json\" (alongside \"html\"). A response object\n // passed here by mistake still carries one of those keys, so that\n // mistake is named directly instead of falling through to the generic\n // wrong-tagName message below.\n if (\"json\" in topolDesign || \"definition\" in topolDesign) {\n throw new Error(INVALID_DESIGN_MESSAGE);\n }\n throw new Error(\n `Invalid Topol template: expected a root node with tagName \"${ROOT_TAG}\".`,\n );\n }\n\n const container = (topolDesign.children ?? []).find((child) =>\n CONTAINER_TAGS.has(child.tagName),\n );\n\n const entries: ImportReportEntry[] = [];\n const warnings: string[] = [];\n const blocks: Block[] = [];\n\n const style = readGlobalStyle(topolDesign, container, warnings);\n const languages = topolDesign.langs ?? [];\n const primary =\n languages.find((language) => language.primary) ?? languages[0];\n // Distinct from the locale below. The nodes hold this language's content\n // only when its key is a usable tag. An unusable key falls through to\n // `defaultLocale`, which may name a different language in `langs`.\n const sourcePrimaryLocale = primary ? localeTag(primary.key, warnings) : null;\n style.settings.locale =\n sourcePrimaryLocale ??\n defaultLocaleOption(options.defaultLocale, warnings) ??\n \"en\";\n const uidMap: NonNullable<MapContext[\"uidMap\"]> = new Map();\n\n const ctx: MapContext = {\n uidMap,\n style,\n columnWidth: style.settings.width,\n };\n\n for (const child of container?.children ?? []) {\n if (child.tagName !== \"mj-section\") continue;\n blocks.push(...buildSection(child, ctx, entries));\n }\n\n if (blocks.length === 0) {\n warnings.push(EMPTY_DESIGN_WARNING);\n }\n\n const content: TemplateContent = {\n ...createDefaultTemplateContent(),\n blocks,\n settings: style.settings,\n };\n\n const preview = primary?.translations?.[\"mj-preview\"]?.content;\n if (typeof preview === \"string\") content.settings.preheaderText = preview;\n // The fallback language's translations become the base, and it keeps no\n // layer of its own. Apply it before the others so their source hashes\n // match the base they sit on, whatever order `langs` stored them in.\n let languageOrder = languages;\n if (sourcePrimaryLocale === null) {\n const fallbackLanguages: typeof languages = [];\n const otherLanguages: typeof languages = [];\n for (const language of languages) {\n if (localeTag(language.key, warnings) === content.settings.locale)\n fallbackLanguages.push(language);\n else otherLanguages.push(language);\n }\n languageOrder = [...fallbackLanguages, ...otherLanguages];\n }\n for (const language of languageOrder) {\n const locale = localeTag(language.key, warnings);\n if (!locale) continue;\n for (const [uid, translation] of Object.entries(\n language.translations ?? {},\n )) {\n if (uid === \"mj-subject\") {\n warn(\n warnings,\n `Dropped language \"${locale}\" mj-subject: the host owns this field.`,\n );\n continue;\n }\n // A usable source primary is already the base. A fallback locale is\n // not, so its translation is written onto the base rather than dropped\n // with the default-locale layer.\n if (locale === content.settings.locale && sourcePrimaryLocale !== null)\n continue;\n const ontoBase = locale === content.settings.locale;\n if (uid === \"mj-preview\") {\n if (typeof translation.content === \"string\") {\n if (ontoBase) content.settings.preheaderText = translation.content;\n else\n text(\n content.settings,\n locale,\n \"preheaderText\",\n content.settings.preheaderText,\n translation.content,\n );\n }\n continue;\n }\n const target = uidMap.get(uid);\n const block = target?.block;\n if (!block || block.type === \"html\") {\n warn(\n warnings,\n `Dropped language \"${locale}\" translation for uid \"${uid}\": target converted to ${block ? \"HTML fallback\" : \"null\"}.`,\n );\n continue;\n }\n if (typeof translation.content === \"string\") {\n const converted = convertLeaf(\n { ...target.node, content: translation.content },\n ctx,\n )?.block;\n if (\n (block.type === \"title\" || block.type === \"paragraph\") &&\n converted &&\n (converted.type === \"title\" || converted.type === \"paragraph\")\n ) {\n if (ontoBase) block.content = converted.content;\n else text(block, locale, \"content\", block.content, converted.content);\n } else if (block.type === \"button\" && converted?.type === \"button\") {\n if (ontoBase) block.text = converted.text;\n else text(block, locale, \"text\", block.text, converted.text);\n } else\n warn(\n warnings,\n `Dropped language \"${locale}\" content for uid \"${uid}\": no language mapping for this format.`,\n );\n }\n for (const [key, value] of Object.entries(translation.attributes ?? {})) {\n if (typeof value !== \"string\") continue;\n if (key === \"alt\" && block.type === \"image\") {\n if (ontoBase) block.alt = value;\n else text(block, locale, \"alt\", block.alt, value);\n } else if (key === \"href\" && block.type === \"button\") {\n if (ontoBase) block.url = value;\n else set(block, locale, \"url\", value);\n } else if (key === \"href\" && block.type === \"image\") {\n if (ontoBase) block.linkUrl = value;\n else set(block, locale, \"linkUrl\", value);\n } else if (key === \"src\" && block.type === \"image\") {\n if (ontoBase) block.src = value;\n else set(block, locale, \"src\", value);\n } else\n warn(\n warnings,\n `Dropped language \"${locale}\" attribute \"${key}\" for uid \"${uid}\": no language mapping for this format.`,\n );\n }\n }\n }\n registerLocales(content);\n const versions = languages\n .map((language) => localeTag(language.key, warnings))\n .filter(\n (locale): locale is string =>\n locale !== null && locale !== content.settings.locale,\n );\n if (versions.length) content.settings.locales = [...new Set(versions)];\n\n const summary = {\n total: entries.length,\n converted: entries.filter((e) => e.status === \"converted\").length,\n approximated: entries.filter((e) => e.status === \"approximated\").length,\n htmlFallback: entries.filter((e) => e.status === \"html-fallback\").length,\n skipped: entries.filter((e) => e.status === \"skipped\").length,\n };\n\n const report: ImportReport = { entries, warnings, summary };\n\n return { content, report };\n}\n\nfunction safeParse(source: string): unknown {\n try {\n return JSON.parse(source);\n } catch {\n throw new Error(INVALID_DESIGN_MESSAGE);\n }\n}\n"],"mappings":";;AAWA,MAAM,+BAAe,IAAI,QAGvB;AAEF,SAAgB,KAAK,UAAoB,SAAuB;CAC9D,IAAI,OAAO,aAAa,IAAI,QAAQ;CACpC,IAAI,CAAC,QAAQ,KAAK,OAAO,SAAS,QAAQ;EACxC,OAAO;GAAE,qBAAK,IAAI,IAAI;GAAG,MAAM;EAAE;EACjC,aAAa,IAAI,UAAU,IAAI;CACjC;CACA,OAAO,KAAK,OAAO,SAAS,QAAQ,KAAK,QACvC,KAAK,IAAI,IAAI,SAAS,KAAK,KAAK;CAElC,IAAI,KAAK,IAAI,IAAI,OAAO,GAAG;CAC3B,SAAS,KAAK,OAAO;CACrB,KAAK,IAAI,IAAI,OAAO;CACpB,KAAK;AACP;AAEA,SAAgB,UAAU,OAAe,UAAmC;CAC1E,MAAM,SAAS,MAAM,WAAW,KAAK,GAAG;CACxC,IAAI,YAAY,MAAM,GAAG,OAAO;CAChC,KAAK,UAAU,qBAAqB,MAAM,6BAA6B;CACvE,OAAO;AACT;;AAGA,SAAgB,oBACd,OACA,UACe;CACf,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAS,MAAM,WAAW,KAAK,GAAG;CACxC,IAAI,YAAY,MAAM,GAAG,OAAO;CAChC,KACE,UACA,0BAA0B,MAAM,wCAClC;CACA,OAAO;AACT;AAEA,SAAgB,KACd,QACA,QACA,MACA,MACA,OACM;CACN,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C;CAYrE,OAAO;EAAE;EAAS,QAAA;GAFa;GAAS;GAAU,SAAA;IAPhD,OAAO,QAAQ;IACf,WAAW,QAAQ,QAAQ,MAAM,EAAE,WAAW,WAAW,CAAC,CAAC;IAC3D,cAAc,QAAQ,QAAQ,MAAM,EAAE,WAAW,cAAc,CAAC,CAAC;IACjE,cAAc,QAAQ,QAAQ,MAAM,EAAE,WAAW,eAAe,CAAC,CAAC;IAClE,SAAS,QAAQ,QAAQ,MAAM,EAAE,WAAW,SAAS,CAAC,CAAC;GAGD;EAEjC;CAAE;AAC3B;AAEA,SAAS,UAAU,QAAyB;CAC1C,IAAI;EACF,OAAO,KAAK,MAAM,MAAM;CAC1B,QAAQ;EACN,MAAM,IAAI,MAAM,sBAAsB;CACxC;AACF"}
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@templatical/import-topol",
3
3
  "description": "Convert Topol.io email templates to Templatical format",
4
- "version": "0.64.0",
4
+ "version": "0.64.1",
5
5
  "bugs": "https://github.com/templatical/sdk/issues",
6
6
  "dependencies": {
7
- "@templatical/types": "0.64.0"
7
+ "@templatical/types": "0.64.1"
8
8
  },
9
9
  "devDependencies": {
10
10
  "@types/node": "^26.6.11",