@maily-to/render 0.2.3 → 2.0.0-beta.10

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.mjs CHANGED
@@ -1,2 +1,1586 @@
1
- import{Fragment as e}from"react";import{Body as t,Button as n,Column as r,Container as i,Font as a,Head as o,Heading as s,Hr as c,Html as l,Img as u,Link as d,Preview as f,Row as p,Section as m,Text as h}from"@react-email/components";import{renderAsync as g}from"@react-email/render";import{Fragment as _,jsx as v,jsxs as y}from"react/jsx-runtime";import{parse as b}from"node-html-parser";import x from"juice";const S=e=>Object.prototype.toString.call(e),C=e=>S(e)===`[object Object]`;function w(e){return Object.keys(e)}function T(e,...t){if(!t.length)return e;let n=t.shift();return n===void 0?e:(E(e)&&E(n)&&w(n).forEach(t=>{t===`__proto__`||t===`constructor`||t===`prototype`||(E(n[t])?(e[t]||(e[t]={}),E(e[t])?T(e[t],n[t]):e[t]=n[t]):e[t]=n[t])}),T(e,...t))}function E(e){return C(e)&&!Array.isArray(e)}const ee=Symbol(`p-void`);function D(){return Math.random().toString(36).substr(2,6)}function O(e){return e.filter((e,t,n)=>{let r=A(e);return t===n.findIndex(e=>A(e)===r)}).map(k).filter(Boolean)}function k(e){if(`tagName`in e){let{tagName:t,...n}=e,r=t;return v(r,{...n},JSON.stringify(n))}return`title`in e?v(`title`,{children:e.title}):`charSet`in e?v(`meta`,{charSet:e.charSet}):v(`meta`,{...e},JSON.stringify(e))}function A(e){let t=Object.keys(e).sort().reduce((t,n)=>{let r=n;return t[r]=e[r],t},{});return JSON.stringify(t)}const j={fallbackFontFamily:`sans-serif`,fontFamily:`Inter`,webFont:{url:`https://rsms.me/inter/font-files/Inter-Regular.woff2?v=3.19`,format:`woff2`}},M=`#111827`,N={colors:{heading:`#111827`,paragraph:`#374151`,horizontal:`#EAEAEA`,footer:`#64748B`,blockquoteBorder:`#D1D5DB`,codeBackground:`#EFEFEF`,codeText:`#111827`,linkCardTitle:`#111827`,linkCardDescription:`#6B7280`,linkCardBadgeText:`#111827`,linkCardBadgeBackground:`#FEF08A`,linkCardSubTitle:`#6B7280`},fontSize:{paragraph:{size:`15px`,lineHeight:`26.25px`},footer:{size:`14px`,lineHeight:`24px`}},container:{backgroundColor:`#ffffff`,maxWidth:`600px`,minWidth:`300px`,paddingTop:`0.5rem`,paddingRight:`0.5rem`,paddingBottom:`0.5rem`,paddingLeft:`0.5rem`,borderRadius:`0px`,borderWidth:`0px`,borderColor:`transparent`},body:{backgroundColor:`#ffffff`,paddingTop:`0px`,paddingRight:`0px`,paddingBottom:`0px`,paddingLeft:`0px`},button:{backgroundColor:`#000000`,color:`#ffffff`,paddingTop:`10px`,paddingRight:`32px`,paddingBottom:`10px`,paddingLeft:`32px`},link:{color:M},font:j};var te=class{constructor(e){this.maily=e}render(e){return typeof e==`string`?e:this.renderNode(e)}renderNode(e){let t=e.type||``;switch(t){case`doc`:return this.doc(e);case`paragraph`:return this.paragraph(e);case`text`:return this.text(e);case`variable`:return this.variable(e);default:return``}}doc(e){let t=e.content||[];return t.length===0?``:t.map(e=>this.renderNode(e)).join(``)}paragraph(e){let t=e.content||[];return t.length===0?``:t.map(e=>this.renderNode(e)).join(``)}text(e){return e.text||``}variable(e){let{id:t,fallback:n}=e.attrs||{};return this.maily.getVariableValue(t,n)}};const P={WebkitFontSmoothing:`antialiased`,MozOsxFontSmoothing:`grayscale`},ne={h1:{fontSize:`36px`,lineHeight:`40px`,fontWeight:800},h2:{fontSize:`30px`,lineHeight:`36px`,fontWeight:700},h3:{fontSize:`24px`,lineHeight:`38px`,fontWeight:600}},F={sm:`40px`,md:`48px`,lg:`64px`},re=`SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,I=`#ffffff`,L=`left`,R=1,z=`#000000`,B=0,V=0,H=0,U=0,W=5,G=5,K=5,q=5,ie=`100%`,J=8,ae=`transparent`,oe=0,se=0,ce=`transparent`,le=0,ue=0,de=0,fe=0,Y=20,X=20,Z=/https?:\/\//,Q=[{name:`viewport`,content:`width=device-width`},{httpEquiv:`X-UA-Compatible`,content:`IE=edge`},{name:`x-apple-disable-message-reformatting`},{name:`format-detection`,content:`telephone=no,address=no,email=no,date=no,url=no`},{name:`color-scheme`,content:`light`},{name:`supported-color-schemes`,content:`light`}],$={lang:`en`,dir:`ltr`},pe={pretty:!1,plainText:!1};var me=class{preheader=new te(this);content;config={theme:N};variableFormatter=({variable:e,fallback:t})=>t?`{{${e},fallback=${t}}}`:`{{${e}}}`;shouldReplaceVariableValues=!1;variableValues=new Map;linkValues=new Map;openTrackingPixel;payloadValues=new Map;marksOrder=[`underline`,`bold`,`italic`,`textStyle`,`link`];meta=Q;htmlProps=$;constructor(e={type:`doc`,content:[]}){this.content=e}setPreviewText(e){this.config.preview=e}setTheme(e){this.config.theme=T(this.config.theme||N,e)}setVariableFormatter(e){this.variableFormatter=e}setVariableValue(e,t){this.shouldReplaceVariableValues||(this.shouldReplaceVariableValues=!0),this.variableValues.set(e,t)}setVariableValues(e){this.shouldReplaceVariableValues||(this.shouldReplaceVariableValues=!0),Object.entries(e).forEach(([e,t])=>{this.setVariableValue(e,t)})}setLinkValue(e,t){this.linkValues.set(e,t)}setLinkValues(e){Object.entries(e).forEach(([e,t])=>{this.setLinkValue(e,t)})}setPayloadValue(e,t){this.shouldReplaceVariableValues||(this.shouldReplaceVariableValues=!0),this.payloadValues.set(e,t)}setPayloadValues(e){Object.entries(e).forEach(([e,t])=>{this.setPayloadValue(e,t)})}setOpenTrackingPixel(e){this.openTrackingPixel=e}setShouldReplaceVariableValues(e){this.shouldReplaceVariableValues=e}setMetaTags(e){this.meta.push(...e)}setHtmlProps(e){this.htmlProps={...this.htmlProps,...e}}getAllLinks(){let e=this.content.content||[],t=new Set,n=e=>e&&this.isValidUrl(e)&&!e.startsWith(`#`)&&!e.startsWith(`mailto:`)&&!e.startsWith(`tel:`)&&typeof e==`string`,r=e=>{if(e.type===`button`){let r=e.attrs?.url;n(r)&&r&&t.add(r)}else e.content&&e.content.forEach(e=>{e.marks&&e.marks.forEach(e=>{let r=e.attrs?.href;e.type===`link`&&n(r)&&t.add(r)}),e.content&&r(e)})};return e.forEach(e=>{r(e)}),t}isValidUrl(e){try{let t=new URL(e);return!0}catch(e){return!1}}async render(e=pe){let t=this.markup();return g(t,e)}children(){let t=this.content.content||[],n=t.map((n,r)=>{let i={prev:t[r-1],next:t[r+1],parent:n},a=this.renderNode(n,i);return a?v(e,{children:a},D()):null});return n}markup(){let e=this.children(),{preview:n}=this.config,r=O(this.meta),s=this.htmlProps,c=this.config.theme?.container,d={...this.config.theme?.font||j,fontStyle:`normal`,fontWeight:400},p={margin:`0px`,...this.config.theme?.body},m=n?this.preheader.render(n):null,h=y(l,{...s,children:[y(o,{children:[v(a,{...d}),v(`style`,{dangerouslySetInnerHTML:{__html:`blockquote,h1,h2,h3,img,li,ol,p,ul{margin-top:0;margin-bottom:0}@media only screen and (max-width:425px){.tab-row-full{width:100%!important}.tab-col-full{display:block!important;width:100%!important}.tab-pad{padding:0!important}}`}}),r]}),y(t,{style:p,children:[m?v(f,{children:m}):null,v(i,{style:{width:`100%`,marginLeft:`auto`,marginRight:`auto`,borderStyle:`solid`,...c},children:e}),this.openTrackingPixel?v(u,{alt:``,src:this.openTrackingPixel,style:{display:`none`,width:`1px`,height:`1px`}}):null]})]});return h}getMarginOverrideConditions(e,t){let{parent:n,prev:r,next:i}=t||{},a=i?.type===`spacer`,o=r?.type===`spacer`,s=n?.type===`listItem`,c=n?.type===`section`&&!i,l=n?.type===`section`&&!r,u=n?.type===`column`&&!i,d=n?.type===`column`&&!r,f=n?.type===`repeat`&&!r,p=n?.type===`repeat`&&!i,m=n?.type===`show`&&!r,h=n?.type===`show`&&!i;return{isNextSpacer:a,isPrevSpacer:o,isLastSectionElement:c,isFirstSectionElement:l,isParentListItem:s,isLastColumnElement:u,isFirstColumnElement:d,isFirstRepeatElement:f,isLastRepeatElement:p,isFirstShowElement:m,isLastShowElement:h,shouldRemoveTopMargin:o||l||d||f||m,shouldRemoveBottomMargin:a||c||u||p||h}}getMappedContent(t,n){let r=t.content||[];return r.map((t,i)=>{let a=this.renderNode(t,{...n,next:r[i+1],prev:r[i-1]});return a?v(e,{children:a},D()):null}).filter(e=>e!==null)}renderNode(e,t={}){let n=e.type||``;if(n in this)return this[n]?.(e,t);throw Error(`Node type "${n}" is not supported.`)}renderMark(e,t){let n=e?.text||v(_,{children:`\xA0`}),r=e?.marks||[];return r.sort((e,t)=>this.marksOrder.indexOf(e.type)-this.marksOrder.indexOf(t.type)),r.reduce((e,t)=>{let n=t.type;if(n in this)return this[n]?.(t,e);throw Error(`Mark type "${n}" is not supported.`)},v(_,{children:n}))}paragraph(e,t){let{attrs:n}=e,r=n?.textAlign||`left`,i=n?.textDirection||`ltr`,{isParentListItem:a,shouldRemoveBottomMargin:o}=this.getMarginOverrideConditions(e,t),s=this.shouldShow(e,t);if(!s)return v(_,{});let c=a||o?0:20;return v(h,{style:{...r===`left`?{}:{textAlign:r},...i===`ltr`?{}:{direction:i},...P,fontSize:this.config.theme?.fontSize?.paragraph?.size,lineHeight:this.config.theme?.fontSize?.paragraph?.lineHeight,color:this.config.theme?.colors?.paragraph,margin:`0 0 ${c}px 0`},children:e.content?this.getMappedContent(e,{...t,parent:e}):v(_,{children:`\xA0`})})}text(t,n){if(t.marks)return this.renderMark(t,n);let r=t.text,i=r?.match(/\s/g);return i&&i.length===r?.length?v(_,{children:i.map((t,n)=>v(e,{children:`\xA0`},n))}):r?v(_,{children:r}):v(_,{children:`\xA0`})}bold(e,t){return v(`strong`,{children:t})}italic(e,t){return v(`em`,{children:t})}underline(e,t){return v(`u`,{children:t})}strike(e,t){return v(`s`,{style:{textDecoration:`line-through`},children:t})}textStyle(e,t){let{attrs:n}=e,{color:r=this.config.theme?.colors?.paragraph}=n||{};return v(`span`,{style:{color:r},children:t})}link(e,t,n){let{attrs:r}=e,i=this.config.theme?.link,a=r?.href||`#`,o=r?.target||`_blank`,s=r?.rel||`noopener noreferrer nofollow`,c=r?.isUrlVariable??!1;if(c){let e=this.removeLinkProtocol(a);a=this.variableUrlValue(e,n)}else a=this.linkValues.get(a)||a;return v(d,{href:a,rel:s,style:{fontWeight:500,textDecoration:`none`,color:i?.color||M},target:o,children:t})}removeLinkProtocol(e){return e.replace(Z,``)}variableUrlValue(e,t){let{payloadValue:n}=t||{},r=this.removeLinkProtocol(e);return this.shouldReplaceVariableValues?(typeof n==`object`?n[r]:n)??this.variableValues.get(r)??e:this.variableFormatter({variable:r})}heading(e,t){let{attrs:n}=e,r=`h${Number(n?.level)||1}`,i=n?.textDirection||`ltr`,a=i===`rtl`,o=a?`right`:`left`,c=n?.textAlign||o,{shouldRemoveBottomMargin:l}=this.getMarginOverrideConditions(e,t),{fontSize:u,lineHeight:d,fontWeight:f}=ne[r],p=this.shouldShow(e,t);return p?v(s,{as:r,style:{...c===`left`?{}:{textAlign:c},...a?{direction:i}:{},color:this.config.theme?.colors?.heading,fontSize:u,lineHeight:d,fontWeight:f},mb:l?0:12,mt:0,mx:0,children:this.getMappedContent(e,{...t,parent:e})}):v(_,{})}variable(e,t){let{payloadValue:n}=t||{},{id:r,fallback:i}=e.attrs||{},a=this.shouldShow(e,t);if(!a||!r)return v(_,{});let o=this.getVariableValue(r,i,t);return e?.marks?this.renderMark({text:o,marks:e.marks},t):v(_,{children:o})}getVariableValue(e,t,n){let{payloadValue:r}=n||{},i=this.variableFormatter({variable:e,fallback:t});return this.shouldReplaceVariableValues&&(i=(typeof r==`object`?r[e]:r)??this.variableValues.get(e)??t??i),i}horizontalRule(e,t){return v(c,{style:{marginTop:`32px`,marginBottom:`32px`}})}orderedList(e,t){let{shouldRemoveBottomMargin:n}=this.getMarginOverrideConditions(e,t);return v(i,{style:{marginTop:`0px`,marginBottom:n?`0`:`20px`},children:v(`ol`,{style:{paddingLeft:`26px`,listStyleType:`decimal`},children:this.getMappedContent(e,{...t,parent:e})})})}bulletList(e,t){let{parent:n,next:r}=t||{},{shouldRemoveBottomMargin:a}=this.getMarginOverrideConditions(e,{parent:n,next:r});return v(i,{style:{maxWidth:`100%`,marginTop:`0px`,marginBottom:a?`0`:`20px`},children:v(`ul`,{style:{paddingLeft:`26px`,listStyleType:`disc`},children:this.getMappedContent(e,{...t,parent:e})})})}listItem(e,t){return v(`li`,{style:{marginBottom:`8px`,marginTop:`8px`,paddingLeft:`6px`,...P},children:this.getMappedContent(e,{...t,parent:e})})}button(e,t){let{attrs:r}=e,a=this.config.theme?.button,{text:o,isTextVariable:s,url:c,isUrlVariable:l,variant:u,buttonColor:d,textColor:f,borderRadius:p,alignment:m=`left`,paddingTop:h,paddingRight:g,paddingBottom:y,paddingLeft:b}=r||{},x=d||a?.backgroundColor,S=f||a?.color,C=parseInt(String(h||a?.paddingTop))||0,w=parseInt(String(g||a?.paddingRight))||0,T=parseInt(String(y||a?.paddingBottom))||0,E=parseInt(String(b||a?.paddingLeft))||0,ee=this.shouldShow(e,t);if(!ee)return v(_,{});let D=`0px`;p===`round`?D=`9999px`:p===`smooth`&&(D=`6px`);let{shouldRemoveBottomMargin:O}=this.getMarginOverrideConditions(e,t),k=l?this.variableUrlValue(c,t):this.linkValues.get(c)||c,A=s?this.variableUrlValue(o,t):o;return C+=2,T+=2,v(i,{style:{textAlign:m,maxWidth:`100%`,marginBottom:O?`0px`:`20px`},children:v(n,{href:k,style:{color:String(S),backgroundColor:u===`filled`?String(x):`transparent`,borderColor:String(x),borderWidth:`2px`,borderStyle:`solid`,textDecoration:`none`,fontSize:`14px`,fontWeight:500,borderRadius:D,padding:`${C}px ${w}px ${T}px ${E}px`},children:A})})}spacer(e,t){let{attrs:n}=e,{height:r}=n||{},a=this.shouldShow(e,t);return a?v(i,{style:{height:`${r}px`}}):v(_,{})}hardBreak(e,t){return v(`br`,{})}logo(e,t){let{attrs:n}=e,{src:i,isSrcVariable:a,alt:o,title:s,size:c,alignment:l=`left`}=n||{},d=this.shouldShow(e,t);if(!d)return v(_,{});i=a?this.variableUrlValue(i,t):i;let{shouldRemoveBottomMargin:f}=this.getMarginOverrideConditions(e,t);return v(p,{style:{marginTop:`0px`,marginBottom:f?`0px`:`32px`},children:v(r,{align:l,children:v(u,{alt:o||s||`Logo`,src:i,style:{width:F[c]||c,height:F[c]||c},title:s||o||`Logo`})})})}image(e,t){let{attrs:n}=e,{src:i,isSrcVariable:a,alt:o,title:s,width:c=`auto`,height:l=`auto`,alignment:d=`center`,externalLink:f=``,isExternalLinkVariable:m,borderRadius:h=0}=n||{},g=this.shouldShow(e,t);if(!g)return v(_,{});let{shouldRemoveBottomMargin:y}=this.getMarginOverrideConditions(e,t);i=a?this.variableUrlValue(i,t):i,f=m?this.variableUrlValue(f,t):f;let b=c===`auto`?`auto`:Number(c),x=b===`auto`?`auto`:`${b}px`,S=l===`auto`?`auto`:Number(l),C=S===`auto`?`auto`:`${S}px`,w=v(u,{alt:o||s||`Image`,src:i,style:{width:x,height:C,maxWidth:`100%`,outline:`none`,border:`none`,textDecoration:`none`,display:`block`,borderRadius:h},title:s||o||`Image`});return v(p,{style:{marginTop:`0px`,marginBottom:y?`0px`:`32px`},children:v(r,{align:d,children:f?v(`a`,{href:f,rel:`noopener noreferrer`,style:{display:`block`,maxWidth:`100%`,textDecoration:`none`},target:`_blank`,children:w}):w})})}footer(e,t){let{attrs:n}=e,{textAlign:r=`left`,textDirection:i=`ltr`}=n||{},{shouldRemoveBottomMargin:a}=this.getMarginOverrideConditions(e,t);return v(h,{style:{fontSize:this.config.theme?.fontSize?.footer?.size,lineHeight:this.config.theme?.fontSize?.footer?.lineHeight,color:this.config.theme?.colors?.footer,marginTop:`0px`,marginBottom:a?`0px`:`20px`,textAlign:r,...i===`ltr`?{}:{direction:i},...P},children:this.getMappedContent(e,{...t,parent:e})})}blockquote(e,t){let{isPrevSpacer:n,shouldRemoveBottomMargin:r}=this.getMarginOverrideConditions(e,t);return v(`blockquote`,{style:{borderLeftWidth:`4px`,borderLeftStyle:`solid`,borderLeftColor:this.config.theme?.colors?.blockquoteBorder,paddingLeft:`16px`,marginLeft:`0px`,marginRight:`0px`,marginTop:n?`0px`:`20px`,marginBottom:r?`0px`:`20px`},children:this.getMappedContent(e,{...t,parent:e})})}code(e,t){return v(`code`,{style:{backgroundColor:this.config.theme?.colors?.codeBackground,color:this.config.theme?.colors?.codeText,padding:`2px 4px`,borderRadius:`6px`,fontFamily:re,fontWeight:400,letterSpacing:0},children:t})}linkCard(e,t){let{attrs:n}=e,{shouldRemoveBottomMargin:i}=this.getMarginOverrideConditions(e,t),{title:a,description:o,link:s,linkTitle:c,image:l,badgeText:d,subTitle:f}=n||{},m=this.linkValues.get(s)||this.variableValues.get(s)||s||`#`;return y(`a`,{href:m,rel:`noopener noreferrer`,style:{border:`1px solid #eaeaea`,borderRadius:`10px`,textDecoration:`none`,color:`inherit`,display:`block`,marginBottom:i?`0px`:`20px`},target:`_blank`,children:[l?v(p,{style:{marginBottom:`6px`},children:v(r,{style:{width:`100%`,height:`100%`},children:v(u,{alt:a||`Link Card`,src:l,style:{borderRadius:`10px 10px 0 0`,width:`100%`,height:`100%`,objectFit:`cover`},title:a||`Link Card`})})}):null,v(p,{style:{padding:`15px`,marginTop:0,marginBottom:0},children:y(r,{style:{verticalAlign:`top`},children:[y(p,{align:void 0,style:{marginBottom:`8px`,marginTop:`0px`},width:`auto`,children:[v(r,{children:v(h,{style:{fontSize:`18px`,fontWeight:600,color:this.config.theme?.colors?.linkCardTitle,margin:`0px`,...P},children:a})}),d||f?y(r,{style:{paddingLeft:`6px`,verticalAlign:`middle`},children:[d?v(`span`,{style:{fontWeight:600,color:this.config.theme?.colors?.linkCardBadgeText,padding:`4px 8px`,borderRadius:`8px`,backgroundColor:this.config.theme?.colors?.linkCardBadgeBackground,fontSize:`12px`,lineHeight:`12px`},children:d}):null,` `,f&&!d?v(`span`,{style:{fontWeight:`normal`,color:this.config.theme?.colors?.linkCardSubTitle,fontSize:`12px`,lineHeight:`12px`},children:f}):null]}):null]}),y(h,{style:{fontSize:`16px`,color:this.config.theme?.colors?.linkCardDescription,marginTop:`0px`,marginBottom:`0px`,...P},children:[o,` `,c?v(`a`,{href:m,rel:`noopener noreferrer`,style:{color:this.config.theme?.colors?.linkCardTitle,fontSize:`14px`,fontWeight:600,textDecoration:`underline`},children:c}):null]})]})})]})}section(e,t){let{attrs:n}=e,{borderRadius:i=0,backgroundColor:a=I,align:o=L,borderWidth:s=R,borderColor:c=z,marginTop:l=B,marginRight:u=V,marginBottom:d=H,marginLeft:f=U,paddingTop:m=W,paddingRight:h=G,paddingBottom:g=K,paddingLeft:y=q}=n||{},b=this.shouldShow(e,t);return b?v(p,{style:{marginTop:l,marginRight:u,marginBottom:d,marginLeft:f},children:v(r,{align:o,style:{borderColor:c,borderWidth:s,borderStyle:`solid`,backgroundColor:a,borderRadius:i,paddingTop:m,paddingRight:h,paddingBottom:g,paddingLeft:y},children:this.getMappedContent(e,{...t,parent:e})})}):v(_,{})}columns(e,t){let{attrs:n}=e,r=this.shouldShow(e,t);if(!r)return v(_,{});let[i,a]=this.adjustColumnsContent(e);return v(p,{width:`${a}%`,style:{margin:0,padding:0,width:`${a}%`},className:`tab-row-full`,children:this.getMappedContent(i,{...t,parent:i})})}adjustColumnsContent(e){let{content:t=[]}=e,n=100,r=t.filter(e=>e.type===`column`&&!!Number(e.attrs?.width||0)),i=t.filter(e=>e.type===`column`&&(e.attrs?.width===`auto`||!e.attrs?.width)),a=r.reduce((e,t)=>e+Number(t.attrs?.width),0),o=n-a,s=Math.round(o/i.length),c=t.filter(e=>e.type===`column`).length,l=e.attrs?.gap??J;return[{...e,content:t.map((e,n)=>{let r=e.type===`column`&&(e.attrs?.width===`auto`||!e.attrs?.width),i=n===0,a=n>0&&n<c-1,o=n===t.length-1,u=0,d=0;if(c<3)u=i?0:l/2,d=o?0:l/2;else{let e=l/2*1.5,t=e/2;u=i?0:a?t:e,d=o?0:a?t:e}return u=Math.round(u*100)/100,d=Math.round(d*100)/100,{...e,attrs:{...e.attrs,width:r?s:e.attrs?.width,isFirstColumn:i,isLastColumn:o,index:n,paddingLeft:u,paddingRight:d}}})},i.length===0?Math.min(n,a):n]}column(e,t){let{attrs:n}=e,{width:i,verticalAlign:a=`top`,paddingLeft:o=0,paddingRight:s=0}=n||{};return v(r,{width:`${Number(i)}%`,style:{width:`${Number(i)}%`,margin:0,verticalAlign:a},className:`tab-col-full`,children:v(m,{style:{margin:0,paddingLeft:o,paddingRight:s},className:`tab-pad`,children:this.getMappedContent(e,{...t,parent:e})})})}repeat(t,n){let{attrs:r}=t,{each:i=``}=r||{},a=this.shouldShow(t,n);if(!a)return v(_,{});let{payloadValue:o}=n||{};o=typeof o==`object`?o:{};let s=this.payloadValues.get(i)??o[i]??[];if(!Array.isArray(s))throw Error(`Payload value for each "${i}" is not an array`);return v(_,{children:s.map(r=>v(e,{children:this.getMappedContent(t,{...n,parent:t,payloadValue:r})},D()))})}for(e,t){return this.repeat(e,t)}shouldShow(e,t){let n=e?.attrs?.showIfKey??``;if(!n)return!0;let{payloadValue:r}=t||{};return r=typeof r==`object`?r:{},!!(this.payloadValues.get(n)??r[n])}htmlCodeBlock(e,t){let n=this.shouldShow(e,t);if(!n)return v(_,{});let r=e.content?.reduce((e,n)=>{if(n?.type===`text`)return e+n?.text;if(n?.type===`variable`){let r=this.getVariableValue(n?.attrs?.id,n?.attrs?.fallback,t);return e+r}return e},``)||``,i=x(r),a=b(i),o=a?.querySelector(`head`);o?.remove();let s=a.toString();return v(`table`,{align:`left`,width:`100%`,border:0,cellPadding:`0`,cellSpacing:`0`,role:`presentation`,children:v(`tbody`,{children:v(`tr`,{style:{width:`100%`},children:v(`td`,{style:{width:`100%`},dangerouslySetInnerHTML:{__html:s}})})})})}inlineImage(e,t){let{attrs:n}=e,{src:r,isSrcVariable:i,alt:a=``,title:o=``,height:s=Y,width:c=X,externalLink:l=``,isExternalLinkVariable:u}=n||{};r=i?this.variableUrlValue(r,t):r,l=u?this.variableUrlValue(l,t):l;let d=v(`img`,{src:r,alt:a,title:o,width:c,height:s,style:{display:`inline`,verticalAlign:`middle`,width:`${c}px`,height:`${s}px`,outline:`none`,border:`none`,textDecoration:`none`}});return l?v(`a`,{href:l,rel:`noopener noreferrer`,style:{display:`inline`,textDecoration:`none`},target:`_blank`,children:d}):d}};async function he(e,t){let{theme:n,preview:r,...i}=t||{},a=new me(e);return a.setPreviewText(r),a.setTheme(n||{}),a.render(i)}export{J as DEFAULT_COLUMNS_GAP,ie as DEFAULT_COLUMNS_WIDTH,ae as DEFAULT_COLUMN_BACKGROUND_COLOR,ce as DEFAULT_COLUMN_BORDER_COLOR,oe as DEFAULT_COLUMN_BORDER_RADIUS,se as DEFAULT_COLUMN_BORDER_WIDTH,de as DEFAULT_COLUMN_PADDING_BOTTOM,fe as DEFAULT_COLUMN_PADDING_LEFT,ue as DEFAULT_COLUMN_PADDING_RIGHT,le as DEFAULT_COLUMN_PADDING_TOP,$ as DEFAULT_HTML_PROPS,Y as DEFAULT_INLINE_IMAGE_HEIGHT,X as DEFAULT_INLINE_IMAGE_WIDTH,Q as DEFAULT_META_TAGS,L as DEFAULT_SECTION_ALIGN,I as DEFAULT_SECTION_BACKGROUND_COLOR,z as DEFAULT_SECTION_BORDER_COLOR,R as DEFAULT_SECTION_BORDER_WIDTH,H as DEFAULT_SECTION_MARGIN_BOTTOM,U as DEFAULT_SECTION_MARGIN_LEFT,V as DEFAULT_SECTION_MARGIN_RIGHT,B as DEFAULT_SECTION_MARGIN_TOP,K as DEFAULT_SECTION_PADDING_BOTTOM,q as DEFAULT_SECTION_PADDING_LEFT,G as DEFAULT_SECTION_PADDING_RIGHT,W as DEFAULT_SECTION_PADDING_TOP,Z as LINK_PROTOCOL_REGEX,me as Maily,he as render};
1
+ import { BUTTON_KINDS, DEFAULT_CONTAINER_MAX_WIDTH, DEFAULT_FONT_FALLBACK, DEFAULT_FONT_FAMILIES, MAILY_MARK_TYPES, MAILY_NODE_TYPES, VISIBILITY_ACTIONS, VISIBILITY_OPERATORS, absoluteFromPercentage, buildDocFromVariableText, deepMerge, getColumnWidthPercent, getCssDirection, getFontFaceStyle, getFontFamilyNames, getSuppressedMargins, getThemeDeclarations, hasVariableInText, invariant, is, isDef, isObject, mergeInlineStyles, parseInlineStyles, parseWidthToPercentage, roundTo, serializeVariableToText, stringifyInlineStyles } from "@maily-to/shared";
2
+ import { Fragment } from "react";
3
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
4
+ import { Body, Button, Column, Container, Head, Heading, Hr, Html, Img, Preview, Row, Section } from "@react-email/components";
5
+ import juice from "juice";
6
+ import { parse } from "node-html-parser";
7
+ import { render as render$1 } from "@react-email/render";
8
+ //#region src/config.ts
9
+ const DEFAULT_VARIABLE_FORMATTER = ({ fallback, variable }) => {
10
+ return serializeVariableToText({
11
+ fallback,
12
+ id: variable
13
+ });
14
+ };
15
+ function buildConfig(config = {}) {
16
+ return {
17
+ fontFamilies: config.fontFamilies ?? DEFAULT_FONT_FAMILIES,
18
+ htmlProps: config.htmlProps ?? {},
19
+ meta: config.meta ?? [],
20
+ openTrackingPixel: config.openTrackingPixel,
21
+ preview: config.preview,
22
+ variableFormatter: config.variableFormatter ?? DEFAULT_VARIABLE_FORMATTER,
23
+ variableValues: new Map(Object.entries(config.variables ?? {}))
24
+ };
25
+ }
26
+ //#endregion
27
+ //#region src/lib/resolve-variable.ts
28
+ /**
29
+ * Resolves a single variable ID using the 3-stage lookup:
30
+ * 1. item (current repeat iteration)
31
+ * 2. variableValues map
32
+ * 3. variableFormatter (fallback)
33
+ */
34
+ function resolveVariableId(id, fallback, ctx) {
35
+ const { config } = ctx;
36
+ const item = ctx.get("item");
37
+ if (item && id in item) return String(item[id]);
38
+ const value = config.variableValues.get(id);
39
+ if (value !== void 0) return typeof value === "object" ? JSON.stringify(value) : String(value);
40
+ return config.variableFormatter({
41
+ fallback: fallback ?? void 0,
42
+ variable: id
43
+ });
44
+ }
45
+ function getVariableId(text) {
46
+ if (!hasVariableInText(text)) return text.trim() || null;
47
+ const paragraph = buildDocFromVariableText(text).content.find((node) => node.type === MAILY_NODE_TYPES.PARAGRAPH);
48
+ for (const node of paragraph?.content ?? []) if (node.type === MAILY_NODE_TYPES.VARIABLE) return node.attrs.id || null;
49
+ return null;
50
+ }
51
+ function getVariableValue(options) {
52
+ const { ctx, id } = options;
53
+ const item = ctx.get("item");
54
+ return item && id in item ? item[id] : ctx.config.variableValues.get(id);
55
+ }
56
+ function getVariableList(each, ctx) {
57
+ const id = getVariableId(each);
58
+ if (!id) return [];
59
+ const value = getVariableValue({
60
+ ctx,
61
+ id
62
+ });
63
+ return Array.isArray(value) ? value : [];
64
+ }
65
+ /**
66
+ * Resolves a text string that may contain `{{variable}}` placeholders.
67
+ * Returns the original string unchanged if no placeholders are present.
68
+ */
69
+ function resolveVariableText(text, ctx) {
70
+ if (!hasVariableInText(text)) return text;
71
+ const paragraph = buildDocFromVariableText(text).content.find((node) => node.type === MAILY_NODE_TYPES.PARAGRAPH);
72
+ if (!paragraph) return text;
73
+ return paragraph.content.map((node) => {
74
+ if (node.type === MAILY_NODE_TYPES.TEXT) return node.text;
75
+ if (node.type === MAILY_NODE_TYPES.VARIABLE) {
76
+ const { fallback, id } = node.attrs ?? {};
77
+ return id ? resolveVariableId(id, fallback, ctx) : "";
78
+ }
79
+ return "";
80
+ }).join("");
81
+ }
82
+ //#endregion
83
+ //#region src/lib/visibility.ts
84
+ function getOperatorMatch(options) {
85
+ const { operator, resolved, value } = options;
86
+ switch (operator) {
87
+ case VISIBILITY_OPERATORS.IS_TRUE: return Boolean(resolved);
88
+ case VISIBILITY_OPERATORS.IS_FALSE: return !resolved;
89
+ case VISIBILITY_OPERATORS.EQUALS: return String(resolved) === value;
90
+ case VISIBILITY_OPERATORS.NOT_EQUALS: return String(resolved) !== value;
91
+ case VISIBILITY_OPERATORS.CONTAINS: return String(resolved).includes(value);
92
+ case VISIBILITY_OPERATORS.NOT_CONTAINS: return !String(resolved).includes(value);
93
+ case VISIBILITY_OPERATORS.STARTS_WITH: return String(resolved).startsWith(value);
94
+ case VISIBILITY_OPERATORS.ENDS_WITH: return String(resolved).endsWith(value);
95
+ case VISIBILITY_OPERATORS.GREATER_THAN: return Number(resolved) > Number(value);
96
+ case VISIBILITY_OPERATORS.LESS_THAN: return Number(resolved) < Number(value);
97
+ default: return false;
98
+ }
99
+ }
100
+ function getVisibilityMatch(options) {
101
+ const { ctx, rule } = options;
102
+ const id = getVariableId(rule.variable);
103
+ return getOperatorMatch({
104
+ operator: rule.operator,
105
+ resolved: id ? getVariableValue({
106
+ ctx,
107
+ id
108
+ }) : void 0,
109
+ value: rule.value
110
+ });
111
+ }
112
+ function shouldShowNode(options) {
113
+ const { ctx, node } = options;
114
+ const rule = node.attrs?.visibilityRule;
115
+ if (!rule) return true;
116
+ const matched = getVisibilityMatch({
117
+ ctx,
118
+ rule
119
+ });
120
+ return rule.action === VISIBILITY_ACTIONS.SHOW ? matched : !matched;
121
+ }
122
+ //#endregion
123
+ //#region src/lib/styles.ts
124
+ function getNodeStyle(style) {
125
+ return style ? parseInlineStyles(style) : void 0;
126
+ }
127
+ const ANTIALIASED = {
128
+ WebkitFontSmoothing: "antialiased",
129
+ MozOsxFontSmoothing: "grayscale"
130
+ };
131
+ function getStyleAlignment(style) {
132
+ const start = style?.marginLeft === "auto";
133
+ const end = style?.marginRight === "auto";
134
+ if (start && end) return "center";
135
+ if (end) return "left";
136
+ if (start) return "right";
137
+ }
138
+ //#endregion
139
+ //#region src/nodes/blockquote.tsx
140
+ const blockquote = (node, ctx) => {
141
+ if (!is.blockquote(node)) return null;
142
+ return /* @__PURE__ */ jsx("blockquote", {
143
+ dir: node.attrs?.dir ?? void 0,
144
+ style: {
145
+ ...getCssDirection(node.attrs?.dir),
146
+ ...getNodeStyle(node.attrs?.style)
147
+ },
148
+ children: ctx.children(node)
149
+ });
150
+ };
151
+ //#endregion
152
+ //#region src/lib/preview.ts
153
+ /**
154
+ * Resolves a preview value to a plain string.
155
+ *
156
+ * - `string` → resolves `{{variable}}` placeholders
157
+ * - `JSONContent` → walks the tree and resolves variable nodes
158
+ */
159
+ function preview(options) {
160
+ const { ctx, preview } = options;
161
+ if (typeof preview === "string") return resolveVariableText(preview, ctx);
162
+ return getWalkedText({
163
+ ctx,
164
+ doc: preview
165
+ });
166
+ }
167
+ function getWalkedText(options) {
168
+ const { ctx, doc } = options;
169
+ const parts = [];
170
+ if (!is.node(doc)) return parts.join("");
171
+ function visitor(node) {
172
+ if (is.text(node)) parts.push(node.text);
173
+ if (is.variable(node)) {
174
+ const { fallback, id } = node.attrs;
175
+ if (!id) return;
176
+ parts.push(resolveVariableId(id, fallback ?? void 0, ctx));
177
+ }
178
+ if (is.parent(node)) node.content.forEach(visitor);
179
+ }
180
+ visitor(doc);
181
+ return parts.join("");
182
+ }
183
+ //#endregion
184
+ //#region src/lib/slots.tsx
185
+ function getPreviewSlot(ctx) {
186
+ const { preview: preview$1 } = ctx.config;
187
+ if (!preview$1) return null;
188
+ return /* @__PURE__ */ jsx(Preview, { children: preview({
189
+ ctx,
190
+ preview: preview$1
191
+ }) });
192
+ }
193
+ function getTrackingPixelSlot(ctx) {
194
+ const { openTrackingPixel } = ctx.config;
195
+ if (!openTrackingPixel) return null;
196
+ return /* @__PURE__ */ jsx(Img, {
197
+ alt: "",
198
+ height: "1",
199
+ src: openTrackingPixel,
200
+ style: { display: "none" },
201
+ width: "1"
202
+ });
203
+ }
204
+ //#endregion
205
+ //#region src/nodes/body.tsx
206
+ const body = (node, ctx) => {
207
+ if (!is.body(node)) return null;
208
+ const { parent } = ctx;
209
+ const isShell = is.node(parent) && is.doc(parent);
210
+ return /* @__PURE__ */ jsxs(Body, {
211
+ style: getNodeStyle(node.attrs?.style),
212
+ children: [
213
+ isShell ? getPreviewSlot(ctx) : null,
214
+ ctx.children(node),
215
+ isShell ? getTrackingPixelSlot(ctx) : null
216
+ ]
217
+ });
218
+ };
219
+ //#endregion
220
+ //#region src/nodes/bullet-list.tsx
221
+ const bulletList = (node, ctx) => {
222
+ if (!is.bulletList(node)) return null;
223
+ return /* @__PURE__ */ jsx("ul", {
224
+ dir: node.attrs?.dir ?? void 0,
225
+ style: {
226
+ ...getCssDirection(node.attrs?.dir),
227
+ ...getNodeStyle(node.attrs?.style)
228
+ },
229
+ children: ctx.children(node)
230
+ });
231
+ };
232
+ //#endregion
233
+ //#region src/lib/link.ts
234
+ /**
235
+ * Extracts all valid URLs from link marks in a Maily document.
236
+ * Returns a deduplicated Set of href strings.
237
+ */
238
+ function links(json) {
239
+ const links = /* @__PURE__ */ new Set();
240
+ if (!is.node(json)) return links;
241
+ function visitor(node) {
242
+ if (is.marked(node)) for (const mark of node.marks) {
243
+ if (!is.link(mark)) continue;
244
+ const href = mark.attrs.href;
245
+ if (!isValidUrl(href)) continue;
246
+ links.add(href);
247
+ }
248
+ if (is.parent(node)) node.content.forEach(visitor);
249
+ }
250
+ visitor(json);
251
+ return links;
252
+ }
253
+ function isValidUrl(value) {
254
+ try {
255
+ new URL(value);
256
+ return true;
257
+ } catch {
258
+ return false;
259
+ }
260
+ }
261
+ const UNSAFE_SCHEME = /^(?:data|javascript|vbscript):/i;
262
+ function getSafeHref(url) {
263
+ if (!url) return url ?? void 0;
264
+ return UNSAFE_SCHEME.test(url.replace(/\s/g, "")) ? void 0 : url;
265
+ }
266
+ //#endregion
267
+ //#region src/nodes/button.tsx
268
+ const button = (node, ctx) => {
269
+ if (!is.button(node)) return null;
270
+ const { align, kind, url } = node.attrs;
271
+ const style = getNodeStyle(node.attrs.style);
272
+ const href = getSafeHref(resolveVariableText(url, ctx));
273
+ if (kind === BUTTON_KINDS.FULL_WIDTH) {
274
+ const { backgroundColor, color, ...cellStyle } = style ?? {};
275
+ return /* @__PURE__ */ jsx(Row, { children: /* @__PURE__ */ jsx(Column, {
276
+ align,
277
+ style: {
278
+ backgroundColor,
279
+ ...cellStyle
280
+ },
281
+ children: /* @__PURE__ */ jsx("a", {
282
+ href,
283
+ style: {
284
+ color,
285
+ display: "block",
286
+ textAlign: align,
287
+ textDecoration: "none"
288
+ },
289
+ target: "_blank",
290
+ children: ctx.children(node)
291
+ })
292
+ }) });
293
+ }
294
+ return /* @__PURE__ */ jsx(Row, { children: /* @__PURE__ */ jsx(Column, {
295
+ align,
296
+ children: /* @__PURE__ */ jsx(Button, {
297
+ href,
298
+ style: {
299
+ display: "inline-block",
300
+ ...style
301
+ },
302
+ children: ctx.children(node)
303
+ })
304
+ }) });
305
+ };
306
+ //#endregion
307
+ //#region src/nodes/column.tsx
308
+ const column = (node, ctx) => {
309
+ if (!is.column(node)) return null;
310
+ const width = ctx.get("columnWidth") ?? (node.attrs.width === null ? void 0 : `${node.attrs.width}%`);
311
+ return /* @__PURE__ */ jsx(Column, {
312
+ className: "tab-col-full",
313
+ style: {
314
+ margin: 0,
315
+ verticalAlign: node.attrs.verticalAlign,
316
+ width,
317
+ ...getNodeStyle(node.attrs.style)
318
+ },
319
+ width,
320
+ children: ctx.children(node)
321
+ });
322
+ };
323
+ //#endregion
324
+ //#region src/lib/columns.ts
325
+ /**
326
+ * Simulates CSS `flexbox gap` using table-cell percentages.
327
+ *
328
+ * Since tables don't support `gap`, we create empty spacer `<td>` cells
329
+ * between columns. This function calculates how wide each column and
330
+ * spacer should be so the layout behaves similar to flexbox.
331
+ *
332
+ * How the gap affects the layout depends on the column configuration:
333
+ *
334
+ * 1. When there are auto-width columns
335
+ * The row always fills 100% of the container.
336
+ * Fixed columns keep their exact width, and auto columns divide
337
+ * the remaining space after subtracting fixed widths and gaps.
338
+ *
339
+ * Example:
340
+ * fixed 40% + auto column, gap 8px in a 600px container
341
+ * → auto column becomes ~58.667%
342
+ *
343
+ * 2. When all columns have fixed widths and still fit
344
+ * The row width becomes `fixed widths + gaps`, which may be
345
+ * smaller than 100%. Columns keep their exact size.
346
+ *
347
+ * Example:
348
+ * 20% + 20% columns, gap 8px in a 600px container
349
+ * → row width becomes ~41.333%
350
+ *
351
+ * 3. When all columns are fixed but overflow
352
+ * If `fixed widths + gaps` exceed 100%, everything is scaled
353
+ * down proportionally so the row never exceeds the container.
354
+ *
355
+ * Example:
356
+ * 50% + 50% columns with gap 8px
357
+ * → both columns shrink to ~49.342%
358
+ */
359
+ function calculateColumnLayout(columnNodes, gap, containerBox) {
360
+ const count = columnNodes.length;
361
+ if (count === 0) return {
362
+ columns: [],
363
+ gapTdWidthPercent: 0,
364
+ rowWidthPercent: 0
365
+ };
366
+ const gapCount = count - 1;
367
+ const gapPercent = gapCount > 0 && containerBox > 0 ? roundTo(gap / containerBox * 100, 3) : 0;
368
+ const totalGapPercent = roundTo(gapCount * gapPercent, 3);
369
+ const percents = columnNodes.map((node) => getColumnWidthPercent({
370
+ containerWidth: containerBox,
371
+ width: node.attrs.width
372
+ }));
373
+ const fixedSum = percents.reduce((sum, percent) => sum + (percent ?? 0), 0);
374
+ const autoCount = percents.filter((percent) => percent === null).length;
375
+ const autoEach = autoCount > 0 ? roundTo(Math.max(0, 100 - fixedSum - totalGapPercent) / autoCount, 3) : 0;
376
+ let containerPercents = percents.map((percent) => percent ?? autoEach);
377
+ let rowWidthPercent = autoCount > 0 ? 100 : roundTo(fixedSum + totalGapPercent, 3);
378
+ let effectiveGapPercent = gapPercent;
379
+ if (autoCount === 0 && rowWidthPercent > 100) {
380
+ const scale = 100 / rowWidthPercent;
381
+ containerPercents = containerPercents.map((percent) => roundTo(percent * scale, 3));
382
+ effectiveGapPercent = roundTo(gapPercent * scale, 3);
383
+ rowWidthPercent = 100;
384
+ }
385
+ const toRowRelative = (percent) => rowWidthPercent > 0 ? roundTo(percent / rowWidthPercent * 100, 3) : 0;
386
+ return {
387
+ columns: columnNodes.map((node, index) => ({
388
+ containerPercent: containerPercents[index],
389
+ node: {
390
+ ...node,
391
+ attrs: {
392
+ ...node.attrs,
393
+ width: percents[index] ?? containerPercents[index]
394
+ }
395
+ },
396
+ tdWidthPercent: toRowRelative(containerPercents[index])
397
+ })),
398
+ gapTdWidthPercent: toRowRelative(effectiveGapPercent),
399
+ rowWidthPercent
400
+ };
401
+ }
402
+ //#endregion
403
+ //#region src/nodes/columns.tsx
404
+ const COLUMNS_RESPONSIVE_CSS = `@media only screen and (max-width:425px){.tab-row-full{width:100%!important}.tab-col-full{display:block!important;width:100%!important}.tab-gap{display:none!important}}`;
405
+ const columns = (node, ctx) => {
406
+ if (!is.columns(node)) return null;
407
+ ctx.style(COLUMNS_RESPONSIVE_CSS);
408
+ const { columns, gapTdWidthPercent, rowWidthPercent } = calculateColumnLayout(node.content.filter(is.column), node.attrs.gap, ctx.box);
409
+ if (columns.length === 0) return null;
410
+ const width = `${rowWidthPercent}%`;
411
+ const gapWidth = `${gapTdWidthPercent}%`;
412
+ return /* @__PURE__ */ jsx(Section, {
413
+ style: getNodeStyle(node.attrs.style),
414
+ children: /* @__PURE__ */ jsx(Row, {
415
+ align: "left",
416
+ className: "tab-row-full",
417
+ style: { width },
418
+ width,
419
+ children: columns.map((item, index) => {
420
+ const childCtx = ctx.child({
421
+ parent: node,
422
+ siblingIndex: index,
423
+ size: {
424
+ totalWidth: absoluteFromPercentage(item.containerPercent, ctx.box),
425
+ totalBorder: 0,
426
+ totalPadding: 0
427
+ }
428
+ });
429
+ childCtx.set("columnWidth", `${item.tdWidthPercent}%`);
430
+ return /* @__PURE__ */ jsxs(Fragment, { children: [childCtx.render(item.node), node.attrs.gap > 0 && index < columns.length - 1 ? /* @__PURE__ */ jsx(Column, {
431
+ className: "tab-gap",
432
+ style: { width: gapWidth },
433
+ width: gapWidth
434
+ }) : null] }, index);
435
+ })
436
+ })
437
+ });
438
+ };
439
+ //#endregion
440
+ //#region src/lib/sizing.ts
441
+ function parsePxValue(value) {
442
+ if (value === void 0 || value === null) return 0;
443
+ if (typeof value === "number") return value;
444
+ const trimmed = value.trim();
445
+ if (trimmed.endsWith("px")) {
446
+ const parsed = Number.parseFloat(trimmed);
447
+ return Number.isNaN(parsed) ? 0 : parsed;
448
+ }
449
+ return 0;
450
+ }
451
+ function initSize(totalWidth) {
452
+ return {
453
+ totalWidth,
454
+ totalBorder: 0,
455
+ totalPadding: 0
456
+ };
457
+ }
458
+ function insetBox(size, spacing) {
459
+ return {
460
+ totalWidth: size.totalWidth,
461
+ totalBorder: size.totalBorder + parsePxValue(spacing.borderLeft) + parsePxValue(spacing.borderRight),
462
+ totalPadding: size.totalPadding + parsePxValue(spacing.paddingLeft) + parsePxValue(spacing.paddingRight)
463
+ };
464
+ }
465
+ function getShorthandSide(value, side) {
466
+ const parts = value?.trim().split(/\s+/);
467
+ if (!parts?.length) return;
468
+ return side === "right" ? parts[1] ?? parts[0] : parts[3] ?? parts[1] ?? parts[0];
469
+ }
470
+ function getBorderShorthandWidth(border) {
471
+ return border?.trim().split(/\s+/).find((token) => token.endsWith("px"));
472
+ }
473
+ function insetXFromStyle(size, style) {
474
+ const border = getBorderShorthandWidth(style?.border);
475
+ return insetBox(size, {
476
+ borderLeft: style?.borderLeftWidth ?? getShorthandSide(style?.borderWidth, "left") ?? border,
477
+ borderRight: style?.borderRightWidth ?? getShorthandSide(style?.borderWidth, "right") ?? border,
478
+ paddingLeft: style?.paddingLeft ?? getShorthandSide(style?.padding, "left"),
479
+ paddingRight: style?.paddingRight ?? getShorthandSide(style?.padding, "right")
480
+ });
481
+ }
482
+ //#endregion
483
+ //#region src/nodes/container.tsx
484
+ const container = (node, ctx) => {
485
+ if (!is.container(node)) return null;
486
+ const style = getNodeStyle(node.attrs?.style);
487
+ const size = insetXFromStyle(initSize(parsePxValue(style?.maxWidth) || DEFAULT_CONTAINER_MAX_WIDTH), style);
488
+ return /* @__PURE__ */ jsx(Container, {
489
+ style,
490
+ children: ctx.child({ size }).children(node)
491
+ });
492
+ };
493
+ //#endregion
494
+ //#region src/lib/font-face.ts
495
+ /**
496
+ * Registers a font face in the context's shared font collector.
497
+ * Deduplicates by family+style+weight+fallback so each variant
498
+ * only appears once in the final `<style>` block.
499
+ */
500
+ function registerFontFace(options) {
501
+ const { ctx, font } = options;
502
+ const { fallbackFontFamily, fontFamily, fontStyle = "normal", fontWeight = 400 } = font;
503
+ if (!fontFamily) return;
504
+ const key = `${fontFamily}:${fontStyle}:${fontWeight}:${fallbackFontFamily}`;
505
+ if (ctx.fonts.has(key)) return;
506
+ ctx.font(key, font);
507
+ }
508
+ function getFallbackFont(names) {
509
+ return (names.length > 1 ? names.at(-1) : void 0) ?? DEFAULT_FONT_FALLBACK;
510
+ }
511
+ function registerStyledFont(options) {
512
+ const { ctx, style } = options;
513
+ const declarations = parseInlineStyles(style);
514
+ const value = declarations.fontFamily;
515
+ if (!value) return;
516
+ const names = getFontFamilyNames(value);
517
+ const fontFamily = names[0];
518
+ if (!fontFamily) return;
519
+ const item = ctx.config.fontFamilies.find((entry) => {
520
+ return entry.fontFamily === fontFamily;
521
+ });
522
+ if (!item) return;
523
+ const weight = Number.parseInt(declarations.fontWeight ?? "", 10);
524
+ const { webFont } = item;
525
+ registerFontFace({
526
+ ctx,
527
+ font: {
528
+ fallbackFontFamily: getFallbackFont(names),
529
+ fontFamily,
530
+ fontStyle: declarations.fontStyle === "italic" ? "italic" : "normal",
531
+ fontWeight: Number.isNaN(weight) ? 400 : weight,
532
+ ...webFont ? { webFont } : {}
533
+ }
534
+ });
535
+ }
536
+ function registerDocumentFonts(options) {
537
+ const { ctx, node } = options;
538
+ const style = node.attrs?.style;
539
+ if (typeof style === "string" && style) registerStyledFont({
540
+ ctx,
541
+ style
542
+ });
543
+ for (const mark of node.marks ?? []) {
544
+ const markStyle = mark.attrs?.style;
545
+ if (typeof markStyle === "string" && markStyle) registerStyledFont({
546
+ ctx,
547
+ style: markStyle
548
+ });
549
+ }
550
+ for (const child of node.content ?? []) registerDocumentFonts({
551
+ ctx,
552
+ node: child
553
+ });
554
+ }
555
+ //#endregion
556
+ //#region src/lib/meta.tsx
557
+ /**
558
+ * Deduplication key for a meta descriptor. Uses a sorted-key JSON hash
559
+ * so `{ name: 'a', content: 'b' }` and `{ content: 'b', name: 'a' }`
560
+ * produce the same key.
561
+ */
562
+ function getHash(descriptor) {
563
+ const sorted = Object.keys(descriptor).sort().reduce((acc, key) => {
564
+ acc[key] = descriptor[key];
565
+ return acc;
566
+ }, {});
567
+ return JSON.stringify(sorted);
568
+ }
569
+ /**
570
+ * Converts MetaDescriptor objects into React elements for the `<head>`.
571
+ * Duplicates (by sorted-key JSON hash) are skipped.
572
+ */
573
+ function meta(descriptors) {
574
+ const seen = /* @__PURE__ */ new Set();
575
+ const elements = [];
576
+ for (const descriptor of descriptors) {
577
+ const key = getHash(descriptor);
578
+ if (seen.has(key)) continue;
579
+ seen.add(key);
580
+ const element = getMetaElement({
581
+ descriptor,
582
+ key
583
+ });
584
+ if (element) elements.push(element);
585
+ }
586
+ return elements;
587
+ }
588
+ function getMetaElement(options) {
589
+ const { descriptor, key } = options;
590
+ if ("charSet" in descriptor) return /* @__PURE__ */ jsx("meta", { charSet: descriptor.charSet }, key);
591
+ if ("title" in descriptor) return /* @__PURE__ */ jsx("title", { children: descriptor.title }, key);
592
+ if ("tagName" in descriptor) {
593
+ const { tagName, ...attrs } = descriptor;
594
+ if (tagName === "link") return /* @__PURE__ */ jsx("link", { ...attrs }, key);
595
+ return /* @__PURE__ */ jsx("meta", { ...attrs }, key);
596
+ }
597
+ const attrs = descriptor;
598
+ if ("httpEquiv" in attrs) {
599
+ const { httpEquiv, ...rest } = attrs;
600
+ return /* @__PURE__ */ jsx("meta", {
601
+ httpEquiv,
602
+ ...rest
603
+ }, key);
604
+ }
605
+ return /* @__PURE__ */ jsx("meta", { ...attrs }, key);
606
+ }
607
+ //#endregion
608
+ //#region src/nodes/document.tsx
609
+ const document = (node, ctx) => {
610
+ if (!is.doc(node)) return null;
611
+ const { dir } = node.attrs ?? {};
612
+ const { htmlProps, meta: meta$1 } = ctx.config;
613
+ registerDocumentFonts({
614
+ ctx,
615
+ node
616
+ });
617
+ const content = ctx.children(node);
618
+ for (const font of ctx.fonts.values()) ctx.style(getFontFaceStyle(font));
619
+ const css = Array.from(ctx.styles).join("");
620
+ return /* @__PURE__ */ jsxs(Html, {
621
+ lang: "en",
622
+ ...htmlProps,
623
+ ...dir ? { dir } : {},
624
+ children: [/* @__PURE__ */ jsxs(Head, { children: [
625
+ /* @__PURE__ */ jsx("meta", {
626
+ content: "IE=edge",
627
+ httpEquiv: "X-UA-Compatible"
628
+ }),
629
+ /* @__PURE__ */ jsx("meta", { name: "x-apple-disable-message-reformatting" }),
630
+ /* @__PURE__ */ jsx("meta", {
631
+ content: "light",
632
+ name: "color-scheme"
633
+ }),
634
+ /* @__PURE__ */ jsx("meta", {
635
+ content: "light",
636
+ name: "supported-color-schemes"
637
+ }),
638
+ meta(meta$1),
639
+ /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: css } })
640
+ ] }), content]
641
+ });
642
+ };
643
+ //#endregion
644
+ //#region src/nodes/footer.tsx
645
+ const footer = (node, ctx) => {
646
+ if (!is.footer(node)) return null;
647
+ return /* @__PURE__ */ jsx("small", {
648
+ dir: node.attrs?.dir ?? void 0,
649
+ style: {
650
+ ...ANTIALIASED,
651
+ ...getCssDirection(node.attrs?.dir),
652
+ ...getNodeStyle(node.attrs?.style)
653
+ },
654
+ children: ctx.children(node)
655
+ });
656
+ };
657
+ //#endregion
658
+ //#region src/nodes/hard-break.tsx
659
+ const hardBreak = () => {
660
+ return /* @__PURE__ */ jsx("br", {});
661
+ };
662
+ //#endregion
663
+ //#region src/nodes/heading.tsx
664
+ const HEADING_LEVELS = {
665
+ 1: "h1",
666
+ 2: "h2",
667
+ 3: "h3"
668
+ };
669
+ const heading = (node, ctx) => {
670
+ if (!is.heading(node)) return null;
671
+ return /* @__PURE__ */ jsx(Heading, {
672
+ as: HEADING_LEVELS[node.attrs.level],
673
+ dir: node.attrs.dir ?? void 0,
674
+ style: {
675
+ ...getCssDirection(node.attrs.dir),
676
+ ...getNodeStyle(node.attrs.style)
677
+ },
678
+ children: ctx.children(node)
679
+ });
680
+ };
681
+ //#endregion
682
+ //#region src/nodes/horizontal-rule.tsx
683
+ const horizontalRule = (node) => {
684
+ if (!is.horizontalRule(node)) return null;
685
+ return /* @__PURE__ */ jsx(Hr, { style: getNodeStyle(node.attrs?.style) });
686
+ };
687
+ //#endregion
688
+ //#region src/nodes/html-code-block.tsx
689
+ function getResolvedText(node, ctx) {
690
+ if (is.text(node)) return node.text;
691
+ if (is.variable(node)) {
692
+ const { fallback, id } = node.attrs;
693
+ return id ? resolveVariableId(id, fallback, ctx) : "";
694
+ }
695
+ if (!node.content) return "";
696
+ return node.content.map((child) => {
697
+ return getResolvedText(child, ctx);
698
+ }).join("");
699
+ }
700
+ const htmlCodeBlock = (node, ctx) => {
701
+ if (!is.htmlCodeBlock(node)) return null;
702
+ const source = node.content ? node.content.map((child) => {
703
+ return getResolvedText(child, ctx);
704
+ }).join("") : "";
705
+ const document = parse(juice(source));
706
+ document.querySelector("head")?.remove();
707
+ return /* @__PURE__ */ jsx("table", {
708
+ align: "left",
709
+ border: 0,
710
+ cellPadding: "0",
711
+ cellSpacing: "0",
712
+ role: "presentation",
713
+ style: getNodeStyle(node.attrs?.style),
714
+ width: "100%",
715
+ children: /* @__PURE__ */ jsx("tbody", { children: /* @__PURE__ */ jsx("tr", {
716
+ style: { width: "100%" },
717
+ children: /* @__PURE__ */ jsx("td", {
718
+ dangerouslySetInnerHTML: { __html: document.toString() },
719
+ style: { width: "100%" }
720
+ })
721
+ }) })
722
+ });
723
+ };
724
+ //#endregion
725
+ //#region src/nodes/image.tsx
726
+ const image = (node, ctx) => {
727
+ if (!is.image(node)) return null;
728
+ const { align, alt, externalLink, src, title, width } = node.attrs;
729
+ const resolvedSrc = resolveVariableText(src, ctx);
730
+ const resolvedExternalLink = externalLink ? getSafeHref(resolveVariableText(externalLink, ctx)) : externalLink;
731
+ const percent = parseWidthToPercentage(width, ctx.box);
732
+ const absoluteWidth = Math.round(ctx.box * percent / 100);
733
+ const img = /* @__PURE__ */ jsx(Img, {
734
+ alt: alt ?? void 0,
735
+ src: resolvedSrc || void 0,
736
+ style: {
737
+ display: "block",
738
+ height: "auto",
739
+ maxWidth: absoluteWidth,
740
+ width: width ?? "100%",
741
+ ...getNodeStyle(node.attrs.style)
742
+ },
743
+ title: title ?? void 0,
744
+ width: absoluteWidth
745
+ });
746
+ return /* @__PURE__ */ jsx(Row, { children: /* @__PURE__ */ jsx(Column, {
747
+ align,
748
+ children: resolvedExternalLink ? /* @__PURE__ */ jsx("a", {
749
+ href: resolvedExternalLink,
750
+ rel: "noopener noreferrer nofollow",
751
+ style: { display: "block" },
752
+ target: "_blank",
753
+ children: img
754
+ }) : img
755
+ }) });
756
+ };
757
+ //#endregion
758
+ //#region src/nodes/inline-image.tsx
759
+ const inlineImage = (node, ctx) => {
760
+ if (!is.inlineImage(node)) return null;
761
+ const { alt, externalLink, height, src, width } = node.attrs;
762
+ const resolvedSrc = resolveVariableText(src, ctx);
763
+ const resolvedExternalLink = externalLink ? getSafeHref(resolveVariableText(externalLink, ctx)) : externalLink;
764
+ const img = /* @__PURE__ */ jsx("img", {
765
+ alt: alt ?? "",
766
+ height,
767
+ src: resolvedSrc || void 0,
768
+ style: {
769
+ border: "none",
770
+ display: "inline",
771
+ height,
772
+ outline: "none",
773
+ textDecoration: "none",
774
+ verticalAlign: "middle",
775
+ width,
776
+ ...getNodeStyle(node.attrs.style)
777
+ },
778
+ width
779
+ });
780
+ if (!resolvedExternalLink) return img;
781
+ return /* @__PURE__ */ jsx("a", {
782
+ href: resolvedExternalLink,
783
+ rel: "noopener noreferrer nofollow",
784
+ style: {
785
+ display: "inline",
786
+ textDecoration: "none"
787
+ },
788
+ target: "_blank",
789
+ children: img
790
+ });
791
+ };
792
+ //#endregion
793
+ //#region src/nodes/inline-span.tsx
794
+ const inlineSpan = (node) => {
795
+ if (!is.inlineSpan(node)) return null;
796
+ return /* @__PURE__ */ jsx("span", { style: getNodeStyle(node.attrs?.style) });
797
+ };
798
+ //#endregion
799
+ //#region src/lib/spacing.ts
800
+ function getNodePosition(ctx) {
801
+ const { parent, siblingIndex } = ctx;
802
+ const content = parent && is.parent(parent) ? parent.content : [];
803
+ return {
804
+ isFirst: siblingIndex === 0,
805
+ isLast: siblingIndex === content.length - 1,
806
+ nextType: content[siblingIndex + 1]?.type,
807
+ parentType: parent?.type,
808
+ previousType: content[siblingIndex - 1]?.type
809
+ };
810
+ }
811
+ /**
812
+ * Returns true if this node's bottom margin should be collapsed — i.e. it's
813
+ * the last child of a block container, or is followed by a spacer or hr.
814
+ */
815
+ function shouldSuppressMarginBottom(ctx) {
816
+ return getSuppressedMargins(getNodePosition(ctx)).marginBottom;
817
+ }
818
+ //#endregion
819
+ //#region src/nodes/link-card.tsx
820
+ const linkCard = (node, ctx) => {
821
+ if (!is.linkCard(node)) return null;
822
+ const { badgeText, description, image, link, linkTitle, subTitle, title } = node.attrs;
823
+ const href = (link ? getSafeHref(resolveVariableText(link, ctx)) : "") || "#";
824
+ const alt = title || "Link card";
825
+ return /* @__PURE__ */ jsxs("a", {
826
+ href,
827
+ rel: "noopener noreferrer",
828
+ style: {
829
+ border: "1px solid #eaeaea",
830
+ borderRadius: "10px",
831
+ color: "inherit",
832
+ display: "block",
833
+ marginBottom: shouldSuppressMarginBottom(ctx) ? "0" : "20px",
834
+ textDecoration: "none",
835
+ ...getNodeStyle(node.attrs?.style)
836
+ },
837
+ target: "_blank",
838
+ children: [image ? /* @__PURE__ */ jsx(Row, {
839
+ style: { marginBottom: "6px" },
840
+ children: /* @__PURE__ */ jsx(Column, {
841
+ style: {
842
+ height: "100%",
843
+ width: "100%"
844
+ },
845
+ children: /* @__PURE__ */ jsx(Img, {
846
+ alt,
847
+ src: image,
848
+ style: {
849
+ borderRadius: "10px 10px 0 0",
850
+ height: "100%",
851
+ objectFit: "cover",
852
+ width: "100%"
853
+ },
854
+ title: alt
855
+ })
856
+ })
857
+ }) : null, /* @__PURE__ */ jsx(Row, {
858
+ style: {
859
+ marginBottom: "0",
860
+ marginTop: "0",
861
+ padding: "15px"
862
+ },
863
+ children: /* @__PURE__ */ jsxs(Column, {
864
+ style: { verticalAlign: "top" },
865
+ children: [/* @__PURE__ */ jsx(Row, {
866
+ align: "left",
867
+ style: {
868
+ marginBottom: "8px",
869
+ marginTop: "0"
870
+ },
871
+ children: /* @__PURE__ */ jsx(Column, { children: /* @__PURE__ */ jsxs("p", {
872
+ style: {
873
+ ...ANTIALIASED,
874
+ color: "#111827",
875
+ fontSize: "18px",
876
+ fontWeight: "600",
877
+ lineHeight: "24px",
878
+ margin: "0",
879
+ textAlign: "left"
880
+ },
881
+ children: [
882
+ title,
883
+ badgeText ? /* @__PURE__ */ jsx("span", {
884
+ style: {
885
+ backgroundColor: "#f3f4f6",
886
+ borderRadius: "8px",
887
+ color: "#6b7280",
888
+ fontSize: "12px",
889
+ fontWeight: "600",
890
+ lineHeight: "12px",
891
+ marginLeft: "6px",
892
+ padding: "4px 8px"
893
+ },
894
+ children: badgeText
895
+ }) : null,
896
+ subTitle && !badgeText ? /* @__PURE__ */ jsx("span", {
897
+ style: {
898
+ color: "#6b7280",
899
+ fontSize: "12px",
900
+ fontWeight: "normal",
901
+ lineHeight: "12px",
902
+ marginLeft: "6px"
903
+ },
904
+ children: subTitle
905
+ }) : null
906
+ ]
907
+ }) })
908
+ }), /* @__PURE__ */ jsxs("p", {
909
+ style: {
910
+ color: "#374151",
911
+ fontSize: "16px",
912
+ lineHeight: "24px",
913
+ marginBottom: "0",
914
+ marginTop: "0"
915
+ },
916
+ children: [
917
+ description,
918
+ " ",
919
+ linkTitle ? /* @__PURE__ */ jsx("a", {
920
+ href,
921
+ rel: "noopener noreferrer",
922
+ style: {
923
+ color: "#111827",
924
+ fontSize: "14px",
925
+ fontWeight: "600",
926
+ textDecoration: "underline"
927
+ },
928
+ target: "_blank",
929
+ children: linkTitle
930
+ }) : null
931
+ ]
932
+ })]
933
+ })
934
+ })]
935
+ });
936
+ };
937
+ //#endregion
938
+ //#region src/nodes/list-item.tsx
939
+ const listItem = (node, ctx) => {
940
+ if (!is.listItem(node)) return null;
941
+ return /* @__PURE__ */ jsx("li", {
942
+ dir: node.attrs?.dir ?? void 0,
943
+ style: {
944
+ ...ANTIALIASED,
945
+ ...getCssDirection(node.attrs?.dir),
946
+ ...getNodeStyle(node.attrs?.style)
947
+ },
948
+ children: ctx.children(node)
949
+ });
950
+ };
951
+ //#endregion
952
+ //#region src/nodes/ordered-list.tsx
953
+ const orderedList = (node, ctx) => {
954
+ if (!is.orderedList(node)) return null;
955
+ return /* @__PURE__ */ jsx("ol", {
956
+ start: node.attrs?.start,
957
+ style: {
958
+ ...getCssDirection(node.attrs?.dir),
959
+ ...getNodeStyle(node.attrs?.style)
960
+ },
961
+ children: ctx.children(node)
962
+ });
963
+ };
964
+ //#endregion
965
+ //#region src/nodes/paragraph.tsx
966
+ const paragraph = (node, ctx) => {
967
+ if (!is.paragraph(node)) return null;
968
+ return /* @__PURE__ */ jsx("p", {
969
+ dir: node.attrs?.dir ?? void 0,
970
+ style: {
971
+ ...getCssDirection(node.attrs?.dir),
972
+ ...getNodeStyle(node.attrs?.style)
973
+ },
974
+ children: ctx.children(node)
975
+ });
976
+ };
977
+ //#endregion
978
+ //#region src/nodes/repeat.tsx
979
+ const repeat = (node, ctx) => {
980
+ if (!is.repeat(node)) return null;
981
+ const { each } = node.attrs;
982
+ const payload = getVariableList(each, ctx);
983
+ return /* @__PURE__ */ jsx(Fragment$1, { children: payload.map((item, index) => {
984
+ const childContext = ctx.child({
985
+ parent: node,
986
+ siblingIndex: index
987
+ });
988
+ childContext.set("item", isObject(item) ? item : { value: item });
989
+ return /* @__PURE__ */ jsx(Fragment, { children: childContext.children(node) }, index);
990
+ }) });
991
+ };
992
+ //#endregion
993
+ //#region src/nodes/section.tsx
994
+ const section = (node, ctx) => {
995
+ if (!is.section(node)) return null;
996
+ const style = getNodeStyle(node.attrs?.style);
997
+ const align = getStyleAlignment(style) ?? "left";
998
+ return /* @__PURE__ */ jsx(Section, {
999
+ align,
1000
+ style,
1001
+ children: ctx.children(node)
1002
+ });
1003
+ };
1004
+ //#endregion
1005
+ //#region src/nodes/spacer.tsx
1006
+ const spacer = (node) => {
1007
+ if (!is.spacer(node)) return null;
1008
+ return /* @__PURE__ */ jsx(Container, { style: {
1009
+ height: `${node.attrs.height}px`,
1010
+ ...getNodeStyle(node.attrs.style)
1011
+ } });
1012
+ };
1013
+ //#endregion
1014
+ //#region src/lib/table.ts
1015
+ const ALIGNMENTS = [
1016
+ "center",
1017
+ "justify",
1018
+ "left",
1019
+ "right"
1020
+ ];
1021
+ const VERTICAL_ALIGNMENTS = [
1022
+ "baseline",
1023
+ "bottom",
1024
+ "middle",
1025
+ "top"
1026
+ ];
1027
+ function toAttributeLength(value) {
1028
+ if (!value) return;
1029
+ const trimmed = value.trim();
1030
+ if (trimmed.endsWith("%")) return trimmed;
1031
+ return trimmed.endsWith("px") ? trimmed.slice(0, -2) : void 0;
1032
+ }
1033
+ function toAllowedKeyword(value, allowed) {
1034
+ return value && allowed.includes(value) ? value : void 0;
1035
+ }
1036
+ function getTableAlignment(style) {
1037
+ const left = style.marginLeft === "auto";
1038
+ const right = style.marginRight === "auto";
1039
+ if (left && right) return "center";
1040
+ if (left) return "right";
1041
+ return right ? "left" : void 0;
1042
+ }
1043
+ function getTableAttributes(style) {
1044
+ if (!style) return {};
1045
+ return {
1046
+ align: getTableAlignment(style),
1047
+ bgcolor: style.backgroundColor,
1048
+ width: toAttributeLength(style.width)
1049
+ };
1050
+ }
1051
+ function getRowAttributes(style) {
1052
+ if (!style) return {};
1053
+ return {
1054
+ align: toAllowedKeyword(style.textAlign, ALIGNMENTS),
1055
+ bgcolor: style.backgroundColor,
1056
+ valign: toAllowedKeyword(style.verticalAlign, VERTICAL_ALIGNMENTS)
1057
+ };
1058
+ }
1059
+ function getCellAttributes(style) {
1060
+ if (!style) return {};
1061
+ return {
1062
+ align: toAllowedKeyword(style.textAlign, ALIGNMENTS),
1063
+ bgcolor: style.backgroundColor,
1064
+ height: toAttributeLength(style.height),
1065
+ valign: toAllowedKeyword(style.verticalAlign, VERTICAL_ALIGNMENTS),
1066
+ width: toAttributeLength(style.width)
1067
+ };
1068
+ }
1069
+ function getDeclaredWidth(style, box) {
1070
+ const width = style?.width?.trim();
1071
+ if (!width) return null;
1072
+ const value = Number.parseFloat(width);
1073
+ if (Number.isNaN(value)) return null;
1074
+ if (width.endsWith("%")) return box * value / 100;
1075
+ return width.endsWith("px") ? value : null;
1076
+ }
1077
+ function getCellWidths(cells, box) {
1078
+ const declared = cells.map((cell) => getDeclaredWidth(getNodeStyle(cell.attrs?.style), box));
1079
+ const spans = cells.map((cell) => Number(cell.attrs?.colspan) || 1);
1080
+ const claimed = declared.reduce((total, width) => total + (width ?? 0), 0);
1081
+ const freeSpans = spans.reduce((total, span, index) => declared[index] === null ? total + span : total, 0);
1082
+ const free = Math.max(0, box - claimed);
1083
+ return declared.map((width, index) => width ?? (freeSpans > 0 ? free * spans[index] / freeSpans : 0));
1084
+ }
1085
+ //#endregion
1086
+ //#region src/nodes/table.tsx
1087
+ const RESPONSIVE_TABLE_CSS = `@media only screen and (max-width:480px){table[data-mly-responsive="stack"]>tbody>tr>td{display:block!important;width:100%!important}}`;
1088
+ const table = (node, ctx) => {
1089
+ if (!is.table(node)) return null;
1090
+ const style = getNodeStyle(node.attrs.style);
1091
+ const hasHeaders = node.content.some((row) => row.content?.some((cell) => cell.type === MAILY_NODE_TYPES.TABLE_HEADER));
1092
+ if (node.attrs.responsive) ctx.style(RESPONSIVE_TABLE_CSS);
1093
+ return /* @__PURE__ */ jsx("table", {
1094
+ ...getTableAttributes(style),
1095
+ border: node.attrs.border ?? 0,
1096
+ cellPadding: node.attrs.cellpadding ?? 0,
1097
+ cellSpacing: node.attrs.cellspacing ?? 0,
1098
+ "data-mly-responsive": node.attrs.responsive ? "stack" : void 0,
1099
+ role: hasHeaders ? void 0 : "presentation",
1100
+ style,
1101
+ children: /* @__PURE__ */ jsx("tbody", { children: ctx.children(node) })
1102
+ });
1103
+ };
1104
+ //#endregion
1105
+ //#region src/nodes/table-cell.tsx
1106
+ const tableCell = (node, ctx) => {
1107
+ if (!is.tableCell(node)) return null;
1108
+ const style = getNodeStyle(node.attrs.style);
1109
+ const size = insetXFromStyle(ctx.size, style);
1110
+ return /* @__PURE__ */ jsx("td", {
1111
+ ...getCellAttributes(style),
1112
+ colSpan: node.attrs.colspan,
1113
+ rowSpan: node.attrs.rowspan,
1114
+ style,
1115
+ children: ctx.child({ size }).children(node)
1116
+ });
1117
+ };
1118
+ //#endregion
1119
+ //#region src/nodes/table-header.tsx
1120
+ const tableHeader = (node, ctx) => {
1121
+ if (!is.tableHeader(node)) return null;
1122
+ const style = getNodeStyle(node.attrs.style);
1123
+ const size = insetXFromStyle(ctx.size, style);
1124
+ return /* @__PURE__ */ jsx("th", {
1125
+ ...getCellAttributes(style),
1126
+ colSpan: node.attrs.colspan,
1127
+ rowSpan: node.attrs.rowspan,
1128
+ style,
1129
+ children: ctx.child({ size }).children(node)
1130
+ });
1131
+ };
1132
+ //#endregion
1133
+ //#region src/nodes/table-row.tsx
1134
+ const tableRow = (node, ctx) => {
1135
+ if (!is.tableRow(node)) return null;
1136
+ const style = getNodeStyle(node.attrs?.style);
1137
+ const widths = getCellWidths(node.content, ctx.box);
1138
+ return /* @__PURE__ */ jsx("tr", {
1139
+ ...getRowAttributes(style),
1140
+ style,
1141
+ children: node.content.map((cell, index) => /* @__PURE__ */ jsx(Fragment, { children: ctx.child({
1142
+ parent: node,
1143
+ siblingIndex: index,
1144
+ size: initSize(widths[index])
1145
+ }).render(cell) }, index))
1146
+ });
1147
+ };
1148
+ //#endregion
1149
+ //#region src/marks/bold.tsx
1150
+ const bold = (mark, text) => {
1151
+ return /* @__PURE__ */ jsx("strong", {
1152
+ style: getNodeStyle(mark.attrs?.style),
1153
+ children: text
1154
+ });
1155
+ };
1156
+ //#endregion
1157
+ //#region src/marks/code.tsx
1158
+ const code = (mark, text) => {
1159
+ return /* @__PURE__ */ jsx("code", {
1160
+ style: {
1161
+ ...ANTIALIASED,
1162
+ ...getNodeStyle(mark.attrs?.style)
1163
+ },
1164
+ children: text
1165
+ });
1166
+ };
1167
+ //#endregion
1168
+ //#region src/marks/italic.tsx
1169
+ const italic = (mark, text) => {
1170
+ return /* @__PURE__ */ jsx("em", {
1171
+ style: getNodeStyle(mark.attrs?.style),
1172
+ children: text
1173
+ });
1174
+ };
1175
+ //#endregion
1176
+ //#region src/marks/link.tsx
1177
+ const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
1178
+ const link = (mark, text, ctx) => {
1179
+ if (!is.link(mark)) return null;
1180
+ const { href, rel, style, target, title } = mark.attrs;
1181
+ return /* @__PURE__ */ jsx("a", {
1182
+ href: getSafeHref(href && resolveVariableText(href, ctx)),
1183
+ rel: rel ?? DEFAULT_LINK_REL,
1184
+ style: getNodeStyle(style),
1185
+ target: target ?? "_blank",
1186
+ title: title ?? void 0,
1187
+ children: text
1188
+ });
1189
+ };
1190
+ //#endregion
1191
+ //#region src/marks/strike.tsx
1192
+ const strike = (mark, text) => {
1193
+ return /* @__PURE__ */ jsx("s", {
1194
+ style: getNodeStyle(mark.attrs?.style),
1195
+ children: text
1196
+ });
1197
+ };
1198
+ //#endregion
1199
+ //#region src/marks/underline.tsx
1200
+ const underline = (mark, text) => {
1201
+ return /* @__PURE__ */ jsx("u", {
1202
+ style: getNodeStyle(mark.attrs?.style),
1203
+ children: text
1204
+ });
1205
+ };
1206
+ //#endregion
1207
+ //#region src/mark.tsx
1208
+ const MAILY_MARKS_ORDER = [
1209
+ MAILY_MARK_TYPES.UNDERLINE,
1210
+ MAILY_MARK_TYPES.BOLD,
1211
+ MAILY_MARK_TYPES.ITALIC,
1212
+ MAILY_MARK_TYPES.STRIKE,
1213
+ MAILY_MARK_TYPES.LINK,
1214
+ MAILY_MARK_TYPES.CODE
1215
+ ];
1216
+ const MAILY_MARK_RENDERERS = {
1217
+ [MAILY_MARK_TYPES.UNDERLINE]: underline,
1218
+ [MAILY_MARK_TYPES.BOLD]: bold,
1219
+ [MAILY_MARK_TYPES.ITALIC]: italic,
1220
+ [MAILY_MARK_TYPES.STRIKE]: strike,
1221
+ [MAILY_MARK_TYPES.LINK]: link,
1222
+ [MAILY_MARK_TYPES.CODE]: code
1223
+ };
1224
+ function render$2(mark, text, ctx) {
1225
+ if (!is.mark(mark)) return null;
1226
+ const renderer = MAILY_MARK_RENDERERS[mark.type];
1227
+ if (!renderer) return null;
1228
+ return renderer(mark, text, ctx);
1229
+ }
1230
+ function marks(node, ctx) {
1231
+ if (!is.marked(node)) return [];
1232
+ const textStyles = node.marks.filter((mark) => is.textStyle(mark) || is.highlight(mark) || is.span(mark)).reduce((acc, mark) => {
1233
+ if (is.textStyle(mark)) {
1234
+ if (mark.attrs.color) acc.color = mark.attrs.color;
1235
+ } else if (is.highlight(mark)) acc.backgroundColor = mark.attrs.color;
1236
+ else Object.assign(acc, getNodeStyle(mark.attrs?.style));
1237
+ return acc;
1238
+ }, {});
1239
+ const marks = node.marks.filter((mark) => !is.textStyle(mark) && !is.highlight(mark) && !is.span(mark)).sort((a, b) => MAILY_MARKS_ORDER.indexOf(a.type) - MAILY_MARKS_ORDER.indexOf(b.type));
1240
+ const text = node?.text || /* @__PURE__ */ jsx(Fragment$1, { children: "\xA0" });
1241
+ const baseText = isEmptyObject(textStyles) ? /* @__PURE__ */ jsx(Fragment$1, { children: text }) : /* @__PURE__ */ jsx("span", {
1242
+ style: textStyles,
1243
+ children: text
1244
+ });
1245
+ return marks.reduce((acc, mark, index) => {
1246
+ const component = render$2(mark, acc, ctx.child({
1247
+ parent: node,
1248
+ siblingIndex: index
1249
+ }));
1250
+ if (!component) return acc;
1251
+ return component;
1252
+ }, baseText);
1253
+ }
1254
+ function isEmptyObject(obj) {
1255
+ for (const _ in obj) return false;
1256
+ return true;
1257
+ }
1258
+ //#endregion
1259
+ //#region src/nodes/text.tsx
1260
+ const text = (node, ctx) => {
1261
+ if (!is.text(node)) return null;
1262
+ if (is.marked(node)) return marks(node, ctx);
1263
+ const { text } = node;
1264
+ if (!isDef(text)) return /* @__PURE__ */ jsx(Fragment$1, { children: "\xA0" });
1265
+ return /* @__PURE__ */ jsx(Fragment$1, { children: text });
1266
+ };
1267
+ //#endregion
1268
+ //#region src/nodes/variable.tsx
1269
+ const variable = (node, ctx) => {
1270
+ if (!is.variable(node)) return null;
1271
+ const { fallback, id } = node.attrs;
1272
+ if (!id) return /* @__PURE__ */ jsx(Fragment$1, { children: fallback ?? "" });
1273
+ return /* @__PURE__ */ jsx(Fragment$1, { children: resolveVariableId(id, fallback, ctx) });
1274
+ };
1275
+ //#endregion
1276
+ //#region src/node.tsx
1277
+ const MAILY_NODE_RENDERERS = {
1278
+ [MAILY_NODE_TYPES.DOCUMENT]: document,
1279
+ [MAILY_NODE_TYPES.BODY]: body,
1280
+ [MAILY_NODE_TYPES.CONTAINER]: container,
1281
+ [MAILY_NODE_TYPES.SECTION]: section,
1282
+ [MAILY_NODE_TYPES.COLUMNS]: columns,
1283
+ [MAILY_NODE_TYPES.COLUMN]: column,
1284
+ [MAILY_NODE_TYPES.PARAGRAPH]: paragraph,
1285
+ [MAILY_NODE_TYPES.HEADING]: heading,
1286
+ [MAILY_NODE_TYPES.REPEAT]: repeat,
1287
+ [MAILY_NODE_TYPES.IMAGE]: image,
1288
+ [MAILY_NODE_TYPES.INLINE_IMAGE]: inlineImage,
1289
+ [MAILY_NODE_TYPES.INLINE_SPAN]: inlineSpan,
1290
+ [MAILY_NODE_TYPES.SPACER]: spacer,
1291
+ [MAILY_NODE_TYPES.BUTTON]: button,
1292
+ [MAILY_NODE_TYPES.FOOTER]: footer,
1293
+ [MAILY_NODE_TYPES.BLOCKQUOTE]: blockquote,
1294
+ [MAILY_NODE_TYPES.HORIZONTAL_RULE]: horizontalRule,
1295
+ [MAILY_NODE_TYPES.HTML_CODE_BLOCK]: htmlCodeBlock,
1296
+ [MAILY_NODE_TYPES.HARD_BREAK]: hardBreak,
1297
+ [MAILY_NODE_TYPES.BULLET_LIST]: bulletList,
1298
+ [MAILY_NODE_TYPES.ORDERED_LIST]: orderedList,
1299
+ [MAILY_NODE_TYPES.LIST_ITEM]: listItem,
1300
+ [MAILY_NODE_TYPES.LINK_CARD]: linkCard,
1301
+ [MAILY_NODE_TYPES.TEXT]: text,
1302
+ [MAILY_NODE_TYPES.VARIABLE]: variable,
1303
+ [MAILY_NODE_TYPES.TABLE]: table,
1304
+ [MAILY_NODE_TYPES.TABLE_ROW]: tableRow,
1305
+ [MAILY_NODE_TYPES.TABLE_CELL]: tableCell,
1306
+ [MAILY_NODE_TYPES.TABLE_HEADER]: tableHeader
1307
+ };
1308
+ function dispatch(node, ctx) {
1309
+ if (!is.node(node)) return null;
1310
+ const renderer = MAILY_NODE_RENDERERS[node.type];
1311
+ if (!renderer) return null;
1312
+ if (!shouldShowNode({
1313
+ ctx,
1314
+ node
1315
+ })) return null;
1316
+ return renderer(node, ctx);
1317
+ }
1318
+ function children(parent, ctx) {
1319
+ if (!is.parent(parent)) return [];
1320
+ return parent.content.map((child, index) => {
1321
+ const component = ctx.child({
1322
+ parent,
1323
+ siblingIndex: index
1324
+ }).render(child);
1325
+ if (!component) return null;
1326
+ return /* @__PURE__ */ jsx(Fragment, { children: component }, index);
1327
+ }).filter(Boolean);
1328
+ }
1329
+ //#endregion
1330
+ //#region src/context.ts
1331
+ const DEFAULT_SIZE = {
1332
+ totalWidth: 600,
1333
+ totalBorder: 0,
1334
+ totalPadding: 0
1335
+ };
1336
+ /**
1337
+ * Creates the root RenderContext for a render pass. Node renderers
1338
+ * derive child contexts via `ctx.child()` as they descend the tree.
1339
+ */
1340
+ function defineRenderContext(opts) {
1341
+ const shared = {
1342
+ vars: /* @__PURE__ */ new Map(),
1343
+ styles: /* @__PURE__ */ new Set(),
1344
+ fonts: /* @__PURE__ */ new Map()
1345
+ };
1346
+ return defineContext({
1347
+ config: opts.config,
1348
+ parent: opts.parent,
1349
+ siblingIndex: opts.siblingIndex ?? 0,
1350
+ size: {
1351
+ ...DEFAULT_SIZE,
1352
+ ...opts.size
1353
+ }
1354
+ }, shared);
1355
+ }
1356
+ function defineContext(opts, shared) {
1357
+ const { config, parent, siblingIndex, size } = opts;
1358
+ const { vars, styles, fonts } = shared;
1359
+ let varCache = null;
1360
+ const ctx = {
1361
+ parent,
1362
+ siblingIndex,
1363
+ config,
1364
+ size,
1365
+ get box() {
1366
+ return size.totalWidth - size.totalBorder - size.totalPadding;
1367
+ },
1368
+ render(node) {
1369
+ return dispatch(node, ctx);
1370
+ },
1371
+ children(parent) {
1372
+ return children(parent, ctx);
1373
+ },
1374
+ set(key, value) {
1375
+ vars.set(key, value);
1376
+ varCache = null;
1377
+ },
1378
+ get(key) {
1379
+ return vars.get(key);
1380
+ },
1381
+ get var() {
1382
+ return varCache ??= Object.fromEntries(vars);
1383
+ },
1384
+ style(css) {
1385
+ styles.add(css);
1386
+ },
1387
+ font(key, font) {
1388
+ fonts.set(key, font);
1389
+ },
1390
+ child(opts) {
1391
+ const childSize = opts.size ? {
1392
+ totalWidth: opts.size.totalWidth ?? size.totalWidth,
1393
+ totalBorder: opts.size.totalBorder ?? size.totalBorder,
1394
+ totalPadding: opts.size.totalPadding ?? size.totalPadding
1395
+ } : size;
1396
+ const childShared = {
1397
+ vars: new Map(vars),
1398
+ styles,
1399
+ fonts
1400
+ };
1401
+ return defineContext({
1402
+ config,
1403
+ parent: opts.parent ?? parent,
1404
+ siblingIndex: opts.siblingIndex ?? siblingIndex,
1405
+ size: childSize
1406
+ }, childShared);
1407
+ },
1408
+ get styles() {
1409
+ return styles;
1410
+ },
1411
+ get fonts() {
1412
+ return fonts;
1413
+ }
1414
+ };
1415
+ return ctx;
1416
+ }
1417
+ //#endregion
1418
+ //#region src/lib/normalize.ts
1419
+ function getUnwrappedBodies(content) {
1420
+ return content.flatMap((node) => {
1421
+ return is.body(node) ? node.content : [node];
1422
+ });
1423
+ }
1424
+ function getShellBody(content) {
1425
+ const [only] = content;
1426
+ if (content.length === 1 && is.body(only)) return only;
1427
+ const authored = content.find((node) => {
1428
+ return is.body(node);
1429
+ });
1430
+ return {
1431
+ ...authored?.attrs ? { attrs: authored.attrs } : {},
1432
+ content: getUnwrappedBodies(content),
1433
+ type: MAILY_NODE_TYPES.BODY
1434
+ };
1435
+ }
1436
+ function getShellContainers(body) {
1437
+ const shelled = body.content.every((node) => {
1438
+ return is.container(node);
1439
+ });
1440
+ if (body.content.length > 0 && shelled) return body.content;
1441
+ return [{
1442
+ content: body.content,
1443
+ type: MAILY_NODE_TYPES.CONTAINER
1444
+ }];
1445
+ }
1446
+ function getNormalizedDocument(options) {
1447
+ const { document } = options;
1448
+ const body = getShellBody(document.content ?? []);
1449
+ return {
1450
+ ...document,
1451
+ content: [{
1452
+ ...body,
1453
+ content: getShellContainers(body)
1454
+ }]
1455
+ };
1456
+ }
1457
+ //#endregion
1458
+ //#region src/lib/theme.ts
1459
+ function getChildPosition(options) {
1460
+ const { index, parent } = options;
1461
+ const content = parent.content ?? [];
1462
+ return {
1463
+ isFirst: index === 0,
1464
+ isLast: index === content.length - 1,
1465
+ nextType: content[index + 1]?.type,
1466
+ parentType: parent.type,
1467
+ previousType: content[index - 1]?.type
1468
+ };
1469
+ }
1470
+ function getSpacedDeclarations(options) {
1471
+ const { declarations, position } = options;
1472
+ const suppressed = getSuppressedMargins(position);
1473
+ const spaced = { ...declarations };
1474
+ if (suppressed.marginTop) spaced.marginTop = "0";
1475
+ if (suppressed.marginBottom) spaced.marginBottom = "0";
1476
+ return spaced;
1477
+ }
1478
+ function getStyledAttrs(options) {
1479
+ const { attrs, declarations } = options;
1480
+ const authored = parseInlineStyles(attrs?.style ?? "");
1481
+ const style = stringifyInlineStyles(mergeInlineStyles(declarations, authored));
1482
+ return {
1483
+ ...attrs,
1484
+ style: style || null
1485
+ };
1486
+ }
1487
+ function getThemedMarks(options) {
1488
+ const { node, theme } = options;
1489
+ if (!is.marked(node)) return;
1490
+ return node.marks.map((mark) => {
1491
+ const attrs = mark.attrs;
1492
+ const declarations = getThemeDeclarations({
1493
+ attrs,
1494
+ theme,
1495
+ type: mark.type
1496
+ });
1497
+ if (!declarations) return mark;
1498
+ return {
1499
+ ...mark,
1500
+ attrs: getStyledAttrs({
1501
+ attrs,
1502
+ declarations
1503
+ })
1504
+ };
1505
+ });
1506
+ }
1507
+ function getThemedNode(options) {
1508
+ const { node, position, theme } = options;
1509
+ const attrs = node.attrs;
1510
+ const declarations = getThemeDeclarations({
1511
+ attrs,
1512
+ theme,
1513
+ type: node.type
1514
+ });
1515
+ const content = node.content?.map((child, index) => {
1516
+ return getThemedNode({
1517
+ node: child,
1518
+ position: getChildPosition({
1519
+ index,
1520
+ parent: node
1521
+ }),
1522
+ theme
1523
+ });
1524
+ });
1525
+ const marks = getThemedMarks({
1526
+ node,
1527
+ theme
1528
+ });
1529
+ if (!declarations) {
1530
+ if (!(content || marks)) return node;
1531
+ return {
1532
+ ...node,
1533
+ ...content ? { content } : {},
1534
+ ...marks ? { marks } : {}
1535
+ };
1536
+ }
1537
+ return {
1538
+ ...node,
1539
+ ...content ? { content } : {},
1540
+ ...marks ? { marks } : {},
1541
+ attrs: getStyledAttrs({
1542
+ attrs,
1543
+ declarations: getSpacedDeclarations({
1544
+ declarations,
1545
+ position
1546
+ })
1547
+ })
1548
+ };
1549
+ }
1550
+ function getThemedDocument(options) {
1551
+ const { document, theme } = options;
1552
+ const resolved = deepMerge(document.attrs?.theme ?? {}, theme ?? {});
1553
+ if (Object.keys(resolved).length === 0) return document;
1554
+ return {
1555
+ ...document,
1556
+ content: document.content.map((node, index) => {
1557
+ return getThemedNode({
1558
+ node,
1559
+ position: getChildPosition({
1560
+ index,
1561
+ parent: document
1562
+ }),
1563
+ theme: resolved
1564
+ });
1565
+ })
1566
+ };
1567
+ }
1568
+ //#endregion
1569
+ //#region src/render.tsx
1570
+ function markup(json, config = {}) {
1571
+ invariant(is.doc(json), `Expected a Maily document, received "${json?.type}"`);
1572
+ return defineRenderContext({ config: buildConfig(config) }).render(getThemedDocument({
1573
+ document: getNormalizedDocument({ document: json }),
1574
+ theme: config.theme
1575
+ }));
1576
+ }
1577
+ async function render(json, config = {}) {
1578
+ return render$1(markup(json, config));
1579
+ }
1580
+ async function renderText(json, config = {}) {
1581
+ return render$1(markup(json, config), { plainText: true });
1582
+ }
1583
+ //#endregion
1584
+ export { buildConfig, children, defineRenderContext, dispatch, getSafeHref, links, marks, markup, render, renderText };
1585
+
2
1586
  //# sourceMappingURL=index.mjs.map