@templatical/editor 0.57.0 → 0.57.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/{AiAltTextPopover-BjClNscQ.js → AiAltTextPopover-BiZHthAB.js} +1 -1
- package/dist/{AiAltTextReview-DeMdVbtT.js → AiAltTextReview-BwhROHiF.js} +1 -1
- package/dist/{AiRewriteMenu-BSzj1dKC.js → AiRewriteMenu-6b8GNj64.js} +4 -4
- package/dist/{BlockPreviewCanvas-D-If_vd_.js → BlockPreviewCanvas-BAYIy-QJ.js} +4 -4
- package/dist/{CloudPanels-DPeK_siQ.js → CloudPanels-Cb54vtYC.js} +1 -1
- package/dist/{CountdownToolbar-DBu2ZqC6.js → CountdownToolbar-CTbJPh8B.js} +4 -4
- package/dist/{IssuesPanel-BnUut-p-.js → IssuesPanel-BUKc8lld.js} +1 -1
- package/dist/{LanguageMenu-DfTxrbvp.js → LanguageMenu-DruJAMET.js} +3 -3
- package/dist/{LogicTagInsertButton-CJ1Jk6jv.js → LogicTagInsertButton-Ci7V0Exe.js} +3 -3
- package/dist/{MergeTagInput-CV-z85s9.js → MergeTagInput-BA89v7KJ.js} +1 -1
- package/dist/{MergeTagModeToggle-CixgX5C_.js → MergeTagModeToggle-De_FNmcG.js} +1 -1
- package/dist/{MergeTagTextarea-B1zOC_Nr.js → MergeTagTextarea-BRMB24Dg.js} +2 -2
- package/dist/{ParagraphEditor-C9UhWvRB.js → ParagraphEditor-DYqh0kEa.js} +8 -8
- package/dist/{RestoreVersionDialog-Do7fZWpT.js → RestoreVersionDialog-CRkyFafq.js} +1 -1
- package/dist/{RichTextEditorContent-wW_SMun2.js → RichTextEditorContent-WeCqqCy3.js} +2 -2
- package/dist/{SaveBlockDialog-CCHIUfR-.js → SaveBlockDialog-D992yyO4.js} +4 -4
- package/dist/{SavedBlocksBrowserModal-DtPHhfw9.js → SavedBlocksBrowserModal-tH74h2Tz.js} +4 -4
- package/dist/{SavedBlocksPanels-CYIby5pR.js → SavedBlocksPanels-BuzEwYfp.js} +1 -1
- package/dist/{SavedBlocksPickBar-CCwBugqN.js → SavedBlocksPickBar-DbULBPsI.js} +1 -1
- package/dist/{TemplateSettings-B8IVy5q9.js → TemplateSettings-eMBAy_wd.js} +4 -4
- package/dist/{TestEmailModal-CS5JoKRH.js → TestEmailModal-hb9iopaZ.js} +5 -5
- package/dist/{TestEmailPanel-sOIZfKzc.js → TestEmailPanel-DbeZjj0u.js} +1 -1
- package/dist/{TitleEditor-ZlBcq9_P.js → TitleEditor-CisDioGi.js} +4 -4
- package/dist/{Toolbar-c4_rLLJT.js → Toolbar-BUVRjylH.js} +9 -9
- package/dist/{TplModal-DnFFEulp.js → TplModal-BPPP-uM6.js} +1 -1
- package/dist/{VersionHistoryPanels-TdGaMaa_.js → VersionHistoryPanels-BNONrE-8.js} +1 -1
- package/dist/{WrapperBlock-BiW4ye3w.js → WrapperBlock-B3UAv5kv.js} +3 -3
- package/dist/{blockTypeIcons-D1aYMC1M.js → blockTypeIcons-BPPpqFc2.js} +1 -1
- package/dist/bundle-stats.json +5 -5
- package/dist/cdn/chunks/{AiAltTextPopover-CfGJNBOb.js → AiAltTextPopover-CafZSF50.js} +2 -2
- package/dist/cdn/chunks/{AiAltTextPopover-CfGJNBOb.js.map → AiAltTextPopover-CafZSF50.js.map} +1 -1
- package/dist/cdn/chunks/{AiAltTextReview-PKe31R_g.js → AiAltTextReview-BJcaqyp5.js} +2 -2
- package/dist/cdn/chunks/{AiAltTextReview-PKe31R_g.js.map → AiAltTextReview-BJcaqyp5.js.map} +1 -1
- package/dist/cdn/chunks/{AiRewriteMenu-ZDBwReuU.js → AiRewriteMenu-DFUZWA7e.js} +5 -5
- package/dist/cdn/chunks/{AiRewriteMenu-ZDBwReuU.js.map → AiRewriteMenu-DFUZWA7e.js.map} +1 -1
- package/dist/cdn/chunks/{BlockPreviewCanvas-D7U6nQ7t.js → BlockPreviewCanvas-D0VhkzY8.js} +5 -5
- package/dist/cdn/chunks/{BlockPreviewCanvas-D7U6nQ7t.js.map → BlockPreviewCanvas-D0VhkzY8.js.map} +1 -1
- package/dist/cdn/chunks/{CloudPanels-EXXNMLbs.js → CloudPanels-BiU1MD-4.js} +2 -2
- package/dist/cdn/chunks/{CloudPanels-EXXNMLbs.js.map → CloudPanels-BiU1MD-4.js.map} +1 -1
- package/dist/cdn/chunks/{CountdownToolbar-BN2_zvRj.js → CountdownToolbar-CH8UK01N.js} +5 -5
- package/dist/cdn/chunks/{CountdownToolbar-BN2_zvRj.js.map → CountdownToolbar-CH8UK01N.js.map} +1 -1
- package/dist/cdn/chunks/{IssuesPanel-BDwegn0s.js → IssuesPanel-3NPqHXJx.js} +3 -3
- package/dist/cdn/chunks/{IssuesPanel-BDwegn0s.js.map → IssuesPanel-3NPqHXJx.js.map} +1 -1
- package/dist/cdn/chunks/{LanguageMenu-DXq9cXUd.js → LanguageMenu-75uu4P2d.js} +4 -4
- package/dist/cdn/chunks/{LanguageMenu-DXq9cXUd.js.map → LanguageMenu-75uu4P2d.js.map} +1 -1
- package/dist/cdn/chunks/{LogicTagInsertButton-BEArlbra.js → LogicTagInsertButton-C5L73hYh.js} +4 -4
- package/dist/cdn/chunks/{LogicTagInsertButton-BEArlbra.js.map → LogicTagInsertButton-C5L73hYh.js.map} +1 -1
- package/dist/cdn/chunks/{MergeTagInput-B3SLXXzL.js → MergeTagInput-D8cbnnZu.js} +2 -2
- package/dist/cdn/chunks/{MergeTagInput-B3SLXXzL.js.map → MergeTagInput-D8cbnnZu.js.map} +1 -1
- package/dist/cdn/chunks/{MergeTagModeToggle-Dywp9ntA.js → MergeTagModeToggle-D-RhwBsO.js} +2 -2
- package/dist/cdn/chunks/{MergeTagModeToggle-Dywp9ntA.js.map → MergeTagModeToggle-D-RhwBsO.js.map} +1 -1
- package/dist/cdn/chunks/{MergeTagTextarea-B9TM7FgM.js → MergeTagTextarea-CAJIi2FE.js} +3 -3
- package/dist/cdn/chunks/{MergeTagTextarea-B9TM7FgM.js.map → MergeTagTextarea-CAJIi2FE.js.map} +1 -1
- package/dist/cdn/chunks/{ParagraphEditor-CVGtTYta.js → ParagraphEditor-sRPXZDzp.js} +9 -9
- package/dist/cdn/chunks/{ParagraphEditor-CVGtTYta.js.map → ParagraphEditor-sRPXZDzp.js.map} +1 -1
- package/dist/cdn/chunks/{RestoreVersionDialog-Dt_0qOOW.js → RestoreVersionDialog-CJK-14PX.js} +2 -2
- package/dist/cdn/chunks/{RestoreVersionDialog-Dt_0qOOW.js.map → RestoreVersionDialog-CJK-14PX.js.map} +1 -1
- package/dist/cdn/chunks/{RichTextEditorContent-BjN4mnzL.js → RichTextEditorContent-DU0wtA_j.js} +3 -3
- package/dist/cdn/chunks/{RichTextEditorContent-BjN4mnzL.js.map → RichTextEditorContent-DU0wtA_j.js.map} +1 -1
- package/dist/cdn/chunks/{SaveBlockDialog-D9eBjE99.js → SaveBlockDialog-C8hY9xA-.js} +5 -5
- package/dist/cdn/chunks/{SaveBlockDialog-D9eBjE99.js.map → SaveBlockDialog-C8hY9xA-.js.map} +1 -1
- package/dist/cdn/chunks/{SavedBlocksBrowserModal-ClsTpkdk.js → SavedBlocksBrowserModal-B3nFAgAa.js} +4 -4
- package/dist/cdn/chunks/{SavedBlocksBrowserModal-ClsTpkdk.js.map → SavedBlocksBrowserModal-B3nFAgAa.js.map} +1 -1
- package/dist/cdn/chunks/{SavedBlocksPanels-CxlNHhUs.js → SavedBlocksPanels-CQenugHO.js} +2 -2
- package/dist/cdn/chunks/{SavedBlocksPanels-CxlNHhUs.js.map → SavedBlocksPanels-CQenugHO.js.map} +1 -1
- package/dist/cdn/chunks/{SavedBlocksPickBar-C7_Z8phX.js → SavedBlocksPickBar-DzUP4IYv.js} +2 -2
- package/dist/cdn/chunks/{SavedBlocksPickBar-C7_Z8phX.js.map → SavedBlocksPickBar-DzUP4IYv.js.map} +1 -1
- package/dist/cdn/chunks/{TemplateSettings-B6zDtjSs.js → TemplateSettings-DnOwyN_1.js} +5 -5
- package/dist/cdn/chunks/{TemplateSettings-B6zDtjSs.js.map → TemplateSettings-DnOwyN_1.js.map} +1 -1
- package/dist/cdn/chunks/{TestEmailModal-CJ_QYFua.js → TestEmailModal-BFqmfOZ1.js} +6 -6
- package/dist/cdn/chunks/{TestEmailModal-CJ_QYFua.js.map → TestEmailModal-BFqmfOZ1.js.map} +1 -1
- package/dist/cdn/chunks/{TestEmailPanel-CsFrTq_a.js → TestEmailPanel-DFOhhaa9.js} +2 -2
- package/dist/cdn/chunks/{TestEmailPanel-CsFrTq_a.js.map → TestEmailPanel-DFOhhaa9.js.map} +1 -1
- package/dist/cdn/chunks/{TitleEditor-CuKJptyw.js → TitleEditor-ChPXTB9T.js} +4 -4
- package/dist/cdn/chunks/{TitleEditor-CuKJptyw.js.map → TitleEditor-ChPXTB9T.js.map} +1 -1
- package/dist/cdn/chunks/{Toolbar-TS2WwlPW.js → Toolbar-bbO5WoKo.js} +9 -9
- package/dist/cdn/chunks/{Toolbar-TS2WwlPW.js.map → Toolbar-bbO5WoKo.js.map} +1 -1
- package/dist/cdn/chunks/{TplModal-CsadClrH.js → TplModal-Bg97XHIJ.js} +2 -2
- package/dist/cdn/chunks/{TplModal-CsadClrH.js.map → TplModal-Bg97XHIJ.js.map} +1 -1
- package/dist/cdn/chunks/{VersionHistoryPanels-CieY91f0.js → VersionHistoryPanels-CyyRXWPU.js} +2 -2
- package/dist/cdn/chunks/{VersionHistoryPanels-CieY91f0.js.map → VersionHistoryPanels-CyyRXWPU.js.map} +1 -1
- package/dist/cdn/chunks/{WrapperBlock-DtnRuKWE.js → WrapperBlock-ZBCf7Y8u.js} +4 -4
- package/dist/cdn/chunks/{WrapperBlock-DtnRuKWE.js.map → WrapperBlock-ZBCf7Y8u.js.map} +1 -1
- package/dist/cdn/chunks/{composables-CUIiW9OD.js → composables-CMBZad02.js} +10 -10
- package/dist/cdn/chunks/{composables-CUIiW9OD.js.map → composables-CMBZad02.js.map} +1 -1
- package/dist/cdn/chunks/{createCloudRuntime-B7D04wKf.js → createCloudRuntime-BHGFjpek.js} +3 -3
- package/dist/cdn/chunks/{createCloudRuntime-B7D04wKf.js.map → createCloudRuntime-BHGFjpek.js.map} +1 -1
- package/dist/cdn/chunks/{extensions-Cbvk9i08.js → extensions-Beg0g2wm.js} +4 -4
- package/dist/cdn/chunks/{extensions-Cbvk9i08.js.map → extensions-Beg0g2wm.js.map} +1 -1
- package/dist/cdn/chunks/{normalizeMergeTagMarkup-BJ-MnCqF.js → normalizeMergeTagMarkup-B8yU4usU.js} +2 -2
- package/dist/cdn/chunks/{normalizeMergeTagMarkup-BJ-MnCqF.js.map → normalizeMergeTagMarkup-B8yU4usU.js.map} +1 -1
- package/dist/cdn/chunks/{preRenderCustomBlocks-D2wISRHq.js → preRenderCustomBlocks-CPHm2GOQ.js} +2 -2
- package/dist/cdn/chunks/{preRenderCustomBlocks-D2wISRHq.js.map → preRenderCustomBlocks-CPHm2GOQ.js.map} +1 -1
- package/dist/cdn/chunks/{sanitizeHtml-CB7fjHFs.js → sanitizeHtml-B7LC0gKK.js} +2 -2
- package/dist/cdn/chunks/{sanitizeHtml-CB7fjHFs.js.map → sanitizeHtml-B7LC0gKK.js.map} +1 -1
- package/dist/cdn/chunks/{socialIcons-C_yggK1_.js → socialIcons-D9D02_y5.js} +2 -2
- package/dist/cdn/chunks/{socialIcons-C_yggK1_.js.map → socialIcons-D9D02_y5.js.map} +1 -1
- package/dist/cdn/chunks/{src-Bp7bZcuD.js → src-BCrSqaj8.js} +2 -2
- package/dist/cdn/chunks/{src-Bp7bZcuD.js.map → src-BCrSqaj8.js.map} +1 -1
- package/dist/cdn/chunks/{src-D-URHI0Z.js → src-BO4aXl_Y.js} +3 -3
- package/dist/cdn/chunks/{src-D-URHI0Z.js.map → src-BO4aXl_Y.js.map} +1 -1
- package/dist/cdn/chunks/{src-CdVAke9t.js → src-DeywvttP.js} +547 -540
- package/dist/cdn/chunks/src-DeywvttP.js.map +1 -0
- package/dist/cdn/chunks/{useLocalizedDisplay-slFOCPrh.js → useLocalizedDisplay-oykFcYrW.js} +2 -2
- package/dist/cdn/chunks/{useLocalizedDisplay-slFOCPrh.js.map → useLocalizedDisplay-oykFcYrW.js.map} +1 -1
- package/dist/cdn/chunks/{useLogicTag-lPjCGeGC.js → useLogicTag-D_qg9qqO.js} +2 -2
- package/dist/cdn/chunks/{useLogicTag-lPjCGeGC.js.map → useLogicTag-D_qg9qqO.js.map} +1 -1
- package/dist/cdn/chunks/{useMergeTag-BKNBwIry.js → useMergeTag-VLnVHtxV.js} +2 -2
- package/dist/cdn/chunks/{useMergeTag-BKNBwIry.js.map → useMergeTag-VLnVHtxV.js.map} +1 -1
- package/dist/cdn/chunks/{withCurrentFont-CzTFFaJA.js → withCurrentFont-m6TtR0dC.js} +2 -2
- package/dist/cdn/chunks/{withCurrentFont-CzTFFaJA.js.map → withCurrentFont-m6TtR0dC.js.map} +1 -1
- package/dist/cdn/editor.js +17 -17
- package/dist/{composables-DbjgUQlV.js → composables-Cq7rsxRc.js} +8 -8
- package/dist/{createCloudRuntime-Cnh2M6iT.js → createCloudRuntime-CHsFF8DI.js} +2 -2
- package/dist/{dist-CAvsz9cW.js → dist-C0hVefGI.js} +343 -336
- package/dist/{extensions-7fb-XtNJ.js → extensions-BSXjPQEc.js} +3 -3
- package/dist/{normalizeMergeTagMarkup-GrXJfXsQ.js → normalizeMergeTagMarkup-CBLCQe02.js} +1 -1
- package/dist/{preRenderCustomBlocks-DuXtzD-F.js → preRenderCustomBlocks-e2OlY4aU.js} +1 -1
- package/dist/{sanitizeHtml-eV4_BpI6.js → sanitizeHtml-Dfn-fH17.js} +1 -1
- package/dist/{socialIcons-brRkK9Om.js → socialIcons-BZRLo0eT.js} +1 -1
- package/dist/templatical-editor.js +17 -17
- package/dist/{useLocalizedDisplay-DoaT7nWk.js → useLocalizedDisplay-B7tlQF4g.js} +1 -1
- package/dist/{useLogicTag-cTC2KbWd.js → useLogicTag-k_y-4o4W.js} +1 -1
- package/dist/{useMergeTag-D2YDZ8vR.js → useMergeTag-BiZ6XOdL.js} +1 -1
- package/dist/{withCurrentFont-DAmED4fN.js → withCurrentFont-CPhRujet.js} +1 -1
- package/package.json +7 -7
- package/dist/cdn/chunks/src-CdVAke9t.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-CdVAke9t.js","names":["isPlainObject","isRecord","json","SECTION_WRAPPER_IN_WRAPPER","blocksIn","isSection","columnsOf","candidate","BORDER_SIDES","uniformBorder","side","toBorderCss","toBorderDeclarations","border","css","value","declarations","index","BORDER_CORNERS","cornerPx","toBorderRadiusCss","radius","corners","corner","HEADING_LEVEL_FONT_SIZE","TITLE_LINE_HEIGHT","BUTTON_LINE_HEIGHT","RICH_TEXT_SPACING","BACKGROUND_SIZES","BACKGROUND_POSITIONS_X","BACKGROUND_POSITIONS_Y","createBackgroundImage","encodeCssUrl","out","char","url","code","resolveBackgroundImage","bg","size","position","x","y","HERO_VERTICAL_ALIGNS","resolveHero","hero","section","image","aspectRatio","imageAspectRatio","height","isFixedHeight","width","SOCIAL_ICON_GLYPHS","SOCIAL_ICON_TONE_COLORS","oneColorTone","tone","socialIconColors","known","platform","socialIconAssetDir","style","socialIconHalo","socialIconGlyphScale","elementIdIssues","issues","check","id","visit","blocks","block","where","path","item","j","icon","rowPath","row","cell","k","column","content","safeClone","ancestors","val","isPlainObject$1","deepEqual","a","b","keys","key","SdkError","message","statusCode","details","TRANSLATABLE_FIELDS","SETTINGS_TRANSLATABLE_FIELDS","isLocaleTag","isRecord$1","FORBIDDEN_SEGMENTS","isSafePath","segment","step","current","readPath","target","pruneLayers","result","locale","layer","kind","parent","pruneLocaleOrphans","children","child","i","isStructuralLocalePath","list","segments","elementPath","depth","before","ids","cells","pruneSettingsLocaleOrphans","settings","writePath","last","expand","head","rest","pattern","tail","next","translatableFields","definition","definitions","candidate","textKeys","field","values","localizableId","isTranslatablePath","blockType","want","have","sourceHash","hash","byte","withoutL10n","_l10n","orderedSetEntries","set","left","right","localizeBlock","applyBlockLocaleLayer","defaultLocale","json","view","text","localizeBlockOwnFields","own","isHidden","stripSettings","_locales","defaultLocaleOf","resolveLocale","fallback","options","project","localeCoverage","paths","texts","walk","localeHiddenBlocks","defaultLocaleGaps","gaps","collect","defaultLocaleGapPaths","rebaseDefaultLocale","previous","rebase","gapPaths","textPaths","layers","promoted","old","after","textPath","restoreSubtrees","roots","root","projected","entry","customTextFields","tag","SECTION_WRAPPER_IN_WRAPPER$1","createSetDefaultLocaleOperation","blocksIn$1","FORBIDDEN_CUSTOM_TEXT_FIELDS_KEYS","fail","CUSTOM_TEXT_FIELDS_ERROR","OperationError","opIndex","blockId","getColumnCount","layout","applyOperations","draft","applyOperationsInPlace","ops","context","engine","applyOne","op","IMMUTABLE_KEYS","SETTINGS_IMMUTABLE_KEYS","SETTINGS_LOCALE_IMMUTABLE_KEYS","isRecord","isSection$1","topLevelOf","columnsOf$1","walkLocations","locate","location","blockIdsOf","idsIn","readBlockId","readParent","readAfter","readExpect","expect","readChanges","unset","immutable","clash","assertNewBlock","placement","columns","heldByOthers","lock","assertUnlocked","held","assertUnlockedLocale","assertExpected","expected","container","found","insertionIndex","sibling","resizeColumns","count","removed","change","dottedElementIds","issue","assertElementIds","existing","raw","addBlock","moveBlock","deleteBlock","updateBlock","updateSettings","setContent","setDefaultLocale","addLocale","removeLocale","updateBlockLocale","updateSettingsLocale","seen","assertSlotPlacement","expectedParent","currentAfter","pruned","readLocale","requireLocale","locales","folded","localeLayer","l10n","readLocaleChanges","assertLocalePaths","changes","assertLocaleExpected","changeLocale","holdsSlot","hiddenInALanguage","hidesSlot","ancestor","hidden","ownLayers","columnsOf","positionOf","requirePosition","state","restoreKeys","restore","remove","layerOf","restoreLocale","restoreRemovedLayer","_unset","blocksIn","restorePrunedLayers","restores","invertOne","inverse","_hidden","invertOperations","inverses","error","defaultStatus","CollaborationConflict","isSection","isTitle","isParagraph","isImage","isButton","isDivider","isVideo","isSocialIcons","isSpacer","isHtml","isMenu","isTable","isCountdown","isCustomBlock","isSlot","isWrapper","TITLE_BLOCK_DEFAULTS","PARAGRAPH_BLOCK_DEFAULTS","IMAGE_BLOCK_DEFAULTS","BUTTON_BLOCK_DEFAULTS","DIVIDER_BLOCK_DEFAULTS","SECTION_BLOCK_DEFAULTS","VIDEO_BLOCK_DEFAULTS","SOCIAL_ICONS_BLOCK_DEFAULTS","SPACER_BLOCK_DEFAULTS","HTML_BLOCK_DEFAULTS","MENU_BLOCK_DEFAULTS","TABLE_BLOCK_DEFAULTS","COUNTDOWN_BLOCK_DEFAULTS","DEFAULT_BLOCK_DEFAULTS","DEFAULT_TEMPLATE_DEFAULTS","isPlainObject","deepMergeDefaults","base","overrides","baseVal","overrideVal","createDefaultTemplateContent","defaultFontFamily","templateDefaults","RTL_LANGUAGE_PRIMARY_SUBTAGS","isRtlLanguageTag","primary","resolveContentDirection","TRANSLATION_MAX_CHARS","QUOTES","findOpenTagEnd","quote","from","html","isWhitespace","findOpenSpanBoundary","isAttrNameChar","NAMED_ENTITIES","decodeHtmlEntities","ref","match","getTagAttrValue","name","attrs","nameStart","attrName","valueStart","valueEnd","convertMergeTagsToValues","rewriteMergeTagSpans","replaceMergeTagSpans","replace","scanMergeTagSpans","spans","markup","start","end","open","afterTagName","openEnd","nextSpan","findAttr","closeEnd","findSpanClose","wholeElement","close","cursor","closing","opening","boundary","SYNTAX_PRESETS","builtInPresetOf","preset","syntax","findCloserOnLine","closer","scanSyntaxMatches","regex","limit","opener","prefixSource","prefix","sticky","matches","afterPrefix","closeSearch","breakAt","scanCombinedSyntaxMatches","logic","logicPrefix","valueMatch","logicMatch","nextValue","nextLogic","declaredDelimiter","presetWithSource","getSyntaxTriggerChar","getSyntaxClosingChar","resolveSyntax","anchoredRegex","source","flags","isMergeTagValue","trimmed","getMergeTagLabel","mergeTags","p","resolveHtmlMergeTagLabels","rewriteSpanByAttr","getMergeTagSample","substituteHtmlMergeTagSamples","escapeTagText","hasMergeTagSamples","substituteTextMergeTagSamples","containsMergeTag","valueRegex","logicRegex","isLogicMergeTagValue","getLogicMergeTagKeyword","resolveHtmlLogicMergeTagLabels","closeStart","newLabel","relabel","TRANSLATABLE_HTML_FIELDS","attributeRanges","ranges","tags","attr","tagRanges","chips","format","attributes","chip","attributeIndex","builtin","kinds","nextMatches","regexes","cached","to","decodedTermText","decoded","offsets","literal","termPatterns","TERM_PATTERN_LIMIT","termPattern","terms","alternatives","term","termRanges","range","maskingRanges","maskedText","maskTags","unmaskTags","valid","self","paired","attribute","tokens","maskTranslation","used","claim","token","indexes","eligibleFields","fields","fieldTarget","type","localeStrings","coverage","selected","strings","masked","applyLocaleStrings","items","grouped","settingsText","rejected","separator","targets","operations","createCustomBlockLiquid","module","applyDefaults","ownBase","partial","copyDefaults","defaults","generateId","createDefaultSpacing","createDefaultStyles","padding","createTitleBlock","createParagraphBlock","createImageBlock","createButtonBlock","createDividerBlock","createSectionBlock","createVideoBlock","createSocialIconsBlock","createSpacerBlock","createHtmlBlock","createMenuBlock","createDefaultTableRows","rows","createTableBlock","createCountdownBlock","getFieldDefault","createCustomBlock","fieldValues","styles","createSlotBlock","createWrapperBlock","createBlock","blockDefaults","remapL10n","rename","parentPath","renamed","entries","v","cloneBlock","cloned","remint","oldId","element","scoped","oldRowId","c","EXACTLY_ONE_SLOT","SLOT_NESTED_IN_SECTION","WRAPPER_IN_WRAPPER","NESTED_MJ_WRAPPER","SLOT_IN_CONTENT","SECTION_WRAPPER_IN_WRAPPER","WRAPPER_IN_CONTENT","walkBlocks","insideSection","insideWrapper","validateLayout","slotCount","assertNoSlotInContent","assertNoWrapperInContent","layoutWrapsSlot","wrapped","cloneLayoutBlock","findSlotLocation","nested","emitsMjWrapper","applyLayout","SAFE_LINK_SCHEMES","DANGEROUS_SCRIPT_SCHEMES","normalizeUrlForSchemeCheck","extractUrlScheme","DATA_IMAGE_SRC_PATTERN","HTML_URL_ATTRIBUTES","HTML_FORBIDDEN_ATTRIBUTES","isSafeHtmlUrl","normalized","scheme","safe","PARAGRAPH_TAG","EMPTY_PARAGRAPH","isBlankRichText","fillEmptyParagraphs","BUILT_IN_FONT_STACKS","CSS_WIDE_KEYWORDS","GENERIC_FAMILIES","isSpace","parseFontFamilies","families","closed","comma","quoteFontFamily","isGenericFontFamily","family","firstFontFamily","resolveFontStack","withFallback","font","fonts","bareName","namedFont","customFont","isRenderableTemplateContent"],"sources":["../../../../types/src/blocks.ts","../../../../types/src/background-image.ts","../../../../types/src/hero.ts","../../../../types/src/social.ts","../../../../types/src/element-ids.ts","../../../../types/src/clone.ts","../../../../types/src/deep-equal.ts","../../../../types/src/config.ts","../../../../types/src/localization.ts","../../../../types/src/operations.ts","../../../../types/src/invert-operations.ts","../../../../types/src/collaboration.ts","../../../../types/src/guards.ts","../../../../types/src/defaults.ts","../../../../types/src/template.ts","../../../../types/src/direction.ts","../../../../types/src/translation.ts","../../../../types/src/html-scan.ts","../../../../types/src/merge-tag-html.ts","../../../../types/src/merge-tags.ts","../../../../types/src/locale-strings.ts","../../../../types/src/custom-block-liquid.ts","../../../../types/src/factory.ts","../../../../types/src/layout.ts","../../../../types/src/url-policy.ts","../../../../types/src/rich-text.ts","../../../../types/src/fonts.ts","../../../../types/src/preview-resolution.ts"],"sourcesContent":["import type { BackgroundImage } from \"./background-image\";\nimport type { SectionHero } from \"./hero\";\nimport type { BlockLocaleLayer } from \"./localization\";\n\nexport interface SpacingValue {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\nexport interface BlockStyles {\n padding: SpacingValue;\n backgroundColor?: string;\n}\n\nexport type BorderStyle = \"solid\" | \"dashed\" | \"dotted\";\n\nexport type BorderSide = \"top\" | \"right\" | \"bottom\" | \"left\";\n\nexport const BORDER_SIDES: readonly BorderSide[] = [\n \"top\",\n \"right\",\n \"bottom\",\n \"left\",\n];\n\n/** One side of a border. A width of `0` leaves that side undrawn. */\nexport interface BorderSideValue {\n /** Width in px. `0` means no border on this side. */\n width: number;\n style: BorderStyle;\n color: string;\n}\n\n/**\n * A border described per side, like `SpacingValue`. Only elements MJML can\n * border natively carry one: sections, images and buttons.\n */\nexport interface BorderValue {\n top: BorderSideValue;\n right: BorderSideValue;\n bottom: BorderSideValue;\n left: BorderSideValue;\n}\n\n/** The same side value on all four sides. */\nexport function uniformBorder(side: BorderSideValue): BorderValue {\n return {\n top: { ...side },\n right: { ...side },\n bottom: { ...side },\n left: { ...side },\n };\n}\n\n/**\n * Convert one side of a border to a CSS `border` value like\n * `\"1px solid #cccccc\"`. Returns `null` when the side is absent or its width is\n * not a positive number, so callers emit nothing rather than a `0px` border.\n */\nexport function toBorderCss(side: BorderSideValue | undefined): string | null {\n if (\n !side ||\n typeof side.width !== \"number\" ||\n !Number.isFinite(side.width) ||\n side.width <= 0\n ) {\n return null;\n }\n\n return `${side.width}px ${side.style} ${side.color}`;\n}\n\n/**\n * Resolve a border to the CSS declarations that draw it, keyed by kebab-case\n * property: one `border` when all four sides are drawn identically, otherwise\n * one `border-<side>` per drawn side. Empty when there is nothing to draw.\n *\n * The keys double as MJML attribute names (`mj-section`, `mj-image` and\n * `mj-button` accept `border` and every `border-<side>`), so the renderer and\n * the editor canvas both go through this and can't disagree about a border.\n */\nexport function toBorderDeclarations(\n border: BorderValue | undefined,\n): Partial<Record<\"border\" | `border-${BorderSide}`, string>> {\n if (!border) {\n return {};\n }\n\n const css = BORDER_SIDES.map((side) => toBorderCss(border[side]));\n if (css[0] !== null && css.every((value) => value === css[0])) {\n return { border: css[0] };\n }\n\n const declarations: Partial<Record<`border-${BorderSide}`, string>> = {};\n BORDER_SIDES.forEach((side, index) => {\n const value = css[index];\n if (value !== null) {\n declarations[`border-${side}`] = value;\n }\n });\n return declarations;\n}\n\nexport type BorderCorner =\n \"topLeft\" | \"topRight\" | \"bottomRight\" | \"bottomLeft\";\n\n/** In CSS shorthand order: top-left, top-right, bottom-right, bottom-left. */\nexport const BORDER_CORNERS: readonly BorderCorner[] = [\n \"topLeft\",\n \"topRight\",\n \"bottomRight\",\n \"bottomLeft\",\n];\n\n/** A radius per corner, in px. */\nexport type CornerRadius = Record<BorderCorner, number>;\n\n/**\n * A corner radius in px: one number for all four corners, or a radius per\n * corner.\n */\nexport type BorderRadiusValue = number | CornerRadius;\n\nfunction cornerPx(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0\n ? value\n : 0;\n}\n\n/**\n * Convert a corner radius to a CSS `border-radius` value: `\"8px\"` when all\n * corners match, otherwise the four-value shorthand `\"8px 8px 0px 0px\"`\n * (top-left, top-right, bottom-right, bottom-left). Returns `null` when every\n * corner is square, so callers emit nothing.\n *\n * A non-finite or negative corner counts as square — hand-authored JSON is the\n * only way to produce one, and the export must not carry it.\n */\nexport function toBorderRadiusCss(\n radius: BorderRadiusValue | undefined,\n): string | null {\n if (radius === undefined || radius === null) {\n return null;\n }\n\n const corners =\n typeof radius === \"number\"\n ? BORDER_CORNERS.map(() => cornerPx(radius))\n : BORDER_CORNERS.map((corner) => cornerPx(radius[corner]));\n\n if (corners.every((value) => value === 0)) {\n return null;\n }\n if (corners.every((value) => value === corners[0])) {\n return `${corners[0]}px`;\n }\n return corners.map((value) => `${value}px`).join(\" \");\n}\n\nexport interface BlockVisibility {\n desktop: boolean;\n mobile: boolean;\n}\n\n/**\n * A display condition wraps a block in host-owned before/after markup so the\n * block renders only when the condition holds.\n */\nexport interface DisplayCondition {\n label: string;\n before: string;\n after: string;\n group?: string;\n description?: string;\n /**\n * Opaque host state. The editor stores it and hands it back as `current`\n * when the host builder reopens, and never reads it. It must survive\n * `JSON.stringify` — content is cloned with `safeClone`, so values that\n * JSON drops (functions, `undefined` keys, a `Date` becoming an ISO string)\n * do not round-trip.\n */\n data?: unknown;\n}\n\nexport interface BaseBlock {\n /** Per-language layers, keyed by BCP 47 tag; see `resolveLocale`. */\n l10n?: Record<string, BlockLocaleLayer>;\n id: string;\n type: string;\n styles: BlockStyles;\n visibility?: BlockVisibility;\n displayCondition?: DisplayCondition;\n}\n\nexport type ColumnLayout =\n \"1\" | \"2\" | \"3\" | \"4\" | \"2-1\" | \"1-2\" | \"3-1\" | \"1-3\" | \"1-2-1\";\n\n/**\n * Optional outer frame for a section. When present, the section is rendered\n * inside an `mj-wrapper` — a band (its own background + padding) that frames\n * the section, e.g. a white card sitting on a colored band. The band is as\n * wide as the email body (`settings.width`), not the recipient's viewport,\n * unless `fullWidth` is set.\n */\nexport interface SectionWrapper {\n backgroundColor?: string;\n padding?: SpacingValue;\n /**\n * Corner radius in px for the outer frame — one number, or a radius per\n * corner. Omitted/0 = square corners. Ignored while `fullWidth` is on: a\n * viewport-wide band has no visible corners, so the renderer omits\n * `border-radius`.\n */\n borderRadius?: BorderRadiusValue;\n /** Image behind the band; `backgroundColor` is its fallback. */\n backgroundImage?: BackgroundImage;\n /**\n * When true, the band spans the recipient's viewport (`full-width` on\n * `mj-wrapper`) while the section stays at the email width. Absent or\n * false keeps the band at `settings.width`.\n */\n fullWidth?: boolean;\n}\n\nexport interface SectionBlock extends BaseBlock {\n type: \"section\";\n columns: ColumnLayout;\n children: Block[][];\n /**\n * Whether columns stack vertically on mobile. Absent or `true` keeps MJML's\n * default responsive behavior (columns stack below 480px). `false` renders\n * the columns inside an `<mj-group>` so they stay side-by-side on mobile,\n * proportionally shrunk to fit.\n */\n stackOnMobile?: boolean;\n /**\n * Corner radius in px — one number, or a radius per corner. Omitted/0 =\n * square corners.\n */\n borderRadius?: BorderRadiusValue;\n /**\n * Border around the section box, per side. Omitted = no border; a side with\n * width 0 is not drawn.\n */\n border?: BorderValue;\n /**\n * Image behind the section's columns, rendered as `background-url` (plus\n * size, position and repeat) on the `mj-section`. `styles.backgroundColor`\n * is its fallback.\n */\n backgroundImage?: BackgroundImage;\n /**\n * Draws a one-column section with a background image as an `mj-hero`: the\n * image fills the box and the content sits on top. Ignored (the section\n * renders as a regular one, and the `structure` linter says why) with more\n * than one column, without an image, or with `height: \"image\"` and no\n * image size.\n */\n hero?: SectionHero;\n /** Optional outer frame (rendered as an `mj-wrapper` around the section). */\n wrapper?: SectionWrapper;\n}\n\nexport type HeadingLevel = 1 | 2 | 3 | 4;\n\nexport const HEADING_LEVEL_FONT_SIZE: Record<HeadingLevel, number> = {\n 1: 36,\n 2: 28,\n 3: 22,\n 4: 18,\n};\n\n/**\n * A title block's line height, as a multiple of its font size.\n *\n * The renderer writes it onto the title's `mj-text`, and the editor sets it on\n * the canvas title in both view and edit mode, so a title is the same height\n * in all three places. A literal in any one of them drifts silently: a\n * multi-line title then reads shorter on the canvas than in the inbox.\n */\nexport const TITLE_LINE_HEIGHT = 1.3;\n\n/**\n * A button label's line box as a ratio of its font size. The renderer emits\n * it and the canvas draws it, matching MJML's `mj-button` default so compiled\n * HTML stays unchanged.\n */\nexport const BUTTON_LINE_HEIGHT = 1.2;\n\n/**\n * A title block's font weight.\n *\n * The renderer writes it onto the exported heading, and the editor sets it on\n * the canvas title in both view and edit mode. The edit surface is a `<p>`, so\n * without it a title drops from bold to regular as editing starts, and a host\n * or client that resets heading styles would show the email's titles regular.\n */\nexport const TITLE_FONT_WEIGHT = 700;\n\n/**\n * Spacing (px) for the HTML a rich-text block stores — the `<p>`, `<ul>`,\n * `<ol>` and `<li>` elements TipTap produces.\n *\n * The editor canvas and the exported email must agree on these to the pixel,\n * so this is the one place they are stated. `@templatical/renderer` reads them\n * to build the global rule it emits; the editor's canvas CSS restates them as\n * literals (CSS cannot import a constant) and a parity test holds the two\n * together.\n *\n * Fixed px, never a `rem`- or base-size-derived scale: an email body is a\n * fixed-width document, so content spacing must not move when a consumer\n * scales the editor chrome.\n */\nexport const RICH_TEXT_SPACING = {\n /** Gap below every `<p>` except the last — the space between paragraphs. */\n paragraphGap: 8,\n /** Vertical margin on `<ul>` / `<ol>`. */\n listMarginY: 8,\n /** Left padding on `<ul>` / `<ol>` — the bullet indent. */\n listPaddingLeft: 24,\n /** Vertical margin on `<li>`. */\n listItemMarginY: 4,\n} as const;\n\nexport interface TitleBlock extends BaseBlock {\n type: \"title\";\n content: string;\n level: HeadingLevel;\n /** Text color. Unset = inherit the document-level `textColor`. */\n color?: string;\n textAlign: \"left\" | \"center\" | \"right\";\n fontFamily?: string;\n}\n\nexport interface ParagraphBlock extends BaseBlock {\n type: \"paragraph\";\n content: string;\n /**\n * Gap in px between this block's paragraphs — the space below every `<p>`\n * except the last. Absent means `RICH_TEXT_SPACING.paragraphGap`.\n *\n * Only affects a block holding more than one paragraph; a single `<p>` has no\n * internal gap, and the space around the block is `styles.padding`.\n *\n * `0` is a valid choice (paragraphs butted together) and is distinct from the\n * field being absent, so readers must test for `undefined` rather than\n * falsiness.\n */\n paragraphSpacing?: number;\n}\n\nexport interface ImageBlock extends BaseBlock {\n type: \"image\";\n src: string;\n alt: string;\n width: number | \"full\";\n /**\n * Height in pixels. Absent means the height is derived from the width, so the\n * image keeps its aspect ratio — setting both stretches it, since email\n * clients don't support `object-fit`.\n */\n height?: number;\n /**\n * The image file's own size in px, when known: given by the media library,\n * read by an importer, or measured in the editor during an edit. Both or\n * neither; one without the other reads as unknown. It drives the editor's\n * aspect-ratio lock and is never rendered. Cleared when `src` changes\n * without a new size alongside it.\n */\n naturalWidth?: number;\n naturalHeight?: number;\n align: \"left\" | \"center\" | \"right\";\n /**\n * Corner radius in px. Omitted/0 = square corners. A radius of at least half\n * the rendered size rounds a square image to a circle, which is how avatar\n * and portrait layouts are built. A radius per corner is also accepted.\n */\n borderRadius?: BorderRadiusValue;\n /**\n * Border around the image itself, per side. Omitted = no border; a side with\n * width 0 is not drawn.\n */\n border?: BorderValue;\n linkUrl?: string;\n linkOpenInNewTab?: boolean;\n placeholderUrl?: string;\n decorative?: boolean;\n /**\n * Whether the image fills its column on a phone (`mj-image`\n * `fluid-on-mobile`). Omitted keeps the automatic rule: fluid only when the\n * image fills its column on desktop. `true` always emits the attribute;\n * `false` never does. Video thumbnails have no equivalent and stay on the\n * automatic rule.\n */\n fluidOnMobile?: boolean;\n}\n\nexport interface ButtonBlock extends BaseBlock {\n type: \"button\";\n text: string;\n url: string;\n openInNewTab?: boolean;\n backgroundColor: string;\n textColor: string;\n /** Corner radius in px — one number, or a radius per corner. */\n borderRadius: BorderRadiusValue;\n /**\n * Border around the button itself, per side. Omitted = no border; a side\n * with width 0 is not drawn. For an outline (\"ghost\") button, set\n * `backgroundColor` to the keyword `\"transparent\"` (the background control\n * stores it) and set `textColor` too — a new button is `#333333` with white\n * text. An empty fill exports as `transparent`, because MJML paints\n * `#414141` when the attribute is omitted.\n */\n border?: BorderValue;\n fontSize: number;\n buttonPadding: SpacingValue;\n fontFamily?: string;\n /**\n * Label weight. `\"regular\"` is 400, `\"medium\"` is 500 and `\"bold\"` is 700.\n * Omitted renders bold, which is what a button with no weight renders.\n */\n fontWeight?: \"regular\" | \"medium\" | \"bold\";\n width?: number | \"full\";\n /**\n * Placement of the button within its column. No visible effect when `width`\n * is `\"full\"`, since the button then spans the column.\n */\n align: \"left\" | \"center\" | \"right\";\n}\n\n/**\n * A share of the column, from `\"0%\"` to `\"100%\"`.\n * @pattern ^(?:100(?:\\.0+)?|\\d{1,2}(?:\\.\\d+)?)%$\n */\nexport type DividerPercentWidth = `${number}%`;\n\nexport interface DividerBlock extends BaseBlock {\n type: \"divider\";\n lineStyle: \"solid\" | \"dashed\" | \"dotted\";\n color: string;\n thickness: number;\n /**\n * `\"full\"` spans the column and a number is pixels. A percentage is a share\n * of the column: MJML renders it natively, and it shrinks with the column on\n * a phone where a pixel width would overflow.\n */\n width: number | \"full\" | DividerPercentWidth;\n}\n\nexport interface VideoBlock extends BaseBlock {\n type: \"video\";\n url: string;\n openInNewTab?: boolean;\n thumbnailUrl: string;\n alt: string;\n width: number | \"full\";\n /**\n * Height in pixels for the thumbnail. Absent means the height is derived from\n * the width, so the thumbnail keeps its aspect ratio — setting both stretches\n * it, since email clients don't support `object-fit`.\n */\n height?: number;\n align: \"left\" | \"center\" | \"right\";\n placeholderUrl?: string;\n}\n\nexport type SocialPlatform =\n | \"facebook\"\n | \"twitter\"\n | \"instagram\"\n | \"linkedin\"\n | \"xing\"\n | \"youtube\"\n | \"tiktok\"\n | \"pinterest\"\n | \"email\"\n | \"whatsapp\"\n | \"telegram\"\n | \"discord\"\n | \"snapchat\"\n | \"reddit\"\n | \"github\"\n | \"dribbble\"\n | \"behance\"\n | \"website\";\n\n/**\n * The icon's shape. `plain` is the glyph alone, with no badge or outline.\n */\nexport type SocialIconStyle =\n \"solid\" | \"outlined\" | \"rounded\" | \"square\" | \"circle\" | \"plain\";\n\n/**\n * The colors an icon is drawn in: each platform's own brand color, or one\n * tone (dark or light) for every icon.\n */\nexport type SocialIconTone = \"brand\" | \"dark\" | \"light\";\n\nexport type SocialIconSize = \"small\" | \"medium\" | \"large\";\n\nexport interface SocialIcon {\n id: string;\n platform: SocialPlatform;\n url: string;\n}\n\nexport interface SocialIconsBlock extends BaseBlock {\n type: \"social\";\n icons: SocialIcon[];\n iconStyle: SocialIconStyle;\n /** Absent means `\"brand\"`. */\n iconTone?: SocialIconTone;\n iconSize: SocialIconSize;\n spacing: number;\n align: \"left\" | \"center\" | \"right\";\n}\n\nexport interface SpacerBlock extends BaseBlock {\n type: \"spacer\";\n height: number;\n}\n\nexport interface HtmlBlock extends BaseBlock {\n type: \"html\";\n content: string;\n}\n\nexport interface MenuItemData {\n id: string;\n text: string;\n url: string;\n openInNewTab: boolean;\n bold: boolean;\n underline: boolean;\n color?: string;\n}\n\nexport interface MenuBlock extends BaseBlock {\n type: \"menu\";\n items: MenuItemData[];\n fontSize: number;\n fontFamily?: string;\n /** Base text/link color. Unset = inherit the document-level `textColor`. */\n color?: string;\n linkColor?: string;\n textAlign: \"left\" | \"center\" | \"right\";\n separator: string;\n separatorColor: string;\n spacing: number;\n}\n\nexport interface TableCellData {\n id: string;\n content: string;\n}\n\nexport interface TableRowData {\n id: string;\n cells: TableCellData[];\n}\n\nexport interface TableBlock extends BaseBlock {\n type: \"table\";\n rows: TableRowData[];\n hasHeaderRow: boolean;\n headerBackgroundColor?: string;\n borderColor: string;\n borderWidth: number;\n cellPadding: number;\n fontSize: number;\n fontFamily?: string;\n /** Text color. Unset = inherit the document-level `textColor`. */\n color?: string;\n textAlign: \"left\" | \"center\" | \"right\";\n}\n\nexport interface CountdownBlock extends BaseBlock {\n type: \"countdown\";\n targetDate: string;\n timezone: string;\n showDays: boolean;\n showHours: boolean;\n showMinutes: boolean;\n showSeconds: boolean;\n separator: \":\" | \"-\" | \" \";\n digitFontSize: number;\n digitColor: string;\n labelColor: string;\n labelFontSize: number;\n backgroundColor: string;\n fontFamily?: string;\n labelDays: string;\n labelHours: string;\n labelMinutes: string;\n labelSeconds: string;\n expiredMessage: string;\n expiredImageUrl: string;\n hideOnExpiry: boolean;\n}\n\nexport interface CustomBlock extends BaseBlock {\n type: \"custom\";\n customType: string;\n fieldValues: Record<string, unknown>;\n renderedHtml?: string;\n /**\n * The definition's `stylesheet`, copied in when `renderedHtml` is written.\n * A render provider's backend, and Cloud rendering from storage, have no\n * definition to ask, so `@templatical/renderer` emits this when no\n * `getCustomBlockStylesheet` resolver is passed. A resolver, when passed,\n * decides every type, so a stale copy never overrides a live definition.\n */\n renderedStylesheet?: string;\n dataSourceFetched?: boolean;\n}\n\n/**\n * Layout-only hole where authored content is spliced in. Extends BaseBlock so\n * Block walkers stay typed (`styles` unused; spliced out before render).\n */\nexport interface SlotBlock extends BaseBlock {\n type: \"slot\";\n}\n\n/**\n * Layout-only band rendered as `mj-wrapper`. The block is the band:\n * `styles.backgroundColor` / `styles.padding` / `borderRadius` /\n * `backgroundImage` map to the wrapper. `fullWidth` spans the recipient's\n * viewport; absent or false keeps the band at the email width. A corner\n * radius is ignored while `fullWidth` is on. Legal in layout only.\n */\nexport interface WrapperBlock extends BaseBlock {\n type: \"wrapper\";\n children: Block[];\n /**\n * Corner radius in px. Ignored while `fullWidth` is on: a viewport-wide\n * band has no visible corners, so the renderer omits `border-radius`.\n */\n borderRadius?: number;\n /** Image behind the band; `styles.backgroundColor` is its fallback. */\n backgroundImage?: BackgroundImage;\n /**\n * When true, the band spans the recipient's viewport (`full-width` on\n * `mj-wrapper`) while its children stay at the email width. Absent or\n * false keeps the band at that width.\n */\n fullWidth?: boolean;\n}\n\nexport type Block =\n | SectionBlock\n | TitleBlock\n | ParagraphBlock\n | ImageBlock\n | ButtonBlock\n | DividerBlock\n | VideoBlock\n | SocialIconsBlock\n | SpacerBlock\n | HtmlBlock\n | MenuBlock\n | TableBlock\n | CountdownBlock\n | CustomBlock\n | SlotBlock\n | WrapperBlock;\n\nexport type BlockType = Block[\"type\"];\n","/**\n * `background-size` keywords. In Outlook on Windows (VML), `cover` and\n * `contain` draw a single frame when `repeat` is off and tile when it is on;\n * `auto` always tiles from the top center, whatever `position` and `repeat`\n * say.\n */\nexport type BackgroundSize = \"cover\" | \"contain\" | \"auto\";\n\nexport type BackgroundPositionX = \"left\" | \"center\" | \"right\";\n\nexport type BackgroundPositionY = \"top\" | \"center\" | \"bottom\";\n\n/**\n * An image painted behind a section or a wrapper band. The element's own\n * `backgroundColor` is its fallback: it shows while the image loads, with\n * images off, and in clients without background-image support.\n */\nexport interface BackgroundImage {\n url: string;\n size: BackgroundSize;\n position: { x: BackgroundPositionX; y: BackgroundPositionY };\n /** `false` paints the image once; `true` tiles it. */\n repeat: boolean;\n /**\n * The image file's own width in px, when known: given by the media library,\n * measured by the editor when the author sets the URL, or read by an\n * importer (from MJML, the hero's `background-width`, which may be the box's\n * size rather than the file's). Only the ratio with `naturalHeight` is used:\n * a section hero with `height: \"image\"` keeps its box at that shape. Both or\n * neither; one without the other reads as unknown.\n */\n naturalWidth?: number;\n /**\n * The image file's own height in px, when known; it pairs with\n * `naturalWidth`, and only their ratio is used. Both or neither.\n */\n naturalHeight?: number;\n}\n\n/**\n * A background image resolved to the values the renderer emits as MJML\n * attributes and the editor canvas applies as CSS, so the two can't disagree.\n */\nexport interface ResolvedBackgroundImage {\n /** Trimmed, with `encodeCssUrl` applied. */\n url: string;\n size: BackgroundSize;\n /** `background-position`, x first: `\"center top\"`. */\n position: string;\n repeat: \"repeat\" | \"no-repeat\";\n}\n\nexport const BACKGROUND_SIZES: readonly BackgroundSize[] = [\n \"cover\",\n \"contain\",\n \"auto\",\n];\n\nexport const BACKGROUND_POSITIONS_X: readonly BackgroundPositionX[] = [\n \"left\",\n \"center\",\n \"right\",\n];\n\nexport const BACKGROUND_POSITIONS_Y: readonly BackgroundPositionY[] = [\n \"top\",\n \"center\",\n \"bottom\",\n];\n\n/** A newly set image: one banner-sized picture, centered, not tiled. */\nexport function createBackgroundImage(url: string): BackgroundImage {\n return {\n url,\n size: \"cover\",\n position: { x: \"center\", y: \"center\" },\n repeat: false,\n };\n}\n\n/**\n * Percent-encode the characters that can end a quoted CSS `url()` string —\n * `'`, `\"`, `\\` and control characters (line breaks included). MJML pastes\n * `background-url` verbatim into `url('…')`, and an HTML entity like `'`\n * is decoded before the CSS is parsed, so entity escaping alone lets a URL\n * close the string. Spaces and parentheses are legal inside a quoted string\n * and are kept, which leaves merge tags such as `{{ hero_url }}` intact.\n */\nexport function encodeCssUrl(url: string): string {\n let out = \"\";\n for (const char of url) {\n const code = char.charCodeAt(0);\n const unsafe =\n code < 0x20 ||\n code === 0x7f ||\n char === \"'\" ||\n char === '\"' ||\n char === \"\\\\\";\n out += unsafe\n ? `%${code.toString(16).toUpperCase().padStart(2, \"0\")}`\n : char;\n }\n return out;\n}\n\n/**\n * Resolve a background image for output. `null` when there is no usable URL.\n * Size and position are checked against their keyword lists — a value from\n * tampered JSON falls back to `cover` / `center` instead of reaching MJML,\n * which copies these attributes into inline CSS.\n */\nexport function resolveBackgroundImage(\n bg: BackgroundImage | undefined,\n): ResolvedBackgroundImage | null {\n const url = typeof bg?.url === \"string\" ? bg.url.trim() : \"\";\n if (!bg || !url) {\n return null;\n }\n\n const size = BACKGROUND_SIZES.includes(bg.size) ? bg.size : \"cover\";\n const position = bg.position;\n const x =\n position && BACKGROUND_POSITIONS_X.includes(position.x)\n ? position.x\n : \"center\";\n const y =\n position && BACKGROUND_POSITIONS_Y.includes(position.y)\n ? position.y\n : \"center\";\n\n return {\n url: encodeCssUrl(url),\n size,\n position: `${x} ${y}`,\n repeat: bg.repeat ? \"repeat\" : \"no-repeat\",\n };\n}\n","import {\n resolveBackgroundImage,\n type BackgroundImage,\n type ResolvedBackgroundImage,\n} from \"./background-image\";\n\n/** Where a hero's content sits in its box. */\nexport type HeroVerticalAlign = \"top\" | \"middle\" | \"bottom\";\n\nexport const HERO_VERTICAL_ALIGNS: readonly HeroVerticalAlign[] = [\n \"top\",\n \"middle\",\n \"bottom\",\n];\n\n/**\n * Draws a one-column section as an MJML `mj-hero`: its background image\n * fills the box (always `cover`, never tiled) and the content sits on top of\n * it. A hero applies only to a one-column section with a background image;\n * otherwise the section renders as a regular one.\n */\nexport interface SectionHero {\n /**\n * `\"image\"` makes the box as tall as the image drawn across its desktop\n * width, and needs the image's size on `backgroundImage.naturalWidth` /\n * `naturalHeight`; a phone keeps that height and crops the image's sides.\n * A number is the box's fixed height in px, padding included.\n */\n height: \"image\" | number;\n verticalAlign: HeroVerticalAlign;\n}\n\n/** Why a section with `hero` set renders as a regular section. */\nexport type HeroNotAppliedReason = \"columns\" | \"image\" | \"size\";\n\n/** A hero that renders, resolved to the values the renderer and canvas use. */\nexport interface AppliedHero {\n applied: true;\n /** The section's background image, as `resolveBackgroundImage` resolves it. */\n image: ResolvedBackgroundImage;\n /** A fixed height in px (rounded), or `\"image\"`. */\n height: \"image\" | number;\n verticalAlign: HeroVerticalAlign;\n /**\n * The image's height ÷ width; `null` when its size is unknown, which only\n * a fixed height allows.\n */\n aspectRatio: number | null;\n}\n\nexport type ResolvedHero =\n AppliedHero | { applied: false; reason: HeroNotAppliedReason };\n\n/** The section fields hero mode reads. */\nexport interface HeroCandidate {\n columns: string;\n hero?: SectionHero;\n backgroundImage?: BackgroundImage;\n}\n\n/**\n * Whether a section renders as a hero, and with what; `null` when `hero` is\n * unset. The renderer, the quality linter and the editor all decide through\n * this, so the email, the warning and the canvas agree. Checked in order:\n * one column, a usable background image, then — for `height: \"image\"` — the\n * image's size. Values from tampered JSON fall back instead of reaching MJML:\n * a height that isn't a finite number of at least 1 reads as `\"image\"`, an\n * unknown `verticalAlign` as `\"middle\"`.\n */\nexport function resolveHero(section: HeroCandidate): ResolvedHero | null {\n const hero = section.hero;\n if (!hero || typeof hero !== \"object\") return null;\n if (section.columns !== \"1\") return { applied: false, reason: \"columns\" };\n\n const image = resolveBackgroundImage(section.backgroundImage);\n if (image === null) return { applied: false, reason: \"image\" };\n\n const aspectRatio = imageAspectRatio(section.backgroundImage);\n const height = isFixedHeight(hero.height) ? Math.round(hero.height) : \"image\";\n if (height === \"image\" && aspectRatio === null) {\n return { applied: false, reason: \"size\" };\n }\n\n const verticalAlign = HERO_VERTICAL_ALIGNS.includes(hero.verticalAlign)\n ? hero.verticalAlign\n : \"middle\";\n return { applied: true, image, height, verticalAlign, aspectRatio };\n}\n\nfunction isFixedHeight(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 1;\n}\n\n/**\n * A background image's height ÷ width, or `null` unless both are positive,\n * finite numbers.\n */\nexport function imageAspectRatio(\n bg: BackgroundImage | undefined,\n): number | null {\n const width = bg?.naturalWidth;\n const height = bg?.naturalHeight;\n if (typeof width !== \"number\" || typeof height !== \"number\") return null;\n if (!Number.isFinite(width) || !Number.isFinite(height)) return null;\n if (width <= 0 || height <= 0) return null;\n return height / width;\n}\n","import type { SocialIconTone, SocialIconStyle, SocialPlatform } from \"./blocks\";\n\n/**\n * SVG glyph (24×24 path) + brand color for each social platform.\n *\n * Single source of truth shared by two consumers that render icons in\n * different formats: the editor draws them as inline SVG (`SocialIconSvg.vue`)\n * and `@templatical/renderer` rasterizes them to PNGs\n * (`scripts/rasterize-social.mjs`) because Outlook's Word engine has no SVG\n * support. Typing as `Record<SocialPlatform, ...>` makes adding a platform to\n * the union a compile error until its glyph is supplied here, keeping both\n * consumers in lockstep.\n */\nexport interface SocialIconGlyph {\n /** SVG path data on a 24×24 viewBox. */\n path: string;\n /** Brand color as a 6-digit hex string. */\n color: string;\n}\n\nexport const SOCIAL_ICON_GLYPHS: Record<SocialPlatform, SocialIconGlyph> = {\n facebook: {\n color: \"#1877F2\",\n path: \"M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z\",\n },\n twitter: {\n color: \"#000000\",\n path: \"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z\",\n },\n instagram: {\n color: \"#E4405F\",\n path: \"M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z\",\n },\n linkedin: {\n color: \"#0A66C2\",\n path: \"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z\",\n },\n xing: {\n color: \"#006567\",\n path: \"M18.188 0c-.517 0-.741.325-.927.66c0 0-7.455 13.224-7.702 13.657c.015.024 4.919 9.023 4.919 9.023c.17.308.436.66.967.66h3.454c.211 0 .375-.078.463-.22c.089-.151.089-.346-.009-.536l-4.879-8.916a.02.02 0 0 1 0-.022L22.139.756c.095-.191.097-.387.006-.535C22.056.078 21.894 0 21.686 0zM3.648 4.74c-.211 0-.385.074-.473.216c-.09.149-.078.339.02.531l2.34 4.05q.006.014 0 .021L1.86 16.051a.52.52 0 0 0 0 .529c.085.142.239.234.45.234h3.461c.518 0 .766-.348.945-.667l3.734-6.609l-2.378-4.155c-.172-.315-.434-.659-.962-.659H3.648z\",\n },\n youtube: {\n color: \"#FF0000\",\n path: \"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z\",\n },\n tiktok: {\n color: \"#000000\",\n path: \"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z\",\n },\n pinterest: {\n color: \"#BD081C\",\n path: \"M12 0C5.373 0 0 5.372 0 12c0 5.084 3.163 9.426 7.627 11.174-.105-.949-.2-2.405.042-3.441.218-.937 1.407-5.965 1.407-5.965s-.359-.719-.359-1.782c0-1.668.967-2.914 2.171-2.914 1.023 0 1.518.769 1.518 1.69 0 1.029-.655 2.568-.994 3.995-.283 1.194.599 2.169 1.777 2.169 2.133 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.012-4.882-3.414 0-5.418 2.561-5.418 5.207 0 1.031.397 2.138.893 2.738.098.119.112.224.083.345l-.333 1.36c-.053.22-.174.267-.402.161-1.499-.698-2.436-2.889-2.436-4.649 0-3.785 2.75-7.262 7.929-7.262 4.163 0 7.398 2.967 7.398 6.931 0 4.136-2.607 7.464-6.227 7.464-1.216 0-2.359-.631-2.75-1.378l-.748 2.853c-.271 1.043-1.002 2.35-1.492 3.146C9.57 23.812 10.763 24 12 24c6.627 0 12-5.373 12-12 0-6.628-5.373-12-12-12z\",\n },\n email: {\n color: \"#6B7280\",\n path: \"M1.5 8.67v8.58a3 3 0 003 3h15a3 3 0 003-3V8.67l-8.928 5.493a3 3 0 01-3.144 0L1.5 8.67z M22.5 6.908V6.75a3 3 0 00-3-3h-15a3 3 0 00-3 3v.158l9.714 5.978a1.5 1.5 0 001.572 0L22.5 6.908z\",\n },\n website: {\n color: \"#6B7280\",\n path: \"M21.721 12.752a9.711 9.711 0 0 0-.945-5.003 12.754 12.754 0 0 1-4.339 2.708 18.991 18.991 0 0 1-.214 4.772 17.165 17.165 0 0 0 5.498-2.477ZM14.634 15.55a17.324 17.324 0 0 0 .332-4.647c-.952.227-1.945.347-2.966.347-1.021 0-2.014-.12-2.966-.347a17.515 17.515 0 0 0 .332 4.647 17.385 17.385 0 0 0 5.268 0ZM9.772 17.119a18.963 18.963 0 0 0 4.456 0A17.182 17.182 0 0 1 12 21.724a17.18 17.18 0 0 1-2.228-4.605ZM7.777 15.23a18.87 18.87 0 0 1-.214-4.774 12.753 12.753 0 0 1-4.34-2.708 9.711 9.711 0 0 0-.944 5.004 17.165 17.165 0 0 0 5.498 2.477ZM21.356 14.752a9.765 9.765 0 0 1-7.478 6.817 18.64 18.64 0 0 0 1.988-4.718 18.627 18.627 0 0 0 5.49-2.098ZM2.644 14.752c1.682.971 3.53 1.688 5.49 2.099a18.64 18.64 0 0 0 1.988 4.718 9.765 9.765 0 0 1-7.478-6.816ZM13.878 2.43a9.755 9.755 0 0 1 6.116 3.986 11.267 11.267 0 0 1-3.746 2.504 18.63 18.63 0 0 0-2.37-6.49ZM12 2.276a17.152 17.152 0 0 1 2.805 7.121c-.897.23-1.837.353-2.805.353-.968 0-1.908-.122-2.805-.353A17.151 17.151 0 0 1 12 2.276ZM10.122 2.43a18.629 18.629 0 0 0-2.37 6.49 11.266 11.266 0 0 1-3.746-2.504 9.754 9.754 0 0 1 6.116-3.985Z\",\n },\n whatsapp: {\n color: \"#25D366\",\n path: \"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z\",\n },\n telegram: {\n color: \"#26A5E4\",\n path: \"M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z\",\n },\n discord: {\n color: \"#5865F2\",\n path: \"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z\",\n },\n snapchat: {\n color: \"#FFFC00\",\n path: \"M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.668.967-2.914 2.171-2.914 1.023 0 1.518.769 1.518 1.69 0 1.029-.655 2.568-.994 3.995-.283 1.194.599 2.169 1.777 2.169 2.133 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.012-4.882-3.414 0-5.418 2.561-5.418 5.207 0 1.031.397 2.138.893 2.738a.36.36 0 01.083.345l-.333 1.36c-.053.22-.174.267-.402.161-1.499-.698-2.436-2.889-2.436-4.649 0-3.785 2.75-7.262 7.929-7.262 4.163 0 7.398 2.967 7.398 6.931 0 4.136-2.607 7.464-6.227 7.464-1.216 0-2.359-.631-2.75-1.378l-.748 2.853c-.271 1.043-1.002 2.35-1.492 3.146 1.124.347 2.317.535 3.554.535 6.627 0 12.017-5.373 12.017-12.001C24.034 5.367 18.644 0 12.017 0z\",\n },\n reddit: {\n color: \"#FF4500\",\n path: \"M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z\",\n },\n github: {\n color: \"#181717\",\n path: \"M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12\",\n },\n dribbble: {\n color: \"#EA4C89\",\n path: \"M12 24C5.385 24 0 18.615 0 12S5.385 0 12 0s12 5.385 12 12-5.385 12-12 12zm10.12-10.358c-.35-.11-3.17-.953-6.384-.438 1.34 3.684 1.887 6.684 1.992 7.308 2.3-1.555 3.936-4.02 4.392-6.87zm-6.115 7.808c-.153-.9-.75-4.032-2.19-7.77l-.066.02c-5.79 2.015-7.86 6.025-8.04 6.4 1.73 1.358 3.92 2.166 6.29 2.166 1.42 0 2.77-.29 4-.814zm-11.62-2.58c.232-.4 3.045-5.055 8.332-6.765.135-.045.27-.084.405-.12-.26-.585-.54-1.167-.832-1.74C7.17 11.775 2.206 11.71 1.756 11.7l-.004.312c0 2.633.998 5.037 2.634 6.855zm-2.42-8.955c.46.008 4.683.026 9.477-1.248-1.698-3.018-3.53-5.558-3.8-5.928-2.868 1.35-5.01 3.99-5.676 7.17zM9.6 2.052c.282.38 2.145 2.914 3.822 6 3.645-1.365 5.19-3.44 5.373-3.702-1.81-1.61-4.19-2.586-6.795-2.586-.825 0-1.63.1-2.4.285zm10.335 3.483c-.218.29-1.935 2.493-5.724 4.04.24.49.47.985.68 1.486.08.18.15.36.22.53 3.41-.43 6.8.26 7.14.33-.02-2.42-.88-4.64-2.31-6.38z\",\n },\n behance: {\n color: \"#1769FF\",\n path: \"M22 7h-7V5h7v2zm1.726 10c-.442 1.297-2.029 3-5.101 3-3.074 0-5.564-1.729-5.564-5.675 0-3.91 2.325-5.92 5.466-5.92 3.082 0 4.964 1.782 5.375 4.426.078.506.109 1.188.095 2.14H15.97c.13 3.211 3.483 3.312 4.588 2.029h3.168zm-7.686-4h4.965c-.105-1.547-1.136-2.219-2.477-2.219-1.466 0-2.277.768-2.488 2.219zm-9.574 6.988H0V5.021h6.953c5.476.081 5.58 5.444 2.72 6.906 3.461 1.26 3.577 8.061-3.207 8.061zM3 11h3.584c2.508 0 2.906-3-.312-3H3v3zm3.391 3H3v3.016h3.341c3.055 0 2.868-3.016.05-3.016z\",\n },\n};\n\n// Keyed by the unions, so a style or tone added to the type is a compile error\n// here until these lists, and so the PNG build that iterates them, include it.\nconst STYLE_KEYS: Record<SocialIconStyle, true> = {\n solid: true,\n outlined: true,\n rounded: true,\n square: true,\n circle: true,\n plain: true,\n};\nconst TONE_KEYS: Record<SocialIconTone, true> = {\n brand: true,\n dark: true,\n light: true,\n};\n\nexport const SOCIAL_ICON_STYLES = Object.keys(\n STYLE_KEYS,\n) as readonly SocialIconStyle[];\n\nexport const SOCIAL_ICON_TONES = Object.keys(\n TONE_KEYS,\n) as readonly SocialIconTone[];\n\n/** The color of each one-color tone, as a 6-digit hex string. */\nexport const SOCIAL_ICON_TONE_COLORS: Record<\n Exclude<SocialIconTone, \"brand\">,\n string\n> = {\n dark: \"#1f1f1f\",\n light: \"#ffffff\",\n};\n\nfunction oneColorTone(\n tone: SocialIconTone | undefined,\n): Exclude<SocialIconTone, \"brand\"> | undefined {\n return tone === \"dark\" || tone === \"light\" ? tone : undefined;\n}\n\n/**\n * The two colors an icon is drawn with, shared by the editor's inline SVG\n * and the renderer's PNGs. `fill` is the icon's color: the badge of a filled\n * style, the outline and glyph of `outlined`, the glyph of `plain`. `onFill`\n * is the glyph on a badge: white, or near-black on a light one. An unknown\n * tone falls back to the brand color.\n */\nexport function socialIconColors(\n platform: SocialPlatform,\n tone: SocialIconTone | undefined,\n): { fill: string; onFill: string } {\n const known = oneColorTone(tone);\n return {\n fill: known\n ? SOCIAL_ICON_TONE_COLORS[known]\n : SOCIAL_ICON_GLYPHS[platform].color,\n onFill: known === \"light\" ? SOCIAL_ICON_TONE_COLORS.dark : \"#ffffff\",\n };\n}\n\n/**\n * The folder an icon's PNG sits in under `socialIconsBaseUrl`: the style for\n * brand colors, which keeps every existing URL as it was, and\n * `{style}-{tone}` for a one-color tone.\n */\nexport function socialIconAssetDir(\n style: SocialIconStyle,\n tone: SocialIconTone | undefined,\n): string {\n const known = oneColorTone(tone);\n return known ? `${style}-${known}` : style;\n}\n\n/**\n * The halo a dark `plain` or `outlined` icon is drawn with, shared by the\n * editor's inline SVG and the renderer's PNGs. Neither has a badge behind it,\n * and nearly every dark-mode client darkens a light background without\n * touching images, which would hide the icon. The faint white halo is barely\n * visible on light backgrounds and traces the icon once the background turns\n * dark. A light icon has none: a dark halo would outline it on every colored\n * band it's meant for. `width` is in the icon's 24-unit grid, centered on the\n * edge it traces.\n */\nexport function socialIconHalo(\n style: SocialIconStyle,\n tone: SocialIconTone | undefined,\n): { color: string; opacity: number; width: number } | undefined {\n if (oneColorTone(tone) !== \"dark\") return undefined;\n if (style !== \"plain\" && style !== \"outlined\") return undefined;\n return {\n color: SOCIAL_ICON_TONE_COLORS.light,\n opacity: 0.6,\n width: 1.4,\n };\n}\n\n/**\n * The glyph's share of the icon's width: larger when it stands alone\n * (`plain`) than inside a badge or outline.\n */\nexport function socialIconGlyphScale(style: SocialIconStyle): number {\n return style === \"plain\" ? 0.84 : 0.6;\n}\n","import type { Block } from \"./blocks\";\nimport type { TemplateContent } from \"./template\";\n\n/** Element ids containing \".\" or \"/\", depth first, with their template paths. Pure. */\nexport function elementIdIssues(\n content: TemplateContent,\n): { path: string; id: string }[] {\n const issues: { path: string; id: string }[] = [];\n const check = (id: unknown, path: string) => {\n if (typeof id === \"string\" && /[./]/.test(id)) issues.push({ path, id });\n };\n const visit = (blocks: Block[], path: string) => {\n if (!Array.isArray(blocks)) return;\n blocks.forEach((block, i) => {\n if (!block || typeof block !== \"object\") return;\n const where = `${path}[${i}]`;\n if (block.type === \"menu\" && Array.isArray(block.items)) {\n block.items.forEach((item, j) =>\n check(item?.id, `${where}.items[${j}].id`),\n );\n } else if (block.type === \"social\" && Array.isArray(block.icons)) {\n block.icons.forEach((icon, j) =>\n check(icon?.id, `${where}.icons[${j}].id`),\n );\n } else if (block.type === \"table\" && Array.isArray(block.rows)) {\n block.rows.forEach((row, j) => {\n const rowPath = `${where}.rows[${j}]`;\n check(row?.id, `${rowPath}.id`);\n if (Array.isArray(row?.cells)) {\n row.cells.forEach((cell, k) =>\n check(cell?.id, `${rowPath}.cells[${k}].id`),\n );\n }\n });\n } else if (block.type === \"section\" && Array.isArray(block.children)) {\n block.children.forEach((column, j) =>\n visit(column, `${where}.children[${j}]`),\n );\n } else if (block.type === \"wrapper\") {\n visit(block.children, `${where}.children`);\n }\n });\n };\n visit(content.blocks, \"blocks\");\n return issues;\n}\n","/**\n * Cycle-safe deep clone via a JSON round-trip.\n *\n * A naked `JSON.stringify` throws `Converting circular structure to JSON`\n * if the tree is self-referencing — e.g. a DOM element carrying a Sortable\n * expando back-ref (`HTMLDivElement.SortableXXX -> instance -> el -> div`)\n * leaks into block data through a drag handler inside a section. Both the\n * editor's public `getContent()` export path and the history snapshot path\n * must tolerate that: we drop the offending back-ref from the clone rather\n * than throw. Losing a transient DOM expando is harmless; the block data is\n * intact.\n *\n * The replacer tracks the ancestors of the value it is serializing and omits\n * only a reference back to one of them, which is what every cycle is. An\n * object reached by two paths is not a cycle and is copied into each place:\n * content can legitimately share one, e.g. content built by hand that puts one\n * array into two blocks, and dropping the second visit would lose that block's\n * data from `getContent()` and undo.\n */\nexport function safeClone<T>(value: T): T {\n const ancestors: object[] = [];\n return JSON.parse(\n JSON.stringify(value, function (this: unknown, _key, val) {\n if (typeof val !== \"object\" || val === null) return val;\n // `this` is the object holding `val`; anything above it on the stack\n // belongs to a branch serialization has already left.\n while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {\n ancestors.pop();\n }\n if (ancestors.includes(val)) return undefined;\n ancestors.push(val);\n return val;\n }),\n ) as T;\n}\n","function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Structural equality for JSON values, the comparison the operation engine\n * uses for `expect`: object key order is ignored, arrays compare in order, an\n * array never equals an object, and numbers compare by value (`1` and `1.0`\n * are the same JSON number). `null` is a value, so `{ a: null }` differs from\n * `{}`; an object key holding `undefined` counts as absent, because JSON\n * drops it.\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n return a.every((item, index) => deepEqual(item, b[index]));\n }\n if (isPlainObject(a)) {\n if (!isPlainObject(b)) return false;\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n if (a[key] === undefined && b[key] === undefined) continue;\n if (!deepEqual(a[key], b[key])) return false;\n }\n return true;\n }\n return false;\n}\n","import type { Block, DisplayCondition } from \"./blocks\";\nimport type { SyntaxPreset, SyntaxPresetName } from \"./merge-tags\";\nimport type { TemplateSettings } from \"./template\";\n\nexport type { DisplayCondition };\n\nexport type ViewportSize = \"desktop\" | \"mobile\";\n\nexport type UiTheme = \"light\" | \"dark\" | \"auto\";\n\nexport interface CustomFont {\n name: string;\n url: string;\n fallback?: string;\n}\n\nexport interface FontsConfig {\n defaultFallback?: string;\n defaultFont?: string;\n customFonts?: CustomFont[];\n /**\n * Restrict which of the seven built-in fonts the font picker offers.\n *\n * - `true` / omitted — every built-in is offered (the default).\n * - `false` — no built-ins; the picker lists only `customFonts`. Use this to\n * keep authors on an embedded brand kit's typefaces.\n * - `string[]` — an allowlist of built-in names to keep, matched\n * case-insensitively (`['Georgia', 'arial']`). A name that isn't a built-in\n * is logged with a warning and skipped — consistent with how\n * `paletteBlocks` treats an unknown entry — so a typo narrows the list\n * rather than silently offering all seven.\n *\n * Independent of `customFonts`: excluding the built-ins never removes a custom\n * font, and a custom font can still be the `defaultFont` when every built-in\n * is excluded. Filtering the picker never affects rendering — content already\n * using an excluded built-in still resolves to its proper fallback stack.\n */\n builtIns?: boolean | string[];\n}\n\nexport interface ColorsConfig {\n /**\n * Preset colors rendered as a clickable grid inside every color picker\n * popover. Each entry is a hex string (`'#0b5cff'`); clicking one applies it,\n * and the preset matching the current value is marked selected (matched\n * case-insensitively). The grid supplements the wheel and hex input unless\n * `allowCustom` is `false`.\n */\n presets?: string[];\n /**\n * Allow free-form color entry — the wheel and hex input — alongside the\n * presets. Defaults to `true`.\n *\n * Set to `false` together with `presets` to lock authors to the preset\n * palette: the popover then offers only the preset grid, with no wheel or hex\n * field (a white-label / brand-kit constraint). Ignored with a warning when\n * no `presets` are configured — hiding the only inputs would leave the picker\n * with no way to choose a color.\n */\n allowCustom?: boolean;\n}\n\nexport interface TemplateSettingsConfig {\n /**\n * Which template settings the Settings panel exposes.\n *\n * - `true` / omitted — every setting is editable (the default).\n * - `false` — none; the Settings tab itself stops rendering.\n * - `Array<Exclude<keyof TemplateSettings, \"locales\" | \"l10n\">>` — an allowlist of settings to keep\n * (`['width', 'backgroundColor', 'fontFamily']`). A card renders when at\n * least one of its settings survives, so hiding `locale` removes the\n * Language card and hiding `preheaderText` removes the Preheader card. An\n * empty array means none, the same as `false`.\n *\n * The list narrows, it never reorders — settings sit in fixed cards, so\n * unlike `paletteBlocks` there is no order to express. An entry that isn't a\n * `TemplateSettings` member is a compile error for TypeScript callers, and is\n * logged with a warning and skipped at runtime, so a typo narrows the panel\n * rather than silently restoring every setting.\n *\n * Presentation only. Hiding a setting never changes its value: whatever the\n * loaded content carries keeps rendering and keeps round-tripping through\n * `getContent()`. Set the values you hide from the content you hand the\n * editor — `init({ content })`, or your own `templates.load`.\n */\n fields?: boolean | Array<Exclude<keyof TemplateSettings, \"locales\" | \"l10n\">>;\n}\n\nexport interface ExportResult {\n html: string;\n mjml: string;\n}\n\nexport interface MergeTag {\n label: string;\n value: string;\n /**\n * Optional grouping label used by the built-in merge tag picker to\n * section the list. When no tag in the configured array carries\n * `group`, the picker renders a plain flat list with no headers.\n * Ignored by the renderer and by typing-autocomplete.\n */\n group?: string;\n /**\n * Optional helper text shown beneath the tag in the built-in merge\n * tag picker. Not rendered anywhere else (toolbar, autocomplete,\n * MJML output) and not stored on the inserted document node.\n */\n description?: string;\n /**\n * Example value shown in place of this tag on preview surfaces — e.g.\n * `\"Ada\"` for `{{first_name}}` — so a preview reads like a delivered\n * email instead of a list of field names.\n *\n * Display-only, and only in the previews' Sample mode: never written to\n * the template, never sent, never present in MJML output. Setting it is\n * the whole opt-in; there is no accompanying flag. A tag without a\n * sample keeps showing its `label`.\n */\n sample?: string;\n}\n\nexport interface MediaResult {\n url: string;\n alt?: string;\n /**\n * The file's own size in px, when the source knows it. An image block stores\n * it as `naturalWidth` / `naturalHeight` for its aspect-ratio lock, and a\n * section's background image for a hero's shape. Both or neither.\n */\n width?: number;\n height?: number;\n}\n\n/**\n * Why the merge-tag chooser opened, handed to {@link MergeTagsConfig.onRequest}.\n *\n * `\"insert\"` is a new tag at the caret. `\"edit\"` is the user activating a tag\n * that is already in the content, asking to swap it for another one.\n */\nexport interface MergeTagRequestContext {\n reason: \"insert\" | \"edit\";\n /**\n * The tag being replaced. Present only when `reason` is `\"edit\"` AND the\n * token in the content resolves against `tags` — a token that matches no\n * configured tag still opens the chooser, with nothing to preselect.\n */\n current?: MergeTag;\n}\n\nexport interface MergeTagsConfig {\n syntax?: SyntaxPresetName | SyntaxPreset;\n tags?: MergeTag[];\n /**\n * Consumer-owned chooser. Called both to insert a tag at the caret and to\n * replace one already in the content — `context.reason` says which. Return\n * the chosen tag, or `null` to cancel.\n *\n * The parameter is optional, so an existing zero-argument implementation\n * keeps working unchanged.\n */\n onRequest?: (context?: MergeTagRequestContext) => Promise<MergeTag | null>;\n /**\n * Whether a tag's tooltip reveals the raw token behind its label. Defaults\n * to `true`, which suits a readable syntax like `{{first_name}}` — the\n * tooltip tells an author which field they are looking at.\n *\n * Set `false` when `value` is an internal identifier (an opaque id resolved\n * by your backend) that an author should never see. Display-only: the token\n * is unchanged in stored content and in the rendered output.\n */\n showRawValue?: boolean;\n /**\n * Enables typing-based autocomplete in rich text blocks and in every\n * merge-tag-enabled input/textarea field (toolbars, template settings,\n * custom-block text fields). When the user types the syntax opener\n * (e.g. `{{`), a popup lists matching `tags`. Both surfaces share the\n * same popup, so behavior is identical.\n *\n * Defaults to `true`. Effective only when `tags` is non-empty AND\n * `syntax` is a built-in preset or a custom syntax with an `opener`\n * (a custom syntax without one has no autocomplete).\n */\n autocomplete?: boolean;\n}\n\n/**\n * A standalone logic tag — a control-flow token (e.g. `{% else %}`) inserted\n * at the cursor. Distinct from data merge tags; rendered as a keyword badge.\n */\nexport interface LogicTag {\n label: string;\n value: string;\n /** Optional grouping label used to section the logic picker. */\n group?: string;\n /** Optional helper text shown beneath the tag in the picker. */\n description?: string;\n}\n\n/**\n * A paired logic construct — an opening tag (`before`) and its matching closer\n * (`after`), e.g. `{% if vip %}` … `{% endif %}`. Selecting one inserts both\n * pills at once, wrapping the selection (or with the caret placed between\n * them). Shares its `before`/`after` shape with `DisplayCondition`.\n */\nexport interface LogicPair {\n label: string;\n /** Opening logic tag, including delimiters (e.g. `{% if vip %}`). */\n before: string;\n /** Closing logic tag, including delimiters (e.g. `{% endif %}`). */\n after: string;\n /** Optional grouping label used to section the logic picker. */\n group?: string;\n /** Optional helper text shown beneath the pair in the picker. */\n description?: string;\n}\n\n/**\n * Standalone logic-tag configuration, independent of `mergeTags`. `tags` are\n * single control-flow tokens inserted at the cursor; `pairs` are open/close\n * constructs inserted around the selection. Both appear in the built-in logic\n * picker, grouped together by `group`. Typed/pasted logic highlighting is\n * always on regardless of this.\n */\nexport interface LogicTagsConfig {\n tags?: LogicTag[];\n pairs?: LogicPair[];\n /**\n * Consumer-owned picker. When set, the \"Insert logic\" affordance calls this\n * instead of the built-in logic picker — return the chosen tag/pair (or\n * `null` to cancel). Mirrors `MergeTagsConfig.onRequest`; lets consumers use\n * their own UI and custom syntax. Precedence: `onRequest` → built-in picker.\n */\n onRequest?: () => Promise<LogicTag | LogicPair | null>;\n}\n\n/**\n * What {@link DisplayConditionsConfig.onRequest} receives. `current` and\n * `block` are copies; mutating them changes nothing in the editor.\n */\nexport interface DisplayConditionRequestContext {\n /** The block's current condition, or absent when it has none. A copy. */\n current?: DisplayCondition;\n /** The block the condition is for. A copy; mutating it changes nothing. */\n block: Block;\n}\n\nexport interface DisplayConditionsConfig {\n /**\n * Preset conditions for the built-in list. Ignored when `onRequest` is set.\n */\n conditions?: DisplayCondition[];\n /** Raw before/after boxes in the built-in list. Ignored when `onRequest` is set. */\n allowCustom?: boolean;\n /**\n * Host-owned condition builder. When set, the block settings call this\n * instead of the built-in condition list — `conditions` and `allowCustom`\n * are ignored. Return the condition to store, or `null` to cancel.\n */\n onRequest?: (\n context: DisplayConditionRequestContext,\n ) => Promise<DisplayCondition | null>;\n}\n\nexport interface ThemeOverrides {\n bg?: string;\n bgElevated?: string;\n bgHover?: string;\n bgActive?: string;\n border?: string;\n borderLight?: string;\n text?: string;\n textMuted?: string;\n textDim?: string;\n primary?: string;\n primaryHover?: string;\n primaryLight?: string;\n secondary?: string;\n secondaryHover?: string;\n secondaryLight?: string;\n success?: string;\n successLight?: string;\n warning?: string;\n warningLight?: string;\n danger?: string;\n dangerLight?: string;\n canvasBg?: string;\n dark?: Omit<ThemeOverrides, \"dark\">;\n}\n\n/**\n * The `code` any provider sends in a refusal. Cloud and AI codes are named\n * here; collaboration refusal codes flow through `CollaborationConflict`.\n * Any other string reaches `SdkError.code` without an SDK release.\n */\nexport type SdkErrorCode =\n | \"invalid_credentials\"\n | \"token_invalid\"\n | \"token_revoked\"\n | \"browser_not_allowed\"\n | \"token_scope_mismatch\"\n | \"limit_reached\"\n | \"feature_unavailable\"\n | \"not_found\"\n | \"user_required\"\n | \"not_author\"\n | \"mcp_not_allowed\"\n | \"content_too_large\"\n | \"recipient_not_allowed\"\n | \"send_failed\"\n | \"rate_limited\"\n | \"ai_turn_running\"\n | \"ai_output_invalid\"\n | \"ai_provider_error\"\n | \"unknown_locale\"\n | (string & {});\n\nexport class SdkError extends Error {\n /**\n * The refusal's other fields, when it has any: `{ limit, resetsAt }` on\n * `limit_reached`. Absent otherwise, so `\"details\" in error` says whether\n * there are some.\n */\n declare readonly details?: Readonly<Record<string, unknown>>;\n\n /**\n * @param code The error body's `code`, as sent. Absent when the body has\n * none, which includes every `422` validation failure.\n * @param details The error body's fields besides `message`, `errors` and\n * `code`, or an AI stream's `error` event's besides `type`, `code` and\n * `message`. Set only when there are some.\n */\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly code?: SdkErrorCode,\n details?: Readonly<Record<string, unknown>>,\n ) {\n super(message);\n this.name = \"SdkError\";\n if (details !== undefined && Object.keys(details).length > 0) {\n this.details = details;\n }\n }\n\n get isNotFound(): boolean {\n return this.statusCode === 404;\n }\n\n get isUnauthorized(): boolean {\n return this.statusCode === 401;\n }\n\n get isServerError(): boolean {\n return this.statusCode !== undefined && this.statusCode >= 500;\n }\n}\n\n/**\n * A `429`: too many requests. `retryAfterMs` is how long to wait, from the\n * response's `Retry-After` (seconds or an HTTP date), a second when it is\n * missing. Every BYO provider may reject with one; the editor says to try\n * again in a moment.\n */\nexport class ThrottledError extends SdkError {\n constructor(\n message: string,\n readonly retryAfterMs: number,\n code: SdkErrorCode = \"rate_limited\",\n details?: Readonly<Record<string, unknown>>,\n ) {\n super(message, 429, code, details);\n this.name = \"ThrottledError\";\n }\n}\n","import type { Block } from \"./blocks\";\nimport { safeClone } from \"./clone\";\nimport { deepEqual } from \"./deep-equal\";\nimport { SdkError } from \"./config\";\nimport type { CustomBlockDefinition } from \"./custom-blocks\";\nimport type { TemplateContent, TemplateSettings } from \"./template\";\n\n/** A translated text value and the hash of the default value it was written against. */\nexport interface LocalizedText {\n value: string;\n /** `sourceHash(defaultValue)` when the value was written or kept. */\n sourceHash: string;\n}\n\n/** One language's layer on a block. Members are omitted when empty. */\nexport interface BlockLocaleLayer {\n /** Translated text, by field path. */\n text?: Record<string, LocalizedText>;\n /** Any other property overridden for this language, by field path. */\n set?: Record<string, unknown>;\n /** The block is left out of this language. */\n hidden?: true;\n}\n\n/** One language's layer on the template settings. */\nexport interface SettingsLocaleLayer {\n text?: Record<string, LocalizedText>;\n set?: Record<string, unknown>;\n}\n\n/**\n * Each block type's human-readable text, as path patterns. `*` stands for an\n * element id in a list. Custom blocks' text fields come from their definition.\n */\nexport const TRANSLATABLE_FIELDS: Readonly<Record<string, readonly string[]>> =\n {\n title: [\"content\"],\n paragraph: [\"content\"],\n html: [\"content\"],\n image: [\"alt\"],\n video: [\"alt\"],\n button: [\"text\"],\n menu: [\"items.*.text\"],\n table: [\"rows.*.cells.*.content\"],\n countdown: [\n \"labelDays\",\n \"labelHours\",\n \"labelMinutes\",\n \"labelSeconds\",\n \"expiredMessage\",\n ],\n custom: [\"fieldValues.*\"],\n };\n\n/** The settings' human-readable text. */\nexport const SETTINGS_TRANSLATABLE_FIELDS: readonly string[] = [\n \"preheaderText\",\n];\n\n/** A language tag Templatical accepts: a 2–3 letter language, then 2–8 character subtags. */\nexport function isLocaleTag(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(value)\n );\n}\n\ntype Json = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Json {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst FORBIDDEN_SEGMENTS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/** True when every segment is usable: non-empty and not a prototype key. */\nexport function isSafePath(path: string): boolean {\n return path\n .split(\".\")\n .every((segment) => segment !== \"\" && !FORBIDDEN_SEGMENTS.has(segment));\n}\n\nfunction step(current: unknown, segment: string): unknown {\n if (FORBIDDEN_SEGMENTS.has(segment)) return undefined;\n if (Array.isArray(current)) {\n return current.find((item) => isRecord(item) && item.id === segment);\n }\n return isRecord(current) && Object.hasOwn(current, segment)\n ? current[segment]\n : undefined;\n}\n\n/** The value at a field path, or `undefined` when any segment doesn't resolve. */\nexport function readPath(target: unknown, path: string): unknown {\n return path.split(\".\").reduce<unknown>(step, target);\n}\n\nfunction pruneLayers<T extends { l10n?: Record<string, BlockLocaleLayer> }>(\n target: T,\n): T {\n const result = safeClone(target);\n for (const [locale, layer] of Object.entries(result.l10n ?? {})) {\n for (const kind of [\"text\", \"set\"] as const) {\n for (const path of Object.keys(layer[kind] ?? {})) {\n const parent = path.includes(\".\")\n ? readPath(target, path.slice(0, path.lastIndexOf(\".\")))\n : target;\n if (\n !isSafePath(path) ||\n (kind === \"text\"\n ? readPath(target, path) === undefined\n : !isRecord(parent) && readPath(target, path) === undefined)\n )\n delete layer[kind]![path];\n }\n if (layer[kind] && !Object.keys(layer[kind]!).length) delete layer[kind];\n }\n if (!Object.keys(layer).length) delete result.l10n![locale];\n }\n if (result.l10n && !Object.keys(result.l10n).length) delete result.l10n;\n return deepEqual(result, target) ? target : result;\n}\n\n/** Remove unresolved layer paths and empty localization members, recursively. Pure. */\nexport function pruneLocaleOrphans(block: Block): Block {\n const result = pruneLayers(block);\n if (result.type === \"wrapper\") {\n const children = result.children.map(pruneLocaleOrphans);\n return children.some((child, i) => child !== result.children[i])\n ? { ...result, children }\n : result;\n }\n if (result.type !== \"section\") return result;\n const children = result.children.map((column) =>\n column.map(pruneLocaleOrphans),\n );\n return children.some((column, i) =>\n column.some((child, j) => child !== result.children[i][j]),\n )\n ? { ...result, children }\n : result;\n}\n\n/** Paths or replacement values that change shared built-in list or section structure. */\nexport function isStructuralLocalePath(\n block: Block,\n path: string,\n value?: unknown,\n): boolean {\n if (block.type === \"custom\") return false;\n if (block.type === \"section\") return path === \"columns\";\n const list =\n block.type === \"menu\"\n ? \"items\"\n : block.type === \"social\"\n ? \"icons\"\n : block.type === \"table\"\n ? \"rows\"\n : null;\n if (!list) return false;\n const segments = path.split(\".\");\n if (segments[0] !== list) return false;\n if (segments.length === 1) return true;\n const elementPath =\n block.type === \"table\" && segments[2] === \"cells\"\n ? segments.slice(0, 4).join(\".\")\n : segments.slice(0, 2).join(\".\");\n if (\n block.type === \"table\" &&\n segments[2] === \"cells\" &&\n segments.length === 3\n )\n return true;\n const depth = elementPath.split(\".\").length;\n if (segments[depth] === \"id\") return true;\n if (segments.length !== depth) return false;\n const before = readPath(block, elementPath);\n if (!isRecord(before) || !isRecord(value) || before.id !== value.id)\n return true;\n if (block.type === \"table\" && depth === 2) {\n const ids = (cells: unknown) =>\n Array.isArray(cells)\n ? cells.map((cell) => (isRecord(cell) ? cell.id : undefined))\n : null;\n return !deepEqual(ids(before.cells), ids(value.cells));\n }\n return false;\n}\n\n/** Remove unresolved settings layer paths and empty localization members. Pure. */\nexport function pruneSettingsLocaleOrphans(\n settings: TemplateSettings,\n): TemplateSettings {\n return pruneLayers(settings);\n}\n\n/** Write at a field path; returns false when the path's parent doesn't resolve. */\nexport function writePath(target: Json, path: string, value: unknown): boolean {\n if (!isSafePath(path)) return false;\n const segments = path.split(\".\");\n const last = segments.pop()!;\n const parent = segments.reduce<unknown>(step, target);\n if (Array.isArray(parent)) {\n const index = parent.findIndex(\n (item) => isRecord(item) && item.id === last,\n );\n if (index < 0) return false;\n parent[index] = safeClone(value);\n return true;\n }\n if (!isRecord(parent)) return false;\n // `null` in a layer's `set` means the property is absent in this language.\n if (value === null) delete parent[last];\n else parent[last] = safeClone(value);\n return true;\n}\n\n/** Expand a pattern against a block: `*` → each element id present. */\nfunction expand(target: unknown, pattern: string): string[] {\n const [head, ...rest] = pattern.split(\".\");\n if (head === undefined) return [\"\"];\n const out: string[] = [];\n if (head === \"*\") {\n const list = Array.isArray(target) ? target : [];\n for (const item of list) {\n if (!isRecord(item) || typeof item.id !== \"string\") continue;\n for (const tail of rest.length ? expand(item, rest.join(\".\")) : [\"\"]) {\n out.push(tail ? `${item.id}.${tail}` : item.id);\n }\n }\n return out;\n }\n const next = isRecord(target) ? target[head] : undefined;\n if (rest.length === 0) return next === undefined ? [] : [head];\n for (const tail of expand(next, rest.join(\".\"))) out.push(`${head}.${tail}`);\n return out;\n}\n\n/**\n * A block's translatable text paths, with element ids filled in. A custom\n * block's `fieldValues.<key>` counts only for its definition's `text` and\n * `textarea` fields, so without `definitions` it has none.\n */\nexport function translatableFields(\n block: Block,\n definitions: readonly CustomBlockDefinition[] = [],\n): string[] {\n if (block.type === \"custom\") {\n const definition = definitions.find(\n (candidate) => candidate.type === (block as unknown as Json).customType,\n );\n const textKeys = new Set(\n (definition?.fields ?? [])\n .filter((field) => field.type === \"text\" || field.type === \"textarea\")\n .map((field) => field.key),\n );\n const values = (block as unknown as Json).fieldValues;\n return isRecord(values)\n ? Object.keys(values)\n .filter((key) => textKeys.has(key))\n .map((key) => `fieldValues.${key}`)\n : [];\n }\n // Dots delimit path segments, so these imported element ids have no localization path.\n const localizableId = (item: { id: string }) => !item.id.includes(\".\");\n const target =\n block.type === \"menu\"\n ? { ...block, items: block.items.filter(localizableId) }\n : block.type === \"table\"\n ? {\n ...block,\n rows: block.rows.filter(localizableId).map((row) => ({\n ...row,\n cells: row.cells.filter(localizableId),\n })),\n }\n : block;\n return (TRANSLATABLE_FIELDS[block.type] ?? []).flatMap((pattern) =>\n expand(target, pattern),\n );\n}\n\n/** Is `path` an instance of one of the block type's text patterns? */\nexport function isTranslatablePath(blockType: string, path: string): boolean {\n return (TRANSLATABLE_FIELDS[blockType] ?? []).some((pattern) => {\n const want = pattern.split(\".\");\n const have = path.split(\".\");\n return (\n want.length === have.length &&\n want.every((segment, i) => segment === \"*\" || segment === have[i])\n );\n });\n}\n\n/** FNV-1a 32-bit over the UTF-8 bytes, as 8 lowercase hex digits. */\nexport function sourceHash(value: string): string {\n let hash = 0x811c9dc5;\n for (const byte of new TextEncoder().encode(value)) {\n hash ^= byte;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\nfunction withoutL10n<T extends Json>(value: T): T {\n const { l10n: _l10n, ...rest } = value;\n return rest as T;\n}\n\nfunction orderedSetEntries(\n set: Record<string, unknown> = {},\n): [string, unknown][] {\n // Stable sorting retains insertion order among paths at the same depth.\n return Object.entries(set).sort(\n ([left], [right]) => left.split(\".\").length - right.split(\".\").length,\n );\n}\n\n/**\n * One block in one language, without its `l10n` and without recursing into\n * children: the editor renders each block through this. For the default\n * locale it only strips `l10n`. Paths that no longer resolve are skipped.\n * Property overrides apply from shallow to deep paths.\n */\nexport function localizeBlock(\n block: Block,\n locale: string,\n defaultLocale: string,\n): Block {\n const json = block as unknown as Json;\n const view = safeClone(withoutL10n(json));\n return applyBlockLocaleLayer(block, view, locale, defaultLocale);\n}\n\nfunction applyBlockLocaleLayer(\n block: Block,\n view: Json,\n locale: string,\n defaultLocale: string,\n): Block {\n const json = block as unknown as Json;\n if (locale === defaultLocale) return view as unknown as Block;\n const layer = (json.l10n as Record<string, BlockLocaleLayer> | undefined)?.[\n locale\n ];\n if (!layer) return view as unknown as Block;\n for (const [path, value] of orderedSetEntries(layer.set))\n writePath(view, path, value);\n for (const [path, text] of Object.entries(layer.text ?? {}))\n if (readPath(block, path) !== undefined) writePath(view, path, text.value);\n // Cached HTML belongs to the default fields; a localized custom block\n // needs its resolver to render those fields again. Its stylesheet is shared.\n if (\n block.type === \"custom\" &&\n (Object.keys(layer.text ?? {}).length > 0 ||\n Object.keys(layer.set ?? {}).length > 0)\n )\n delete view.renderedHtml;\n return view as unknown as Block;\n}\n\nfunction localizeBlockOwnFields(\n block: Block,\n locale: string,\n defaultLocale: string,\n): Block {\n const json = block as unknown as Json;\n // Only sections and wrappers have children, and `resolveLocale` projects\n // those into new arrays, so they are left out of this block's own copy.\n if (\n (json.type !== \"section\" && json.type !== \"wrapper\") ||\n !Array.isArray(json.children)\n )\n return localizeBlock(block, locale, defaultLocale);\n const { children, ...own } = withoutL10n(json);\n const view = safeClone(own) as Json;\n view.children = children;\n return applyBlockLocaleLayer(block, view, locale, defaultLocale);\n}\n\nfunction isHidden(block: Block, locale: string): boolean {\n return (\n (block as unknown as Json & { l10n?: Record<string, BlockLocaleLayer> })\n .l10n?.[locale]?.hidden === true\n );\n}\n\nfunction stripSettings(settings: TemplateSettings): TemplateSettings {\n const { locales: _locales, l10n: _l10n, ...rest } = settings;\n return rest as TemplateSettings;\n}\n\n/** The template's default (source) language. */\nexport function defaultLocaleOf(content: TemplateContent): string {\n return content.settings?.locale ?? \"en\";\n}\n\n/**\n * One language of a template, as a plain template: hidden blocks dropped,\n * overrides and translations applied, missing values left at the default\n * (LD3), and no localization fields left. Pure: `content` is not changed.\n */\nexport function resolveLocale(\n content: TemplateContent,\n locale: string,\n options?: { missing?: \"throw\" | \"default\" },\n): TemplateContent {\n const fallback = defaultLocaleOf(content);\n const locales = content.settings?.locales ?? [];\n if (locale !== fallback && !locales.includes(locale)) {\n if (options?.missing === \"default\") locale = fallback;\n else\n throw new SdkError(\n `This template has no \"${locale}\" version.`,\n undefined,\n \"unknown_locale\",\n );\n }\n const project = (blocks: Block[]): Block[] =>\n blocks.flatMap((block) => {\n if (locale !== fallback && isHidden(block, locale)) return [];\n const layer = block.l10n?.[locale];\n const touchesChildPath = [\n ...Object.keys(layer?.set ?? {}),\n ...Object.keys(layer?.text ?? {}),\n ].some((path) => path.startsWith(\"children.\"));\n const view = (touchesChildPath\n ? localizeBlock(block, locale, fallback)\n : localizeBlockOwnFields(block, locale, fallback)) as unknown as Json;\n if (view.type === \"section\" && Array.isArray(view.children)) {\n view.children = (view.children as Block[][]).map((column) =>\n project(column),\n );\n } else if (view.type === \"wrapper\" && Array.isArray(view.children)) {\n view.children = project(view.children as Block[]);\n }\n return [view as unknown as Block];\n });\n const settings = safeClone(\n stripSettings(content.settings),\n ) as unknown as Json;\n const layer = content.settings?.l10n?.[locale];\n if (locale !== fallback && layer) {\n for (const [path, value] of orderedSetEntries(layer.set))\n writePath(settings, path, value);\n for (const [path, text] of Object.entries(layer.text ?? {}))\n if (readPath(content.settings, path) !== undefined)\n writePath(settings, path, text.value);\n }\n settings.locale = locale;\n return {\n blocks: project(content.blocks),\n settings: settings as unknown as TemplateSettings,\n };\n}\n\nexport interface LocaleCoverage {\n translated: string[];\n missing: string[];\n stale: string[];\n}\n\n/**\n * Which translatable fields of one language are translated, missing or stale,\n * as field ids, in document order with settings last. Hidden blocks and empty\n * defaults don't count.\n */\nexport function localeCoverage(\n content: TemplateContent,\n locale: string,\n definitions: readonly CustomBlockDefinition[] = [],\n): LocaleCoverage {\n const result: LocaleCoverage = { translated: [], missing: [], stale: [] };\n const visit = (\n id: string,\n target: unknown,\n paths: string[],\n texts: Record<string, LocalizedText> | undefined,\n ) => {\n for (const path of paths) {\n const value = readPath(target, path);\n if (typeof value !== \"string\") continue;\n const text = texts?.[path];\n // An empty default isn't missing, but an existing translation of it can be stale.\n if (!text && value === \"\") continue;\n if (!text) result.missing.push(`${id}/${path}`);\n else if (text.sourceHash !== sourceHash(value))\n result.stale.push(`${id}/${path}`);\n else result.translated.push(`${id}/${path}`);\n }\n };\n const walk = (blocks: Block[]) => {\n for (const block of blocks) {\n if (isHidden(block, locale)) continue;\n const layer = (\n block as unknown as { l10n?: Record<string, BlockLocaleLayer> }\n ).l10n?.[locale];\n visit(\n block.id,\n block,\n translatableFields(block, definitions),\n layer?.text,\n );\n const children = (block as unknown as Json).children;\n if (block.type === \"section\" && Array.isArray(children)) {\n for (const column of children as Block[][]) walk(column);\n } else if (block.type === \"wrapper\" && Array.isArray(children)) {\n walk(children as Block[]);\n }\n }\n };\n walk(content.blocks);\n visit(\n \"settings\",\n content.settings,\n [...SETTINGS_TRANSLATABLE_FIELDS],\n content.settings?.l10n?.[locale]?.text,\n );\n return result;\n}\n\n/** Ids of blocks hidden in `locale`, depth first. Pure. */\nexport function localeHiddenBlocks(\n content: TemplateContent,\n locale: string,\n): string[] {\n if (\n locale === defaultLocaleOf(content) ||\n !content.settings.locales?.includes(locale)\n )\n return [];\n const ids: string[] = [];\n const walk = (blocks: Block[]) => {\n for (const block of blocks) {\n if (isHidden(block, locale)) ids.push(block.id);\n if (block.type === \"section\") block.children.forEach(walk);\n else if (block.type === \"wrapper\") walk(block.children);\n }\n };\n walk(content.blocks);\n return ids;\n}\n\n/** Field ids with a nonempty default that would keep the current default's value if `locale` became the default. Pure. */\nexport function defaultLocaleGaps(\n content: TemplateContent,\n locale: string,\n definitions: readonly CustomBlockDefinition[] = [],\n): string[] {\n if (\n locale === defaultLocaleOf(content) ||\n !content.settings.locales?.includes(locale)\n )\n return [];\n const gaps: string[] = [];\n const collect = (id: string, target: Json, paths: readonly string[]) => {\n gaps.push(\n ...defaultLocaleGapPaths(target, locale, paths).map(\n (path) => `${id}/${path}`,\n ),\n );\n };\n const walk = (blocks: Block[]) => {\n for (const block of blocks) {\n collect(\n block.id,\n block as unknown as Json,\n translatableFields(block, definitions),\n );\n if (block.type === \"section\") block.children.forEach(walk);\n else if (block.type === \"wrapper\") walk(block.children);\n }\n };\n walk(content.blocks);\n collect(\n \"settings\",\n content.settings as unknown as Json,\n SETTINGS_TRANSLATABLE_FIELDS,\n );\n return gaps;\n}\n\nfunction defaultLocaleGapPaths(\n target: Json,\n locale: string,\n paths: readonly string[],\n): string[] {\n const layer = (target.l10n as Record<string, BlockLocaleLayer> | undefined)?.[\n locale\n ];\n return paths.filter((path) => {\n const value = readPath(target, path);\n // An empty default has no text to keep, as in localeCoverage.\n if (typeof value !== \"string\" || value === \"\" || layer?.text?.[path])\n return false;\n return !Object.keys(layer?.set ?? {}).some(\n (key) =>\n (path === key || path.startsWith(`${key}.`)) &&\n (!key.includes(\".\") ||\n readPath(target, key.slice(0, key.lastIndexOf(\".\"))) !== undefined),\n );\n });\n}\n\n/** Promote a language's layers to the base. Membership and visibility are checked by the engine. */\nexport function rebaseDefaultLocale(\n content: TemplateContent,\n locale: string,\n customTextFields: Readonly<Record<string, readonly string[]>> = {},\n): TemplateContent {\n const previous = defaultLocaleOf(content);\n const rebase = <T extends { l10n?: Record<string, BlockLocaleLayer> }>(\n target: T,\n textPath: (path: string) => boolean,\n textPaths: readonly string[],\n ): T => {\n const gapPaths = defaultLocaleGapPaths(\n target as unknown as Json,\n locale,\n textPaths,\n );\n const layers = safeClone(target.l10n ?? {});\n const promoted = layers[locale] ?? {};\n const next = safeClone(target) as T & Json;\n delete next.l10n;\n for (const [path, value] of orderedSetEntries(promoted.set))\n writePath(next, path, value);\n for (const [path, value] of Object.entries(promoted.text ?? {}))\n if (readPath(target, path) !== undefined)\n writePath(next, path, value.value);\n delete layers[locale];\n const old: BlockLocaleLayer = {};\n const paths = new Set([\n ...Object.keys(promoted.set ?? {}),\n ...Object.keys(promoted.text ?? {}),\n ...gapPaths,\n ]);\n for (const path of paths) {\n const before = readPath(target, path);\n const after = readPath(next, path);\n if (deepEqual(before, after)) {\n // Keep the former default current even when the new default has no\n // translation and inherits this value unchanged.\n if (\n (promoted.text?.[path] || gapPaths.includes(path)) &&\n textPath(path) &&\n typeof before === \"string\" &&\n before !== \"\"\n )\n (old.text ??= {})[path] = {\n value: before,\n sourceHash: sourceHash(before),\n };\n continue;\n }\n if (\n textPath(path) &&\n typeof before === \"string\" &&\n typeof after === \"string\"\n )\n (old.text ??= {})[path] = {\n value: before,\n sourceHash: sourceHash(after),\n };\n else\n (old.set ??= {})[path] =\n before === undefined ? null : safeClone(before);\n }\n const restoreSubtrees = (layer: BlockLocaleLayer, projected: Json) => {\n const roots = new Set<string>();\n for (const path of Object.keys(layer.set ?? {})) {\n const segments = path.split(\".\");\n while (segments.length > 1) {\n const parent = readPath(next, segments.slice(0, -1).join(\".\"));\n if (\n isRecord(parent) ||\n (Array.isArray(parent) &&\n readPath(next, segments.join(\".\")) !== undefined)\n )\n break;\n segments.pop();\n }\n const root = segments.join(\".\");\n if (root !== path) roots.add(root);\n }\n for (const root of roots) {\n for (const kind of [\"text\", \"set\"] as const) {\n for (const path of Object.keys(layer[kind] ?? {}))\n if (path === root || path.startsWith(`${root}.`))\n delete layer[kind]![path];\n }\n const value = readPath(projected, root);\n (layer.set ??= {})[root] =\n value === undefined ? null : safeClone(value);\n }\n if (layer.text && !Object.keys(layer.text).length) delete layer.text;\n };\n for (const layer of Object.values(layers)) {\n // A missing parent needs the whole prior projection, including inherited\n // siblings and all of this language's overrides and translated values.\n const projected = safeClone(target) as T & Json;\n for (const [path, value] of orderedSetEntries(layer.set))\n writePath(projected, path, value);\n for (const [path, entry] of Object.entries(layer.text ?? {}))\n if (readPath(target, path) !== undefined)\n writePath(projected, path, entry.value);\n for (const [path, entry] of Object.entries(layer.text ?? {})) {\n const after = readPath(next, path);\n if (typeof after !== \"string\") {\n (layer.set ??= {})[path] = entry.value;\n delete layer.text![path];\n } else {\n const before = readPath(target, path);\n if (\n typeof before === \"string\" &&\n entry.sourceHash === sourceHash(before)\n )\n entry.sourceHash = sourceHash(after);\n }\n }\n restoreSubtrees(layer, projected);\n }\n if (Object.keys(old).length) {\n restoreSubtrees(old, target as T & Json);\n layers[previous] = old;\n }\n if (Object.keys(layers).length) next.l10n = layers;\n return next;\n };\n const walk = (blocks: Block[]): Block[] =>\n blocks.map((block) => {\n // Captured paths travel with the operation; prior text entries still\n // identify custom text when the caller has no definitions.\n const textPaths =\n block.type === \"custom\"\n ? [\n ...new Set([\n ...(Object.hasOwn(customTextFields, block.id)\n ? customTextFields[block.id]!\n : []),\n ...Object.values(block.l10n ?? {}).flatMap((layer) =>\n Object.keys(layer.text ?? {}),\n ),\n ]),\n ]\n : translatableFields(block);\n const next = rebase(\n block,\n (path) =>\n block.type === \"custom\"\n ? textPaths.includes(path)\n : isTranslatablePath(block.type, path),\n textPaths,\n );\n if (\n block.type === \"custom\" &&\n next.type === \"custom\" &&\n !deepEqual(block.fieldValues, next.fieldValues)\n )\n delete next.renderedHtml;\n if (next.type === \"section\") next.children = next.children.map(walk);\n else if (next.type === \"wrapper\") next.children = walk(next.children);\n return next;\n });\n const settings = rebase(\n content.settings,\n (path) => SETTINGS_TRANSLATABLE_FIELDS.includes(path),\n SETTINGS_TRANSLATABLE_FIELDS,\n );\n settings.locale = locale;\n settings.locales = content.settings.locales!.map((tag) =>\n tag === locale ? previous : tag,\n );\n return { blocks: walk(content.blocks), settings };\n}\n","import { elementIdIssues } from \"./element-ids\";\nimport type { Block } from \"./blocks\";\nimport type { CustomBlockDefinition } from \"./custom-blocks\";\nimport { safeClone } from \"./clone\";\nimport { deepEqual } from \"./deep-equal\";\nimport {\n defaultLocaleOf,\n localeHiddenBlocks,\n rebaseDefaultLocale,\n isLocaleTag,\n isSafePath,\n isTranslatablePath,\n isStructuralLocalePath,\n readPath,\n pruneLocaleOrphans,\n pruneSettingsLocaleOrphans,\n SETTINGS_TRANSLATABLE_FIELDS,\n translatableFields,\n type BlockLocaleLayer,\n type LocalizedText,\n type SettingsLocaleLayer,\n} from \"./localization\";\nimport type { TemplateContent, TemplateSettings } from \"./template\";\n\n/** Where a block sits: the top level, a section column, or wrapper children. */\nexport type BlockParent =\n null | { sectionId: string; column: number } | { wrapperId: string };\n\nconst SECTION_WRAPPER_IN_WRAPPER =\n \"Sections with a wrapper cannot be placed inside wrappers.\";\n\n/** Insert `block` into `parent`, after the sibling `after` (`null`: first). */\nexport interface AddBlockOperation {\n op: \"addBlock\";\n /**\n * A non-empty string `id` and a string `type`. A section brings columns of\n * blocks in `children`; a wrapper brings a flat child list.\n */\n block: Block;\n parent: BlockParent;\n after: string | null;\n}\n\n/**\n * Move a block to `parent`, after the sibling `after` (`null`: first). The\n * sibling list is the target container with the moved block taken out.\n */\nexport interface MoveBlockOperation {\n op: \"moveBlock\";\n blockId: string;\n parent: BlockParent;\n after: string | null;\n /**\n * The block's current position: its parent and its previous sibling. A key\n * left out counts as `null`.\n */\n expect?: { parent: BlockParent; after: string | null };\n}\n\n/** Delete a block and its descendants, if it is a section or wrapper. */\nexport interface DeleteBlockOperation {\n op: \"deleteBlock\";\n blockId: string;\n /** The whole current block, children included, compared exactly. */\n expect?: { block: Block };\n}\n\n/**\n * Replace top-level keys of a block (`set`, a `styles` object included) and\n * remove others (`unset`). `id`, `type`, `children` and `l10n` can't be touched, and\n * a section's `columns` can't be unset. On a section, `set.columns` resizes\n * `children` to the layout's column count.\n */\nexport interface UpdateBlockOperation {\n op: \"updateBlock\";\n blockId: string;\n set?: Record<string, unknown>;\n unset?: string[];\n /** Expected current values by key; `null` matches `null` or an absent key. */\n expect?: Record<string, unknown>;\n}\n\n/** Replace and remove top-level keys of `content.settings`. */\nexport interface UpdateSettingsOperation {\n op: \"updateSettings\";\n set?: Partial<TemplateSettings>;\n unset?: string[];\n /** Expected current values by key; `null` matches `null` or an absent key. */\n expect?: Record<string, unknown>;\n}\n\n/**\n * Replace `blocks` and `settings` wholesale. The engine checks only that\n * `blocks` is an array, `settings` an object, and element ids contain no \".\" or \"/\".\n */\nexport interface SetContentOperation {\n op: \"setContent\";\n content: TemplateContent;\n}\n\nexport interface AddLocaleOperation {\n op: \"addLocale\";\n locale: string;\n /** Index in `settings.locales` to insert at; default the end. Undo uses it to restore order. */\n position?: number;\n}\n\nexport interface RemoveLocaleOperation {\n op: \"removeLocale\";\n locale: string;\n /** Guard: the locale's block and settings layers must match exactly; absent means no layer. */\n expect?: {\n blocks: Record<string, BlockLocaleLayer>;\n settings?: SettingsLocaleLayer;\n };\n}\n\nexport interface SetDefaultLocaleOperation {\n op: \"setDefaultLocale\";\n /** A language already in `settings.locales`. */\n locale: string;\n /**\n * Custom block ids mapped to their registered text/textarea\n * `fieldValues.<key>` paths. Paths must resolve to strings on existing custom\n * blocks; `__proto__`, `constructor` and `prototype` are forbidden map keys.\n * Captured in the operation so replay needs no field definitions;\n * omitted means only existing custom text entries identify text fields.\n */\n customTextFields?: Record<string, string[]>;\n}\n\n/**\n * Capture a default-language change with custom text paths from definitions. Pure.\n * Throws `invalid_operation` at index 0 if a captured custom block id is a\n * forbidden metadata key (`__proto__`, `constructor` or `prototype`).\n */\nexport function createSetDefaultLocaleOperation(\n content: TemplateContent,\n locale: string,\n definitions: readonly CustomBlockDefinition[] = [],\n): SetDefaultLocaleOperation {\n const customTextFields = Object.fromEntries(\n blocksIn(content.blocks).flatMap((block) => {\n if (block.type !== \"custom\") return [];\n const paths = translatableFields(\n block as unknown as Block,\n definitions,\n ).filter((path) => typeof readPath(block, path) === \"string\");\n if (\n paths.length &&\n FORBIDDEN_CUSTOM_TEXT_FIELDS_KEYS.has(block.id as string)\n )\n fail(\"invalid_operation\", 0, CUSTOM_TEXT_FIELDS_ERROR);\n return paths.length ? [[block.id as string, paths]] : [];\n }),\n );\n return {\n op: \"setDefaultLocale\",\n locale,\n ...(Object.keys(customTextFields).length ? { customTextFields } : {}),\n };\n}\n\nexport interface LocaleLayerExpect {\n text?: Record<string, LocalizedText | null>;\n /** `null` matches an absent override. */\n set?: Record<string, unknown>;\n hidden?: boolean;\n}\n\nexport interface UpdateBlockLocaleOperation {\n op: \"updateBlockLocale\";\n blockId: string;\n locale: string;\n text?: Record<string, LocalizedText>;\n set?: Record<string, unknown>;\n unset?: string[];\n hidden?: boolean;\n expect?: LocaleLayerExpect;\n}\n\nexport interface UpdateSettingsLocaleOperation {\n op: \"updateSettingsLocale\";\n locale: string;\n text?: Record<string, LocalizedText>;\n set?: Record<string, unknown>;\n unset?: string[];\n expect?: Omit<LocaleLayerExpect, \"hidden\">;\n}\n\n/**\n * One change to a template, in the vocabulary the editor, the CLI's `edit`\n * command, collaboration backends and Templatical Cloud share. Positions are\n * anchored to a sibling rather than an index, so an operation means the same\n * thing after someone else's change lands first.\n */\nexport type Operation =\n | AddBlockOperation\n | MoveBlockOperation\n | DeleteBlockOperation\n | UpdateBlockOperation\n | UpdateSettingsOperation\n | SetContentOperation\n | AddLocaleOperation\n | RemoveLocaleOperation\n | SetDefaultLocaleOperation\n | UpdateBlockLocaleOperation\n | UpdateSettingsLocaleOperation;\n\n/** Why {@link applyOperations} refused a batch. */\nexport type OperationErrorCode =\n | \"block_exists\"\n | \"block_missing\"\n | \"anchor_missing\"\n | \"precondition_failed\"\n | \"lock_held\"\n | \"locked_by_others\"\n | \"invalid_operation\";\n\n/**\n * A refused batch. `opIndex` is the 0-based index of the operation that\n * failed; nothing in the batch was applied. `blockId`, when set, is the block\n * the refusal is about: the locked block for `lock_held` and\n * `locked_by_others`, the clashing id for `block_exists`, the missing block or\n * section for `block_missing`, the missing anchor for `anchor_missing`.\n */\nexport class OperationError extends Error {\n readonly code: OperationErrorCode;\n readonly opIndex: number;\n readonly blockId?: string;\n\n constructor(\n code: OperationErrorCode,\n opIndex: number,\n message: string,\n blockId?: string,\n ) {\n super(message);\n this.name = \"OperationError\";\n this.code = code;\n this.opIndex = opIndex;\n if (blockId !== undefined) this.blockId = blockId;\n }\n}\n\n/** A lock as the engine sees it: which session holds which block. */\nexport interface OperationLock {\n blockId: string;\n sessionId: string;\n /** Absent or `null` holds the default language and structure. */\n locale?: string | null;\n}\n\n/**\n * Who is acting, and which blocks sessions hold. Omit it to apply with no\n * locks at all, which is how an editor applies a batch the server accepted.\n */\nexport interface OperationContext {\n /** Unexpired locks only. */\n locks?: readonly OperationLock[];\n /** The acting session; `null` (headless) treats every lock as another's. */\n session?: string | null;\n}\n\n/**\n * The column count of a section layout. `\"1\"` → 1. `\"3\"` and `\"1-2-1\"` → 3.\n * `\"4\"` → 4. `\"2\"`, `\"1-2\"`, `\"2-1\"`, `\"1-3\"` and `\"3-1\"` → 2. Anything else\n * → 2. The section toolbar and Templatical Cloud's engine use the same rule.\n */\nexport function getColumnCount(layout: unknown): number {\n if (layout === \"1\") return 1;\n if (layout === \"3\" || layout === \"1-2-1\") return 3;\n if (layout === \"4\") return 4;\n return 2;\n}\n\n/**\n * Apply a batch to a copy of `content` and return the copy. All or nothing:\n * the first operation that can't apply throws an {@link OperationError}, and\n * `content` is untouched.\n *\n * `addLocale` and `removeLocale` manage language versions. `updateBlockLocale`\n * and `updateSettingsLocale` change their layers: unset, text, set, then hidden.\n * Empty localization members are pruned. Only `updateBlockLocale` checks\n * language locks; the membership and settings-layer operations ignore locks.\n * `setDefaultLocale` promotes a version to the base and checks every lock.\n *\n * Each operation is checked in a fixed order, and the first failing check\n * decides the error (the cross-track contract's C1, which Templatical Cloud's\n * PHP engine follows too):\n *\n * 1. its shape (`invalid_operation`), a section's `columns` in `unset` included;\n * 2. the blocks it names (`block_missing`, `block_exists`);\n * 3. locks (`lock_held`, `locked_by_others`);\n * 4. preconditions (`precondition_failed`);\n * 5. placement (`invalid_operation`): an illegal section or wrapper parent,\n * a descendant cycle, or a block after itself;\n * 6. the target container (`block_missing`, `invalid_operation`);\n * 7. the anchor (`anchor_missing`);\n * 8. the change itself (`invalid_operation`): a layout that drops non-empty columns.\n */\nexport function applyOperations(\n content: TemplateContent,\n ops: readonly Operation[],\n context: OperationContext = {},\n): TemplateContent {\n const draft = safeClone(content);\n applyOperationsInPlace(draft, ops, context);\n return draft;\n}\n\n/**\n * {@link applyOperations} without the copy: `content` itself changes. When an\n * operation throws, the ones before it have already applied, so use this only\n * on a draft you can throw away, or with operations known to apply.\n */\nexport function applyOperationsInPlace(\n content: TemplateContent,\n ops: readonly Operation[],\n context: OperationContext = {},\n): void {\n const engine: EngineContext = {\n locks: context.locks ?? [],\n session: context.session ?? null,\n };\n ops.forEach((op, index) => applyOne(content, op, index, engine));\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\ninterface EngineContext {\n locks: readonly OperationLock[];\n session: string | null;\n}\n\ntype Json = Record<string, unknown>;\n\ninterface Location {\n block: Json;\n /** The list the block sits in, changed in place. */\n list: unknown[];\n index: number;\n parent: BlockParent;\n}\n\nconst IMMUTABLE_KEYS: ReadonlySet<string> = new Set([\n \"id\",\n \"type\",\n \"children\",\n \"l10n\",\n]);\nconst SETTINGS_IMMUTABLE_KEYS: ReadonlySet<string> = new Set([\n \"locales\",\n \"l10n\",\n]);\nconst SETTINGS_LOCALE_IMMUTABLE_KEYS: ReadonlySet<string> = new Set([\n \"locale\",\n \"locales\",\n \"l10n\",\n]);\nconst FORBIDDEN_CUSTOM_TEXT_FIELDS_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\nconst CUSTOM_TEXT_FIELDS_ERROR =\n \"customTextFields must map existing custom block ids to lists of string fieldValues paths.\";\n\nfunction fail(\n code: OperationErrorCode,\n index: number,\n message: string,\n blockId?: string,\n): never {\n throw new OperationError(code, index, message, blockId);\n}\n\nfunction isRecord(value: unknown): value is Json {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isSection(block: Json): boolean {\n return block.type === \"section\";\n}\n\n/** The top-level blocks, read only: anything but a list reads as none. */\nfunction topLevelOf(content: TemplateContent): unknown[] {\n return Array.isArray(content.blocks) ? content.blocks : [];\n}\n\n/** A section's columns, read only: anything but a list reads as empty. */\nfunction columnsOf(section: Json): unknown[][] {\n const children = section.children;\n if (!Array.isArray(children)) return [];\n return children.map((column) => (Array.isArray(column) ? column : []));\n}\n\n/** Locations in document order, including children of wrappers and sections. */\nfunction* walkLocations(\n list: unknown[],\n parent: BlockParent,\n): Generator<Location> {\n for (let index = 0; index < list.length; index++) {\n const block = list[index];\n if (!isRecord(block)) continue;\n yield { block, list, index, parent };\n if (typeof block.id !== \"string\") continue;\n if (isSection(block)) {\n for (const [column, children] of columnsOf(block).entries()) {\n yield* walkLocations(children, { sectionId: block.id, column });\n }\n } else if (block.type === \"wrapper\" && Array.isArray(block.children)) {\n yield* walkLocations(block.children, { wrapperId: block.id });\n }\n }\n}\n\nfunction locate(content: TemplateContent, blockId: string): Location | null {\n for (const location of walkLocations(topLevelOf(content), null)) {\n if (location.block.id === blockId) return location;\n }\n return null;\n}\n\n/** A block's id and every descendant id, in document order. */\nexport function blockIdsOf(block: unknown): string[] {\n if (!isRecord(block)) return [];\n const ids = typeof block.id === \"string\" ? [block.id] : [];\n // One push per id: spreading a wide container's ids into push() passes them\n // as arguments and throws past the engine's argument limit.\n if (isSection(block)) {\n for (const column of columnsOf(block))\n for (const id of idsIn(column)) ids.push(id);\n } else if (block.type === \"wrapper\" && Array.isArray(block.children)) {\n for (const id of idsIn(block.children)) ids.push(id);\n }\n return ids;\n}\n\nfunction idsIn(blocks: readonly unknown[]): string[] {\n return blocks.flatMap(blockIdsOf);\n}\n\n// --- 1. Shape ----------------------------------------------------------------\n\nfunction readBlockId(op: Json, index: number): string {\n if (typeof op.blockId !== \"string\" || op.blockId === \"\") {\n return fail(\"invalid_operation\", index, \"blockId must be a block id.\");\n }\n return op.blockId;\n}\n\n/** `parent` is required: a root, section column, or wrapper child list. */\nfunction readParent(op: Json, index: number): BlockParent {\n const parent = op.parent;\n if (parent === null) return null;\n if (\n isRecord(parent) &&\n typeof parent.sectionId === \"string\" &&\n typeof parent.column === \"number\" &&\n Number.isInteger(parent.column)\n ) {\n return { sectionId: parent.sectionId, column: parent.column };\n }\n if (\n isRecord(parent) &&\n typeof parent.wrapperId === \"string\" &&\n parent.wrapperId !== \"\" &&\n !Object.hasOwn(parent, \"sectionId\") &&\n !Object.hasOwn(parent, \"column\")\n ) {\n return { wrapperId: parent.wrapperId };\n }\n return fail(\n \"invalid_operation\",\n index,\n 'parent must be null, { \"sectionId\", \"column\" }, or { \"wrapperId\" }.',\n );\n}\n\n/** `after` is required: `null`, or a block id. */\nfunction readAfter(op: Json, index: number): string | null {\n const after = op.after;\n if (after === null) return null;\n if (typeof after === \"string\" && after !== \"\") return after;\n return fail(\"invalid_operation\", index, \"after must be null or a block id.\");\n}\n\n/** `expect`, or `null` when it is absent or `null`. */\nfunction readExpect(op: Json, index: number): Json | null {\n const expect = op.expect;\n if (expect === undefined || expect === null) return null;\n if (isRecord(expect)) return expect;\n return fail(\"invalid_operation\", index, \"expect must be an object.\");\n}\n\n/**\n * `set` and `unset`, either absent or `null`, but not both empty. A key that\n * holds `undefined` isn't set: JSON drops it on the way to a server.\n */\nfunction readChanges(\n op: Json,\n index: number,\n immutable: ReadonlySet<string>,\n): { set: Json; unset: string[] } {\n const set = op.set ?? null;\n const unset = op.unset ?? [];\n if (\n (set !== null && !isRecord(set)) ||\n !Array.isArray(unset) ||\n !unset.every((key) => typeof key === \"string\")\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"set must be an object and unset a list of keys.\",\n );\n }\n const values = set === null ? {} : set;\n const keys = Object.keys(values).filter((key) => values[key] !== undefined);\n if (keys.length === 0 && unset.length === 0) {\n fail(\"invalid_operation\", index, \"Set or unset at least one key.\");\n }\n for (const key of [...keys, ...unset]) {\n if (immutable.has(key)) {\n fail(\"invalid_operation\", index, `\"${key}\" can't be set or unset.`);\n }\n }\n const clash = unset.find((key) => keys.includes(key));\n if (clash !== undefined) {\n fail(\"invalid_operation\", index, `\"${clash}\" is both set and unset.`);\n }\n return {\n set: Object.fromEntries(keys.map((key) => [key, values[key]])),\n unset: unset as string[],\n };\n}\n\n/**\n * A new block: a non-empty string id and a string type. A section has a list\n * of columns, each a list of such blocks, and sits only at the top level, so\n * no section goes into a column.\n */\nfunction assertNewBlock(\n block: unknown,\n index: number,\n placement: \"root\" | \"column\" | \"wrapper\",\n): asserts block is Json {\n if (\n !isRecord(block) ||\n typeof block.id !== \"string\" ||\n block.id === \"\" ||\n typeof block.type !== \"string\"\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"A block needs a non-empty string id and a string type.\",\n );\n }\n if (block.type === \"wrapper\") {\n if (placement !== \"root\") {\n fail(\n \"invalid_operation\",\n index,\n placement === \"column\"\n ? \"Wrappers can only be placed at the top level.\"\n : \"Wrappers cannot be placed inside wrappers.\",\n );\n }\n if (!Array.isArray(block.children)) {\n fail(\n \"invalid_operation\",\n index,\n \"A wrapper needs children: a list of blocks.\",\n );\n }\n for (const child of block.children) assertNewBlock(child, index, \"wrapper\");\n return;\n }\n if (!isSection(block)) return;\n if (placement === \"column\") {\n fail(\n \"invalid_operation\",\n index,\n \"Sections can only be placed at the top level.\",\n );\n }\n if (placement === \"wrapper\" && block.wrapper) {\n fail(\"invalid_operation\", index, SECTION_WRAPPER_IN_WRAPPER);\n }\n const columns = block.children;\n if (\n !Array.isArray(columns) ||\n !columns.every((column) => Array.isArray(column))\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"A section needs children: a list of columns, each a list of blocks.\",\n );\n }\n for (const column of columns as unknown[][]) {\n for (const child of column) assertNewBlock(child, index, \"column\");\n }\n}\n\n// --- 3. Locks ----------------------------------------------------------------\n\nfunction heldByOthers(engine: EngineContext, lock: OperationLock): boolean {\n return engine.session === null || lock.sessionId !== engine.session;\n}\n\nfunction assertUnlocked(\n engine: EngineContext,\n ids: readonly string[],\n index: number,\n): void {\n const held = engine.locks.find(\n (lock) => ids.includes(lock.blockId) && heldByOthers(engine, lock),\n );\n if (held) {\n fail(\n \"lock_held\",\n index,\n `Block \"${held.blockId}\" is being edited in another session.`,\n held.blockId,\n );\n }\n}\n\nfunction assertUnlockedLocale(\n engine: EngineContext,\n blockId: string,\n locale: string,\n index: number,\n): void {\n const held = engine.locks.find(\n (lock) =>\n heldByOthers(engine, lock) &&\n lock.blockId === blockId &&\n ((lock.locale ?? null) === null || lock.locale === locale),\n );\n if (held) {\n fail(\n \"lock_held\",\n index,\n `Block \"${blockId}\" is being edited in another session.`,\n blockId,\n );\n }\n}\n\n// --- 4. Preconditions --------------------------------------------------------\n\n/**\n * Each `expect` key against the current value, where an absent key reads as\n * `null`: an expected `null` matches `null` or absent. Values compare with\n * {@link deepEqual}.\n */\nfunction assertExpected(\n target: Json,\n expect: Json,\n index: number,\n blockId?: string,\n): void {\n for (const [key, expected] of Object.entries(expect)) {\n if (expected === undefined) continue;\n const current =\n Object.hasOwn(target, key) && target[key] !== undefined\n ? target[key]\n : null;\n if (!deepEqual(current, expected)) {\n fail(\n \"precondition_failed\",\n index,\n blockId === undefined\n ? `Setting \"${key}\" has changed since.`\n : `\"${key}\" of block \"${blockId}\" has changed since.`,\n blockId,\n );\n }\n }\n}\n\n// --- 6 and 7. Container and anchor --------------------------------------------\n\n/** The list a block goes into, changed in place. */\nfunction container(\n content: TemplateContent,\n parent: BlockParent,\n index: number,\n): unknown[] {\n if (parent === null) {\n if (!Array.isArray(content.blocks)) content.blocks = [];\n return content.blocks;\n }\n if (\"wrapperId\" in parent) {\n const found = locate(content, parent.wrapperId);\n if (!found) {\n return fail(\n \"block_missing\",\n index,\n `No wrapper with id \"${parent.wrapperId}\".`,\n parent.wrapperId,\n );\n }\n if (found.block.type !== \"wrapper\") {\n return fail(\n \"invalid_operation\",\n index,\n `Block \"${parent.wrapperId}\" isn't a wrapper.`,\n );\n }\n if (!Array.isArray(found.block.children)) {\n return fail(\n \"invalid_operation\",\n index,\n `Wrapper \"${parent.wrapperId}\" has no children list.`,\n );\n }\n return found.block.children;\n }\n const found = locate(content, parent.sectionId);\n if (!found) {\n return fail(\n \"block_missing\",\n index,\n `No section with id \"${parent.sectionId}\".`,\n parent.sectionId,\n );\n }\n if (!isSection(found.block)) {\n return fail(\n \"invalid_operation\",\n index,\n `Block \"${parent.sectionId}\" isn't a section.`,\n );\n }\n const children = found.block.children;\n if (\n !Array.isArray(children) ||\n parent.column < 0 ||\n parent.column >= children.length\n ) {\n return fail(\n \"invalid_operation\",\n index,\n `Section \"${parent.sectionId}\" has no column ${parent.column}.`,\n );\n }\n if (!Array.isArray(children[parent.column])) children[parent.column] = [];\n return children[parent.column] as unknown[];\n}\n\nfunction insertionIndex(\n list: readonly unknown[],\n after: string | null,\n index: number,\n): number {\n if (after === null) return 0;\n const position = list.findIndex(\n (sibling) => isRecord(sibling) && sibling.id === after,\n );\n if (position === -1) {\n return fail(\n \"anchor_missing\",\n index,\n `No block \"${after}\" in the target container.`,\n after,\n );\n }\n return position + 1;\n}\n\n// --- 8. The change -----------------------------------------------------------\n\n/** Grow with empty columns, or drop trailing columns that are already empty. */\nfunction resizeColumns(\n section: Json,\n layout: unknown,\n index: number,\n blockId: string,\n): void {\n const count = getColumnCount(layout);\n const columns: unknown[] = Array.isArray(section.children)\n ? section.children\n : [];\n for (let column = count; column < columns.length; column++) {\n const removed = columns[column];\n if (Array.isArray(removed) && removed.length > 0) {\n fail(\n \"invalid_operation\",\n index,\n `Column ${column} of section \"${blockId}\" still holds blocks, so the layout can't drop it.`,\n );\n }\n }\n const next = columns.slice(0, count);\n while (next.length < count) next.push([]);\n section.children = next;\n}\n\n/**\n * Set and unset top-level keys; a set value is a copy.\n *\n * Writes go through assignment and `delete`, never `Object.defineProperty`:\n * the editor applies remote batches in place to its reactive content, and a\n * Vue reactive proxy has no `defineProperty` trap, so a defined key changes\n * the object without re-rendering the block. `__proto__` is the one key that\n * needs `defineProperty`, because assigning it would replace the prototype.\n */\nfunction change(target: Json, set: Json, unset: readonly string[]): void {\n for (const [key, value] of Object.entries(set)) {\n if (key === \"__proto__\") {\n Object.defineProperty(target, key, {\n value: safeClone(value),\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n target[key] = safeClone(value);\n }\n }\n for (const key of unset) delete target[key];\n}\n\n/** Each element id containing \".\" or \"/\", with the id of the block that holds it. */\nfunction dottedElementIds(\n content: TemplateContent,\n): { id: string; blockId: string | undefined }[] {\n return elementIdIssues(content).map((issue) => {\n const blockPath = issue.path.replace(/\\.(items|icons|rows)\\[.*$/, \"\");\n const block = blockPath\n .replace(/\\[(\\d+)\\]/g, \".$1\")\n .split(\".\")\n .reduce<unknown>((value, key) => (value as Json)[key], content) as Json;\n return {\n id: issue.id,\n blockId: typeof block.id === \"string\" ? block.id : undefined,\n };\n });\n}\n\n/**\n * Refuse an element id containing \".\" or \"/\" that the operation introduces:\n * one `content` has and `before` doesn't have on the same block. Ids a\n * template already holds stay editable.\n */\nfunction assertElementIds(\n content: TemplateContent,\n index: number,\n before?: TemplateContent,\n): void {\n const key = ({ id, blockId }: { id: string; blockId?: string }) =>\n JSON.stringify([blockId ?? null, id]);\n const existing = new Set(before ? dottedElementIds(before).map(key) : []);\n const issue = dottedElementIds(content).find(\n (candidate) => !existing.has(key(candidate)),\n );\n if (!issue) return;\n fail(\n \"invalid_operation\",\n index,\n `Element id \"${issue.id}\" must not contain \".\" or \"/\".`,\n issue.blockId,\n );\n}\n\n// --- The operations ----------------------------------------------------------\n\nfunction applyOne(\n content: TemplateContent,\n raw: Operation,\n index: number,\n engine: EngineContext,\n): void {\n const op: unknown = raw;\n if (!isRecord(op) || typeof op.op !== \"string\") {\n fail(\n \"invalid_operation\",\n index,\n 'Each operation must be an object with an \"op\".',\n );\n }\n switch (op.op) {\n case \"addBlock\":\n return addBlock(content, op, index);\n case \"moveBlock\":\n return moveBlock(content, op, index, engine);\n case \"deleteBlock\":\n return deleteBlock(content, op, index, engine);\n case \"updateBlock\":\n return updateBlock(content, op, index, engine);\n case \"updateSettings\":\n return updateSettings(content, op, index);\n case \"setContent\":\n return setContent(content, op, index, engine);\n case \"setDefaultLocale\":\n return setDefaultLocale(content, op, index, engine);\n case \"addLocale\":\n return addLocale(content, op, index);\n case \"removeLocale\":\n return removeLocale(content, op, index);\n case \"updateBlockLocale\":\n return updateBlockLocale(content, op, index, engine);\n case \"updateSettingsLocale\":\n return updateSettingsLocale(content, op, index);\n default:\n fail(\"invalid_operation\", index, `Unknown operation \"${op.op}\".`);\n }\n}\n\nfunction addBlock(content: TemplateContent, op: Json, index: number): void {\n const parent = readParent(op, index);\n const after = readAfter(op, index);\n const block = op.block;\n assertNewBlock(\n block,\n index,\n parent === null ? \"root\" : \"wrapperId\" in parent ? \"wrapper\" : \"column\",\n );\n assertElementIds(\n { blocks: [block as unknown as Block], settings: content.settings },\n index,\n );\n\n const existing = new Set(idsIn(topLevelOf(content)));\n const seen = new Set<string>();\n for (const id of blockIdsOf(block)) {\n if (existing.has(id) || seen.has(id)) {\n fail(\n \"block_exists\",\n index,\n `A block with id \"${id}\" already exists.`,\n id,\n );\n }\n seen.add(id);\n }\n\n const list = container(content, parent, index);\n const position = insertionIndex(list, after, index);\n assertSlotPlacement(content, block, parent, index, true);\n list.splice(position, 0, safeClone(block));\n}\n\nfunction moveBlock(\n content: TemplateContent,\n op: Json,\n index: number,\n engine: EngineContext,\n): void {\n const blockId = readBlockId(op, index);\n const parent = readParent(op, index);\n const after = readAfter(op, index);\n const expect = readExpect(op, index);\n const expectedParent =\n expect && expect.parent !== undefined\n ? readParent({ parent: expect.parent }, index)\n : null;\n\n const location = locate(content, blockId);\n if (!location) {\n return fail(\n \"block_missing\",\n index,\n `No block with id \"${blockId}\".`,\n blockId,\n );\n }\n assertUnlocked(engine, blockIdsOf(location.block), index);\n if (expect) {\n const previous =\n location.index > 0 ? location.list[location.index - 1] : null;\n const currentAfter = isRecord(previous) ? (previous.id ?? null) : null;\n if (\n !deepEqual(location.parent, expectedParent) ||\n !deepEqual(currentAfter, expect.after ?? null)\n ) {\n fail(\n \"precondition_failed\",\n index,\n `Block \"${blockId}\" has moved since.`,\n blockId,\n );\n }\n }\n if (\n parent !== null &&\n (\"wrapperId\" in parent ? parent.wrapperId : parent.sectionId) === blockId\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"A block cannot be moved into itself or its descendants.\",\n );\n }\n if (\n parent !== null &&\n blockIdsOf(location.block).includes(\n \"wrapperId\" in parent ? parent.wrapperId : parent.sectionId,\n )\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"A block cannot be moved into itself or its descendants.\",\n );\n }\n if (isSection(location.block) && parent !== null && \"sectionId\" in parent) {\n fail(\n \"invalid_operation\",\n index,\n \"Sections can only be placed at the top level.\",\n );\n }\n if (\n isSection(location.block) &&\n location.block.wrapper &&\n parent !== null &&\n \"wrapperId\" in parent\n ) {\n fail(\"invalid_operation\", index, SECTION_WRAPPER_IN_WRAPPER);\n }\n if (location.block.type === \"wrapper\" && parent !== null) {\n fail(\n \"invalid_operation\",\n index,\n \"wrapperId\" in parent\n ? \"Wrappers cannot be placed inside wrappers.\"\n : \"Wrappers can only be placed at the top level.\",\n );\n }\n if (after === blockId) {\n fail(\"invalid_operation\", index, \"A block can't be placed after itself.\");\n }\n\n // The target is resolved before the block leaves its place, so a missing or\n // wrong parent is reported as such. It is a live list: when it is also the\n // block's own list, the anchor is looked up without the moved block.\n const target = container(content, parent, index);\n // The anchor, then the change, are checked before anything moves.\n insertionIndex(\n target.filter((sibling) => sibling !== location.block),\n after,\n index,\n );\n assertSlotPlacement(content, location.block, parent, index, false);\n location.list.splice(location.index, 1);\n target.splice(insertionIndex(target, after, index), 0, location.block);\n}\n\nfunction deleteBlock(\n content: TemplateContent,\n op: Json,\n index: number,\n engine: EngineContext,\n): void {\n const blockId = readBlockId(op, index);\n const expect = readExpect(op, index);\n\n const location = locate(content, blockId);\n if (!location) {\n return fail(\n \"block_missing\",\n index,\n `No block with id \"${blockId}\".`,\n blockId,\n );\n }\n assertUnlocked(engine, blockIdsOf(location.block), index);\n if (expect && !deepEqual(location.block, expect.block ?? null)) {\n fail(\n \"precondition_failed\",\n index,\n `Block \"${blockId}\" has changed since.`,\n blockId,\n );\n }\n location.list.splice(location.index, 1);\n}\n\nfunction updateBlock(\n content: TemplateContent,\n op: Json,\n index: number,\n engine: EngineContext,\n): void {\n const blockId = readBlockId(op, index);\n const { set, unset } = readChanges(op, index, IMMUTABLE_KEYS);\n const expect = readExpect(op, index);\n\n const location = locate(content, blockId);\n if (!location) {\n return fail(\n \"block_missing\",\n index,\n `No block with id \"${blockId}\".`,\n blockId,\n );\n }\n const block = location.block;\n const section = isSection(block);\n // Shape, but only knowable once the block is found: a section keeps its layout.\n if (section && unset.includes(\"columns\")) {\n fail(\n \"invalid_operation\",\n index,\n \"A section's columns can't be unset; set another layout instead.\",\n );\n }\n assertUnlocked(engine, [blockId], index);\n if (expect) assertExpected(block, expect, index, blockId);\n if (\n section &&\n location.parent !== null &&\n \"wrapperId\" in location.parent &&\n set.wrapper\n ) {\n fail(\"invalid_operation\", index, SECTION_WRAPPER_IN_WRAPPER);\n }\n const next = { ...block };\n change(next, set, unset);\n assertElementIds(\n { blocks: [next as unknown as Block], settings: content.settings },\n index,\n { blocks: [block as unknown as Block], settings: content.settings },\n );\n if (section && Object.hasOwn(set, \"columns\")) {\n resizeColumns(block, set.columns, index, blockId);\n }\n change(block, set, unset);\n const pruned = pruneLocaleOrphans(block as unknown as Block);\n if (!deepEqual(block.l10n, pruned.l10n)) {\n if (pruned.l10n) block.l10n = pruned.l10n;\n else delete block.l10n;\n }\n if (\n (section || block.type === \"wrapper\") &&\n !deepEqual(block.children, (pruned as unknown as Json).children)\n )\n block.children = (pruned as unknown as Json).children;\n}\n\nfunction updateSettings(\n content: TemplateContent,\n op: Json,\n index: number,\n): void {\n const { set, unset } = readChanges(op, index, SETTINGS_IMMUTABLE_KEYS);\n const expect = readExpect(op, index);\n if (\n content.settings?.locales?.length &&\n (Object.hasOwn(set, \"locale\") || unset.includes(\"locale\"))\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"The default locale can't change while language versions exist.\",\n );\n }\n if (!isRecord(content.settings)) {\n content.settings = {} as TemplateSettings;\n }\n const settings = content.settings as unknown as Json;\n if (expect) assertExpected(settings, expect, index);\n change(settings, set, unset);\n const pruned = pruneSettingsLocaleOrphans(content.settings);\n if (!deepEqual(settings.l10n, pruned.l10n)) {\n if (pruned.l10n) settings.l10n = pruned.l10n;\n else delete settings.l10n;\n }\n}\n\nfunction readLocale(op: Json, index: number): string {\n const locale = op.locale;\n // A language tag can't be a prototype key; the explicit check keeps one out\n // of every layer map whatever isLocaleTag accepts.\n if (\n !isLocaleTag(locale) ||\n locale === \"__proto__\" ||\n locale === \"constructor\" ||\n locale === \"prototype\"\n ) {\n fail(\"invalid_operation\", index, \"locale must be a language tag.\");\n }\n return locale;\n}\n\nfunction requireLocale(\n content: TemplateContent,\n op: Json,\n index: number,\n): string {\n const locale = readLocale(op, index);\n if (!content.settings.locales?.includes(locale)) {\n fail(\n \"invalid_operation\",\n index,\n `Locale \"${locale}\" isn't in settings.locales.`,\n );\n }\n return locale;\n}\n\nfunction addLocale(content: TemplateContent, op: Json, index: number): void {\n const locale = readLocale(op, index);\n const locales = content.settings.locales ?? [];\n const folded = locale.toLowerCase();\n const position = op.position === undefined ? locales.length : op.position;\n if (\n defaultLocaleOf(content).toLowerCase() === folded ||\n locales.some((tag) => tag.toLowerCase() === folded) ||\n typeof position !== \"number\" ||\n !Number.isInteger(position) ||\n position < 0 ||\n position > locales.length\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"The locale already exists or its insertion position is invalid.\",\n );\n }\n if (!content.settings.locales) content.settings.locales = [];\n content.settings.locales.splice(position, 0, locale);\n}\n\nfunction blocksIn(blocks: readonly unknown[]): Json[] {\n return blocks.flatMap((block) =>\n isRecord(block)\n ? [\n block,\n ...(isSection(block)\n ? columnsOf(block).flatMap(blocksIn)\n : block.type === \"wrapper\" && Array.isArray(block.children)\n ? blocksIn(block.children)\n : []),\n ]\n : [],\n );\n}\n\nfunction localeLayer(target: Json, locale: string): BlockLocaleLayer {\n const l10n = target.l10n;\n return isRecord(l10n) && isRecord(l10n[locale]) ? l10n[locale] : {};\n}\n\nfunction removeLocale(content: TemplateContent, op: Json, index: number): void {\n const locale = requireLocale(content, op, index);\n const expect = readExpect(op, index);\n if (\n expect &&\n (!isRecord(expect.blocks) ||\n (expect.settings !== undefined && !isRecord(expect.settings)))\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"expect needs a blocks object and an optional settings layer.\",\n );\n }\n const settings = content.settings as unknown as Json;\n const blocks = blocksIn(topLevelOf(content));\n const layers = Object.fromEntries(\n blocks.flatMap((target) =>\n isRecord(target.l10n) && Object.hasOwn(target.l10n, locale)\n ? [[String(target.id), target.l10n[locale]]]\n : [],\n ),\n );\n if (\n expect &&\n (!deepEqual(layers, expect.blocks) ||\n !deepEqual(\n isRecord(settings.l10n) ? settings.l10n[locale] : undefined,\n expect.settings,\n ))\n ) {\n fail(\"precondition_failed\", index, `Locale \"${locale}\" has changed since.`);\n }\n for (const target of [...blocks, settings]) {\n if (!isRecord(target.l10n)) continue;\n delete target.l10n[locale];\n if (Object.keys(target.l10n).length === 0) delete target.l10n;\n }\n content.settings.locales!.splice(\n content.settings.locales!.indexOf(locale),\n 1,\n );\n if (content.settings.locales!.length === 0) delete content.settings.locales;\n}\n\ninterface LocaleChanges {\n text: Record<string, LocalizedText>;\n set: Json;\n unset: string[];\n hidden?: boolean;\n expect: Json | null;\n}\n\nfunction readLocaleChanges(\n op: Json,\n index: number,\n settings: boolean,\n): LocaleChanges {\n const validText = (value: unknown): boolean =>\n isRecord(value) &&\n Object.values(value).every(\n (entry) =>\n isRecord(entry) &&\n typeof entry.value === \"string\" &&\n typeof entry.sourceHash === \"string\",\n );\n if (\n (op.text !== undefined && !validText(op.text)) ||\n (op.set !== undefined &&\n (!isRecord(op.set) ||\n Object.values(op.set).some((value) => value === undefined))) ||\n (op.unset !== undefined &&\n (!Array.isArray(op.unset) ||\n !op.unset.every(\n (path) => typeof path === \"string\" && path !== \"\" && isSafePath(path),\n ))) ||\n (op.hidden !== undefined && (settings || typeof op.hidden !== \"boolean\")) ||\n ![\"text\", \"set\", \"unset\", ...(settings ? [] : [\"hidden\"])].some(\n (key) => op[key] !== undefined,\n )\n ) {\n fail(\n \"invalid_operation\",\n index,\n \"A locale update needs text, set, unset or a block's boolean hidden.\",\n );\n }\n const expect = readExpect(op, index);\n if (\n expect &&\n ((expect.text !== undefined && !isRecord(expect.text)) ||\n (expect.set !== undefined && !isRecord(expect.set)) ||\n (expect.hidden !== undefined &&\n (settings || typeof expect.hidden !== \"boolean\")))\n ) {\n fail(\"invalid_operation\", index, \"The locale layer expect is malformed.\");\n }\n return {\n text: (op.text ?? {}) as Record<string, LocalizedText>,\n set: (op.set ?? {}) as Json,\n unset: (op.unset ?? []) as string[],\n hidden: op.hidden as boolean | undefined,\n expect,\n };\n}\n\nfunction assertLocalePaths(\n target: Json,\n changes: LocaleChanges,\n index: number,\n settings: boolean,\n): void {\n for (const path of Object.keys(changes.text)) {\n if (\n !isSafePath(path) ||\n !(settings\n ? SETTINGS_TRANSLATABLE_FIELDS.includes(path)\n : isTranslatablePath(String(target.type), path)) ||\n readPath(target, path) === undefined\n ) {\n fail(\n \"invalid_operation\",\n index,\n `Text path \"${path}\" isn't translatable or doesn't resolve.`,\n );\n }\n }\n for (const path of Object.keys(changes.set)) {\n const segments = path.split(\".\");\n const immutable = settings\n ? SETTINGS_LOCALE_IMMUTABLE_KEYS\n : IMMUTABLE_KEYS;\n const parent =\n segments.length === 1\n ? target\n : readPath(target, segments.slice(0, -1).join(\".\"));\n if (\n !isSafePath(path) ||\n immutable.has(segments[0]) ||\n (!settings &&\n isStructuralLocalePath(\n target as unknown as Block,\n path,\n changes.set[path],\n )) ||\n (readPath(target, path) === undefined && !isRecord(parent))\n ) {\n fail(\n \"invalid_operation\",\n index,\n `Override path \"${path}\" is immutable or doesn't resolve.`,\n );\n }\n }\n}\n\nfunction assertLocaleExpected(\n layer: BlockLocaleLayer,\n expect: Json | null,\n index: number,\n blockId?: string,\n): void {\n if (!expect) return;\n for (const kind of [\"text\", \"set\"] as const) {\n for (const [path, expected] of Object.entries(\n (expect[kind] ?? {}) as Json,\n )) {\n if (!deepEqual(layer[kind]?.[path] ?? null, expected)) {\n fail(\n \"precondition_failed\",\n index,\n `Locale path \"${path}\" has changed since.`,\n blockId,\n );\n }\n }\n }\n if (\n expect.hidden !== undefined &&\n !deepEqual(layer.hidden === true, expect.hidden)\n ) {\n fail(\n \"precondition_failed\",\n index,\n \"The locale's hidden state has changed since.\",\n blockId,\n );\n }\n}\n\nfunction changeLocale(\n target: Json,\n locale: string,\n changes: LocaleChanges,\n): void {\n if (!isRecord(target.l10n)) target.l10n = {};\n const l10n = target.l10n as Record<string, BlockLocaleLayer>;\n if (!isRecord(l10n[locale])) l10n[locale] = {};\n const layer = l10n[locale];\n for (const path of changes.unset) {\n if (layer.text) delete layer.text[path];\n if (layer.set) delete layer.set[path];\n }\n for (const [path, value] of Object.entries(changes.text)) {\n if (!layer.text) layer.text = {};\n layer.text[path] = safeClone(value);\n if (layer.set) delete layer.set[path];\n }\n for (const [path, value] of Object.entries(changes.set)) {\n if (!layer.set) layer.set = {};\n layer.set[path] = safeClone(value);\n if (layer.text) delete layer.text[path];\n }\n if (changes.hidden === true) layer.hidden = true;\n else if (changes.hidden === false) delete layer.hidden;\n if (layer.text && Object.keys(layer.text).length === 0) delete layer.text;\n if (layer.set && Object.keys(layer.set).length === 0) delete layer.set;\n if (Object.keys(layer).length === 0) delete l10n[locale];\n if (Object.keys(l10n).length === 0) delete target.l10n;\n}\n\n/** True for a layout's slot block and for any block that contains it. */\nfunction holdsSlot(block: unknown): boolean {\n if (!isRecord(block)) return false;\n if (block.type === \"slot\") return true;\n return (\n Array.isArray(block.children) &&\n block.children.some((child) =>\n Array.isArray(child) ? child.some(holdsSlot) : holdsSlot(child),\n )\n );\n}\n\n/** Whether any language's layer hides `block`. */\nfunction hiddenInALanguage(block: unknown): boolean {\n return (\n isRecord(block) &&\n isRecord(block.l10n) &&\n Object.values(block.l10n).some(\n (layer) => isRecord(layer) && layer.hidden === true,\n )\n );\n}\n\n/** True when a language hides the slot inside `block`: it, or a block between them. */\nfunction hidesSlot(block: unknown): boolean {\n if (!isRecord(block) || !holdsSlot(block)) return false;\n if (hiddenInALanguage(block)) return true;\n return (\n Array.isArray(block.children) &&\n block.children.some((child) =>\n Array.isArray(child) ? child.some(hidesSlot) : hidesSlot(child),\n )\n );\n}\n\n/**\n * Refuse placing `block` where a language would hide the slot it holds: under\n * any ancestor hidden in a language, or with a hidden block on the way.\n */\nfunction assertSlotPlacement(\n content: TemplateContent,\n block: unknown,\n parent: BlockParent,\n index: number,\n ownLayers: boolean,\n): void {\n if (!holdsSlot(block)) return;\n let ancestor = parent;\n let hidden = false;\n while (ancestor !== null) {\n const id =\n \"wrapperId\" in ancestor ? ancestor.wrapperId : ancestor.sectionId;\n const found = locate(content, id);\n if (!found) break;\n if (hiddenInALanguage(found.block)) hidden = true;\n ancestor = found.parent;\n }\n if (hidden || (ownLayers && hidesSlot(block)))\n fail(\n \"invalid_operation\",\n index,\n \"A layout's slot block can't be placed inside a block that a language hides.\",\n isRecord(block) && typeof block.id === \"string\" ? block.id : undefined,\n );\n}\n\nfunction updateBlockLocale(\n content: TemplateContent,\n op: Json,\n index: number,\n engine: EngineContext,\n): void {\n const locale = requireLocale(content, op, index);\n const blockId = readBlockId(op, index);\n const changes = readLocaleChanges(op, index, false);\n const block = blocksIn(topLevelOf(content)).find(\n (block) => block.id === blockId,\n );\n if (!block)\n fail(\"block_missing\", index, `No block with id \"${blockId}\".`, blockId);\n assertLocalePaths(block, changes, index, false);\n assertUnlockedLocale(engine, blockId, locale, index);\n assertLocaleExpected(\n localeLayer(block, locale),\n changes.expect,\n index,\n blockId,\n );\n // Without its slot, a layout can't compose that language at all.\n if (changes.hidden === true && holdsSlot(block))\n fail(\n \"invalid_operation\",\n index,\n \"A layout's slot block, and any block that contains it, can't be hidden.\",\n blockId,\n );\n changeLocale(block, locale, changes);\n}\n\nfunction updateSettingsLocale(\n content: TemplateContent,\n op: Json,\n index: number,\n): void {\n const locale = requireLocale(content, op, index);\n const changes = readLocaleChanges(op, index, true);\n const settings = content.settings as unknown as Json;\n assertLocalePaths(settings, changes, index, true);\n assertLocaleExpected(localeLayer(settings, locale), changes.expect, index);\n changeLocale(settings, locale, changes);\n}\n\nfunction setContent(\n content: TemplateContent,\n op: Json,\n index: number,\n engine: EngineContext,\n): void {\n const next = op.content;\n if (\n !isRecord(next) ||\n !Array.isArray(next.blocks) ||\n !isRecord(next.settings)\n ) {\n return fail(\n \"invalid_operation\",\n index,\n \"setContent needs content with a blocks array and a settings object.\",\n );\n }\n assertElementIds(next as unknown as TemplateContent, index, content);\n const held = engine.locks.find((lock) => heldByOthers(engine, lock));\n if (held) {\n fail(\n \"locked_by_others\",\n index,\n \"Other sessions hold locks on this template.\",\n held.blockId,\n );\n }\n content.blocks = safeClone(next.blocks) as Block[];\n content.settings = safeClone(next.settings) as unknown as TemplateSettings;\n}\n\nfunction setDefaultLocale(\n content: TemplateContent,\n op: Json,\n index: number,\n engine: EngineContext,\n): void {\n const locale = readLocale(op, index);\n if (!content.settings.locales?.includes(locale))\n fail(\n \"invalid_operation\",\n index,\n `\"${locale}\" is not a language version of this template.`,\n );\n const hidden = localeHiddenBlocks(content, locale);\n if (hidden.length)\n fail(\n \"invalid_operation\",\n index,\n hidden.length === 1\n ? `1 block is hidden in \"${locale}\". Show it before making it the default.`\n : `${hidden.length} blocks are hidden in \"${locale}\". Show them before making it the default.`,\n hidden[0],\n );\n const held = engine.locks.find((lock) => heldByOthers(engine, lock));\n if (held)\n fail(\n \"locked_by_others\",\n index,\n \"Other sessions hold locks on this template.\",\n held.blockId,\n );\n const customTextFields = op.customTextFields;\n if (customTextFields !== undefined) {\n const blocks = blocksIn(content.blocks);\n if (\n !isRecord(customTextFields) ||\n Object.getOwnPropertyNames(customTextFields).some((id) => {\n if (FORBIDDEN_CUSTOM_TEXT_FIELDS_KEYS.has(id)) return true;\n const paths = customTextFields[id];\n const block = blocks.find((candidate) => candidate.id === id);\n return (\n block?.type !== \"custom\" ||\n !Array.isArray(paths) ||\n paths.some(\n (path) =>\n typeof path !== \"string\" ||\n !isSafePath(path) ||\n !isTranslatablePath(\"custom\", path) ||\n typeof readPath(block, path) !== \"string\",\n )\n );\n })\n )\n fail(\"invalid_operation\", index, CUSTOM_TEXT_FIELDS_ERROR);\n }\n const next = rebaseDefaultLocale(\n content,\n locale,\n op.customTextFields as Record<string, string[]> | undefined,\n );\n content.blocks = next.blocks;\n content.settings = next.settings;\n}\n","import type { Block } from \"./blocks\";\nimport { safeClone } from \"./clone\";\nimport type { BlockLocaleLayer, LocalizedText } from \"./localization\";\nimport {\n applyOperationsInPlace,\n OperationError,\n type BlockParent,\n type Operation,\n type LocaleLayerExpect,\n type UpdateBlockLocaleOperation,\n type UpdateSettingsLocaleOperation,\n} from \"./operations\";\nimport type { TemplateContent } from \"./template\";\n\ntype Json = Record<string, unknown>;\n\ninterface Position {\n block: Block;\n parent: BlockParent;\n /** The previous sibling's id, or `null` when the block is first. */\n after: string | null;\n}\n\nfunction columnsOf(block: Block): Block[][] {\n const children = (block as { children?: unknown }).children;\n return block.type === \"section\" && Array.isArray(children)\n ? (children as Block[][])\n : [];\n}\n\nfunction positionOf(\n blocks: Block[],\n blockId: string,\n parent: BlockParent = null,\n): Position | null {\n for (let index = 0; index < blocks.length; index++) {\n const block = blocks[index];\n if (block.id === blockId) {\n return { block, parent, after: index > 0 ? blocks[index - 1].id : null };\n }\n const columns = columnsOf(block);\n for (let column = 0; column < columns.length; column++) {\n if (!Array.isArray(columns[column])) continue;\n const found = positionOf(columns[column], blockId, {\n sectionId: block.id,\n column,\n });\n if (found) return found;\n }\n if (block.type === \"wrapper\" && Array.isArray(block.children)) {\n const found = positionOf(block.children, blockId, {\n wrapperId: block.id,\n });\n if (found) return found;\n }\n }\n return null;\n}\n\nfunction requirePosition(\n state: TemplateContent,\n blockId: string,\n index: number,\n): Position {\n const position = positionOf(state.blocks, blockId);\n if (!position) {\n throw new OperationError(\n \"block_missing\",\n index,\n `No block with id \"${blockId}\".`,\n blockId,\n );\n }\n return position;\n}\n\n/** Put back the keys an update touched, expecting what the update left. */\nfunction restoreKeys(\n current: Json,\n set: Json | undefined,\n unset: readonly string[] | undefined,\n): { set: Json; unset: string[]; expect: Json } {\n const restore: Json = {};\n const remove: string[] = [];\n const expect: Json = {};\n const keys = [...new Set([...Object.keys(set ?? {}), ...(unset ?? [])])];\n for (const key of keys) {\n const previous = current[key];\n if (previous === undefined) remove.push(key);\n else restore[key] = safeClone(previous);\n const next = set && key in set ? set[key] : undefined;\n expect[key] = next === undefined ? null : safeClone(next);\n }\n return { set: restore, unset: remove, expect };\n}\n\nfunction layerOf(\n target: { l10n?: Record<string, BlockLocaleLayer> },\n locale: string,\n): BlockLocaleLayer {\n return target.l10n?.[locale] ?? {};\n}\n\nfunction restoreLocale(\n previous: BlockLocaleLayer,\n next: BlockLocaleLayer,\n paths: string[],\n hidden: boolean,\n): {\n unset: string[];\n text?: Record<string, LocalizedText>;\n set?: Json;\n hidden?: boolean;\n expect: LocaleLayerExpect;\n} {\n const text: Record<string, LocalizedText> = {};\n const set: Json = {};\n const expect: LocaleLayerExpect = {};\n if (paths.length) {\n expect.text = {};\n expect.set = {};\n }\n for (const path of paths) {\n if (previous.text?.[path] !== undefined)\n text[path] = safeClone(previous.text[path]);\n if (previous.set && Object.hasOwn(previous.set, path))\n set[path] = safeClone(previous.set[path]);\n expect.text![path] = safeClone(next.text?.[path] ?? null);\n expect.set![path] = safeClone(next.set?.[path] ?? null);\n }\n if (hidden) expect.hidden = next.hidden === true;\n return {\n unset: paths,\n ...(Object.keys(text).length ? { text } : {}),\n ...(Object.keys(set).length ? { set } : {}),\n ...(hidden ? { hidden: previous.hidden === true } : {}),\n expect,\n };\n}\n\nfunction restoreRemovedLayer(\n layer: BlockLocaleLayer,\n): Omit<UpdateBlockLocaleOperation, \"op\" | \"blockId\" | \"locale\"> {\n const paths = [\n ...new Set([\n ...Object.keys(layer.text ?? {}),\n ...Object.keys(layer.set ?? {}),\n ]),\n ];\n const restored = restoreLocale(layer, {}, paths, layer.hidden === true);\n const { unset: _unset, ...changes } = restored;\n return changes;\n}\n\nfunction blocksIn(blocks: Block[]): Block[] {\n return blocks.flatMap((block) => [\n block,\n ...(block.type === \"wrapper\"\n ? blocksIn(block.children)\n : columnsOf(block).flatMap(blocksIn)),\n ]);\n}\n\n/** Restore paths lost to base pruning only after the base keys exist again. */\nfunction restorePrunedLayers(\n state: TemplateContent,\n op: Operation,\n): Operation[] {\n const next = safeClone(state);\n applyOperationsInPlace(next, [op]);\n const restores: Operation[] = [];\n const collect = (\n previous: { l10n?: Record<string, BlockLocaleLayer> },\n after: { l10n?: Record<string, BlockLocaleLayer> },\n blockId?: string,\n ) => {\n for (const [locale, layer] of Object.entries(previous.l10n ?? {})) {\n const current = after.l10n?.[locale] ?? {};\n const paths = [\n ...new Set([\n ...Object.keys(layer.text ?? {}).filter(\n (path) => !Object.hasOwn(current.text ?? {}, path),\n ),\n ...Object.keys(layer.set ?? {}).filter(\n (path) => !Object.hasOwn(current.set ?? {}, path),\n ),\n ]),\n ];\n if (!paths.length) continue;\n const changes = restoreLocale(layer, current, paths, false);\n restores.push(\n blockId === undefined\n ? ({\n op: \"updateSettingsLocale\",\n locale,\n ...changes,\n } as UpdateSettingsLocaleOperation)\n : { op: \"updateBlockLocale\", blockId, locale, ...changes },\n );\n }\n };\n if (op.op === \"updateSettings\") collect(state.settings, next.settings);\n else {\n const after = new Map(\n blocksIn(next.blocks).map((block) => [block.id, block]),\n );\n for (const block of blocksIn(state.blocks)) {\n const current = after.get(block.id);\n if (current) collect(block, current, block.id);\n }\n }\n return restores;\n}\n\nfunction invertOne(\n state: TemplateContent,\n op: Operation,\n index: number,\n): Operation | Operation[] {\n switch (op.op) {\n case \"addBlock\":\n return {\n op: \"deleteBlock\",\n blockId: op.block.id,\n expect: { block: safeClone(op.block) },\n };\n case \"deleteBlock\": {\n const position = requirePosition(state, op.blockId, index);\n return {\n op: \"addBlock\",\n block: safeClone(position.block),\n parent: position.parent,\n after: position.after,\n };\n }\n case \"moveBlock\": {\n const position = requirePosition(state, op.blockId, index);\n return {\n op: \"moveBlock\",\n blockId: op.blockId,\n parent: position.parent,\n after: position.after,\n expect: { parent: op.parent, after: op.after },\n };\n }\n case \"updateBlock\": {\n const block = requirePosition(state, op.blockId, index)\n .block as unknown as Json;\n const { set, unset, expect } = restoreKeys(block, op.set, op.unset);\n return [\n {\n op: \"updateBlock\",\n blockId: op.blockId,\n ...(Object.keys(set).length > 0 ? { set } : {}),\n ...(unset.length > 0 ? { unset } : {}),\n expect,\n },\n ...restorePrunedLayers(state, op),\n ];\n }\n case \"updateSettings\": {\n const { set, unset, expect } = restoreKeys(\n state.settings as unknown as Json,\n op.set as Json | undefined,\n op.unset,\n );\n return [\n {\n op: \"updateSettings\",\n ...(Object.keys(set).length > 0 ? { set } : {}),\n ...(unset.length > 0 ? { unset } : {}),\n expect,\n },\n ...restorePrunedLayers(state, op),\n ];\n }\n case \"addLocale\":\n return { op: \"removeLocale\", locale: op.locale, expect: { blocks: {} } };\n case \"removeLocale\": {\n const inverse: Operation[] = [\n {\n op: \"addLocale\",\n locale: op.locale,\n position: state.settings.locales?.indexOf(op.locale),\n },\n ];\n for (const block of blocksIn(state.blocks)) {\n const layer = block.l10n?.[op.locale];\n if (layer)\n inverse.push({\n op: \"updateBlockLocale\",\n blockId: block.id,\n locale: op.locale,\n ...restoreRemovedLayer(layer),\n });\n }\n const layer = state.settings.l10n?.[op.locale];\n if (layer) {\n const { hidden: _hidden, ...changes } = restoreRemovedLayer(layer);\n inverse.push({\n op: \"updateSettingsLocale\",\n locale: op.locale,\n ...changes,\n });\n }\n return inverse;\n }\n case \"updateBlockLocale\":\n case \"updateSettingsLocale\": {\n const next = safeClone(state);\n applyOperationsInPlace(next, [op]);\n const paths = [\n ...new Set([\n ...Object.keys(op.text ?? {}),\n ...Object.keys(op.set ?? {}),\n ...(op.unset ?? []),\n ]),\n ];\n if (op.op === \"updateBlockLocale\") {\n const previous = blocksIn(state.blocks).find(\n (block) => block.id === op.blockId,\n )!;\n const after = blocksIn(next.blocks).find(\n (block) => block.id === op.blockId,\n )!;\n return {\n op: \"updateBlockLocale\",\n blockId: op.blockId,\n locale: op.locale,\n ...restoreLocale(\n layerOf(previous, op.locale),\n layerOf(after, op.locale),\n paths,\n op.hidden !== undefined,\n ),\n };\n }\n const { hidden: _hidden, ...changes } = restoreLocale(\n layerOf(state.settings, op.locale),\n layerOf(next.settings, op.locale),\n paths,\n false,\n );\n return {\n op: \"updateSettingsLocale\",\n locale: op.locale,\n ...changes,\n } as UpdateSettingsLocaleOperation;\n }\n case \"setDefaultLocale\":\n case \"setContent\":\n return {\n op: \"setContent\",\n content: {\n blocks: safeClone(state.blocks),\n settings: safeClone(state.settings),\n },\n };\n }\n}\n\n/**\n * The batch that undoes `ops`, given the content they apply to. Each operation\n * is inverted against the content just before it, and the inverses run in\n * reverse order.\n *\n * Every inverse that can be guarded is: it expects what its operation left\n * behind, so an undo that a later edit by someone else has overtaken is refused\n * (`precondition_failed`, `anchor_missing`, `block_missing`) instead of\n * overwriting that edit. `setContent` and `setDefaultLocale` restore snapshots\n * without a guard of their own: the backend's `locked_by_others` rule stops\n * them while others hold locks, and the collaboration controller skips such a\n * step once another session's batch has changed the content it applies to.\n *\n * Throws the engine's `OperationError` when `ops` don't apply to `before`.\n */\nexport function invertOperations(\n before: TemplateContent,\n ops: readonly Operation[],\n): Operation[] {\n const state = safeClone(before);\n const inverses: Operation[] = [];\n ops.forEach((op, index) => {\n try {\n const inverse = invertOne(state, op, index);\n inverses.push(\n ...(Array.isArray(inverse) ? [...inverse].reverse() : [inverse]),\n );\n applyOperationsInPlace(state, [op]);\n } catch (error) {\n if (!(error instanceof OperationError)) throw error;\n // Applied one at a time, so the engine numbers it 0: give it its index.\n throw new OperationError(error.code, index, error.message, error.blockId);\n }\n });\n return inverses.reverse();\n}\n","import { SdkError } from \"./config\";\nimport type { Operation, OperationErrorCode } from \"./operations\";\n\n/** A batch an editor submits. */\nexport interface OperationBatch {\n /** A UUID the editor generates; resubmitting the same id applies it once. */\n batchId: string;\n /** The last revision the editor had confirmed when it sent the batch. */\n baseRevision: number;\n /** 1–100 operations, applied in order and all or nothing. */\n ops: Operation[];\n /**\n * `\"ai\"` when an AI turn produced the batch: the editor applied the\n * operations an `AiProvider` handed it. A backend may broadcast the batch\n * with `actor.type: \"ai\"` (the same user and session), and the other\n * editors then name it \"AI (for Ada)\". Absent on every other batch.\n */\n origin?: \"ai\";\n}\n\n/** Who made a change. */\nexport interface CollaborationActor {\n type: \"user\" | \"guest\" | \"mcp\" | \"api\" | \"ai\";\n /**\n * The user id, `guest:{sessionId}` for a guest, `null` for `api`. For `mcp`,\n * the id of the user the agent acts for; for `ai`, of the user who asked.\n */\n id: string | null;\n /** For `mcp` and `ai`, the name of the user the agent or the AI acts for. */\n name: string;\n /**\n * `null` when no editor session made the change (`api`, `mcp`). For `ai`,\n * the session that asked: that editor shows the outline and no notice.\n */\n sessionId: string | null;\n /**\n * For `mcp` only: the agent's name (`Claude`, `Cursor`, …). The editor names\n * it in the notice it shows for the batch (\"Claude for Ada changed 3\n * blocks\"), as text. A backend that lets agents edit sends it with every\n * agent batch, broadcast and catch-up alike.\n */\n client?: string;\n}\n\n/** A batch as the backend applied it, at the revision it produced. */\nexport interface RevisionedBatch {\n revision: number;\n batchId: string;\n actor: CollaborationActor;\n ops: Operation[];\n createdAt?: string;\n}\n\n/** One editor session with the template open. */\nexport interface CollaborationMember {\n sessionId: string;\n /** `null` for a guest. */\n userId: string | null;\n name: string;\n type: \"user\" | \"guest\";\n avatarUrl?: string;\n /** A CSS colour the backend picks, so it is the same on every screen. */\n color: string;\n}\n\n/** Who holds a lock. */\nexport interface BlockLockHolder {\n sessionId: string;\n type: \"user\" | \"guest\" | \"mcp\";\n /** The user id, or `guest:{sessionId}`. */\n id: string;\n name: string;\n color: string;\n}\n\n/** A block one session holds. */\nexport interface BlockLock {\n blockId: string;\n /** The language held; absent or `null` holds the default language and structure. */\n locale?: string | null;\n holder: BlockLockHolder;\n /**\n * ISO 8601. Renewals aren't broadcast, so another session's lock is dropped\n * when it is released or its session leaves, never by this time.\n */\n expiresAt: string;\n}\n\n/** Why a backend refused a batch or a lock. */\nexport type CollaborationConflictCode =\n OperationErrorCode | \"lock_lost\" | \"content_too_large\";\n\nfunction defaultStatus(code: CollaborationConflictCode): number {\n if (code === \"invalid_operation\") return 422;\n if (code === \"content_too_large\") return 413;\n return 409;\n}\n\n/**\n * A refusal from a collaboration backend. `submit` rejects with one when the\n * batch conflicts (409, or 422 for `invalid_operation`) or is too large (413,\n * `content_too_large`), `acquireLock` with `lock_held`, `renewLock` with\n * `lock_lost`. The editor reads only `code`, `holder` and `holders`, so any\n * error carrying those works the same.\n */\nexport class CollaborationConflict extends SdkError {\n declare readonly code: CollaborationConflictCode;\n /** The operation the backend refused, for a refused batch. */\n readonly opIndex?: number;\n /** Who holds the block, for `lock_held`. */\n readonly holder?: BlockLockHolder;\n /** Who holds locks, for `locked_by_others`. */\n readonly holders?: BlockLockHolder[];\n\n constructor(\n message: string,\n details: {\n code: CollaborationConflictCode;\n status?: number;\n opIndex?: number;\n holder?: BlockLockHolder;\n holders?: BlockLockHolder[];\n },\n ) {\n super(message, details.status ?? defaultStatus(details.code), details.code);\n this.name = \"CollaborationConflict\";\n if (details.opIndex !== undefined) this.opIndex = details.opIndex;\n if (details.holder !== undefined) this.holder = details.holder;\n if (details.holders !== undefined) this.holders = details.holders;\n }\n}\n\n/** The realtime connection, as the editor shows it. */\nexport type CollaborationConnectionState =\n \"connected\" | \"reconnecting\" | \"offline\";\n\n/** What a backend calls while an editor has joined a template. */\nexport interface CollaborationHandlers {\n /** Another session's batch, or one this session can't attribute to itself. */\n onBatch(batch: RevisionedBatch): void;\n /**\n * The content changed in a way batches don't describe: fetch it again.\n * `actor` is who changed it, when the backend knows: the editor names an\n * agent's re-sync (`type: \"mcp\"`) in a notice (\"Claude for Ada updated the\n * template\").\n */\n onResync(revision: number, actor?: CollaborationActor): void;\n onLock(lock: BlockLock): void;\n onUnlock(blockId: string, sessionId: string, locale?: string | null): void;\n /** Everyone with the template open, this session included. */\n onMembers(members: CollaborationMember[]): void;\n onConnectionChange(state: CollaborationConnectionState): void;\n}\n\n/** What {@link CollaborationProvider.join} resolves with. */\nexport interface CollaborationJoin {\n /** The template's current revision. */\n revision: number;\n /** Unexpired locks. */\n locks: BlockLock[];\n /** Everyone with the template open, this session included; empty without presence. */\n members: CollaborationMember[];\n /** Stop receiving events for this template. */\n leave(): void;\n}\n\n/** What {@link CollaborationProvider.operationsAfter} resolves with. */\nexport type OperationsAfterResult =\n | { revision: number; batches: RevisionedBatch[] }\n | { revision: number; resync: true };\n\n/**\n * The bring-your-own collaboration contract: ordered operations, presence and\n * block locks over your backend. Templatical Cloud is one implementation.\n *\n * `join` may be called again for the template already joined, after a\n * reconnect: answer with the current revision, locks and members without\n * subscribing twice.\n *\n * The three lock methods are optional together: a backend without them gets\n * ordered operations and no locks.\n */\nexport interface CollaborationProvider {\n join(\n templateId: string,\n session: { sessionId: string },\n handlers: CollaborationHandlers,\n ): Promise<CollaborationJoin>;\n submit(\n templateId: string,\n batch: OperationBatch,\n ): Promise<{ revision: number }>;\n operationsAfter(\n templateId: string,\n revision: number,\n ): Promise<OperationsAfterResult>;\n /**\n * Acquire the block's lock in `locale`; absent or `null` means the default\n * language and structure. A provider that ignores `locale` serializes per block.\n */\n acquireLock?(\n templateId: string,\n blockId: string,\n locale?: string | null,\n ): Promise<BlockLock>;\n /**\n * Renew the block's lock in `locale`; absent or `null` means the default\n * language and structure. A provider that ignores `locale` serializes per block.\n */\n renewLock?(\n templateId: string,\n blockId: string,\n locale?: string | null,\n ): Promise<BlockLock>;\n /**\n * Release the block's lock in `locale`; absent or `null` means the default\n * language and structure. A provider that ignores `locale` serializes per block.\n */\n releaseLock?(\n templateId: string,\n blockId: string,\n locale?: string | null,\n ): Promise<void>;\n}\n\n/** What `onRemoteChange` reports: a batch another session made. */\nexport interface CollaborationRemoteChange {\n actor: CollaborationActor;\n /**\n * The first locale operation's language, excluding `setDefaultLocale`, otherwise `null`.\n * A `setDefaultLocale` batch reports `null`: it changes the template's default.\n */\n locale: string | null;\n ops: Operation[];\n}\n","import type {\n Block,\n ButtonBlock,\n CountdownBlock,\n CustomBlock,\n DividerBlock,\n HtmlBlock,\n ImageBlock,\n MenuBlock,\n ParagraphBlock,\n SectionBlock,\n SlotBlock,\n SocialIconsBlock,\n SpacerBlock,\n TableBlock,\n TitleBlock,\n VideoBlock,\n WrapperBlock,\n} from \"./blocks\";\n\nexport function isSection(block: Block): block is SectionBlock {\n return block.type === \"section\";\n}\n\nexport function isTitle(block: Block): block is TitleBlock {\n return block.type === \"title\";\n}\n\nexport function isParagraph(block: Block): block is ParagraphBlock {\n return block.type === \"paragraph\";\n}\n\nexport function isImage(block: Block): block is ImageBlock {\n return block.type === \"image\";\n}\n\nexport function isButton(block: Block): block is ButtonBlock {\n return block.type === \"button\";\n}\n\nexport function isDivider(block: Block): block is DividerBlock {\n return block.type === \"divider\";\n}\n\nexport function isVideo(block: Block): block is VideoBlock {\n return block.type === \"video\";\n}\n\nexport function isSocialIcons(block: Block): block is SocialIconsBlock {\n return block.type === \"social\";\n}\n\nexport function isSpacer(block: Block): block is SpacerBlock {\n return block.type === \"spacer\";\n}\n\nexport function isHtml(block: Block): block is HtmlBlock {\n return block.type === \"html\";\n}\n\nexport function isMenu(block: Block): block is MenuBlock {\n return block.type === \"menu\";\n}\n\nexport function isTable(block: Block): block is TableBlock {\n return block.type === \"table\";\n}\n\nexport function isCountdown(block: Block): block is CountdownBlock {\n return block.type === \"countdown\";\n}\n\nexport function isCustomBlock(block: Block): block is CustomBlock {\n return block.type === \"custom\";\n}\n\nexport function isSlot(block: Block): block is SlotBlock {\n return block.type === \"slot\";\n}\n\nexport function isWrapper(block: Block): block is WrapperBlock {\n return block.type === \"wrapper\";\n}\n","import type {\n ButtonBlock,\n CountdownBlock,\n DividerBlock,\n HtmlBlock,\n ImageBlock,\n MenuBlock,\n ParagraphBlock,\n SectionBlock,\n SocialIconsBlock,\n SpacerBlock,\n TableBlock,\n TitleBlock,\n VideoBlock,\n} from \"./blocks\";\nimport type { TemplateSettings } from \"./template\";\n\ntype BlockDefaultsFor<T> = Partial<Omit<T, \"id\" | \"type\">>;\n\nexport interface BlockDefaults {\n title?: BlockDefaultsFor<TitleBlock>;\n paragraph?: BlockDefaultsFor<ParagraphBlock>;\n image?: BlockDefaultsFor<ImageBlock>;\n button?: BlockDefaultsFor<ButtonBlock>;\n divider?: BlockDefaultsFor<DividerBlock>;\n section?: BlockDefaultsFor<SectionBlock>;\n video?: BlockDefaultsFor<VideoBlock>;\n social?: BlockDefaultsFor<SocialIconsBlock>;\n spacer?: BlockDefaultsFor<SpacerBlock>;\n html?: BlockDefaultsFor<HtmlBlock>;\n menu?: BlockDefaultsFor<MenuBlock>;\n table?: BlockDefaultsFor<TableBlock>;\n countdown?: BlockDefaultsFor<CountdownBlock>;\n}\n\nexport type TemplateDefaults = Partial<TemplateSettings>;\n\n// ---------------------------------------------------------------------------\n// Built-in default values — single source of truth for factories & consumers\n// ---------------------------------------------------------------------------\n\n// `color` is intentionally omitted: a new Title inherits the document\n// `textColor` (see `TemplateSettings`) unless the user sets a per-block color.\nexport const TITLE_BLOCK_DEFAULTS: BlockDefaultsFor<TitleBlock> = {\n content: \"<p>Enter your title</p>\",\n level: 2,\n textAlign: \"left\",\n};\n\nexport const PARAGRAPH_BLOCK_DEFAULTS: BlockDefaultsFor<ParagraphBlock> = {\n content: \"<p>Enter your text here</p>\",\n};\n\nexport const IMAGE_BLOCK_DEFAULTS: BlockDefaultsFor<ImageBlock> = {\n src: \"\",\n alt: \"\",\n width: \"full\",\n align: \"center\",\n};\n\nexport const BUTTON_BLOCK_DEFAULTS: BlockDefaultsFor<ButtonBlock> = {\n text: \"Click Here\",\n url: \"\",\n backgroundColor: \"#333333\",\n textColor: \"#ffffff\",\n borderRadius: 6,\n fontSize: 15,\n buttonPadding: { top: 12, right: 24, bottom: 12, left: 24 },\n align: \"center\",\n};\n\nexport const DIVIDER_BLOCK_DEFAULTS: BlockDefaultsFor<DividerBlock> = {\n lineStyle: \"solid\",\n color: \"#e0e0e0\",\n thickness: 1,\n width: \"full\",\n};\n\nexport const SECTION_BLOCK_DEFAULTS: BlockDefaultsFor<SectionBlock> = {\n columns: \"1\",\n};\n\nexport const VIDEO_BLOCK_DEFAULTS: BlockDefaultsFor<VideoBlock> = {\n url: \"\",\n thumbnailUrl: \"\",\n alt: \"Video\",\n width: \"full\",\n align: \"center\",\n};\n\nexport const SOCIAL_ICONS_BLOCK_DEFAULTS: BlockDefaultsFor<SocialIconsBlock> = {\n iconStyle: \"solid\",\n iconSize: \"medium\",\n spacing: 10,\n align: \"center\",\n};\n\nexport const SPACER_BLOCK_DEFAULTS: BlockDefaultsFor<SpacerBlock> = {\n height: 24,\n};\n\nexport const HTML_BLOCK_DEFAULTS: BlockDefaultsFor<HtmlBlock> = {\n content: \"\",\n};\n\n// `color` is intentionally omitted: a new Menu inherits the document\n// `textColor` unless the user sets a per-block color (or per-item `linkColor`).\nexport const MENU_BLOCK_DEFAULTS: BlockDefaultsFor<MenuBlock> = {\n fontSize: 15,\n textAlign: \"center\",\n separator: \"|\",\n separatorColor: \"#e0e0e0\",\n spacing: 10,\n};\n\n// `color` is intentionally omitted: a new Table inherits the document\n// `textColor` unless the user sets a per-block color.\nexport const TABLE_BLOCK_DEFAULTS: BlockDefaultsFor<TableBlock> = {\n hasHeaderRow: true,\n borderColor: \"#e0e0e0\",\n borderWidth: 1,\n cellPadding: 8,\n fontSize: 15,\n textAlign: \"left\",\n};\n\nexport const COUNTDOWN_BLOCK_DEFAULTS: BlockDefaultsFor<CountdownBlock> = {\n targetDate: \"\",\n timezone: \"UTC\",\n showDays: true,\n showHours: true,\n showMinutes: true,\n showSeconds: true,\n separator: \":\",\n digitFontSize: 32,\n digitColor: \"#1a1a1a\",\n labelColor: \"#6b7280\",\n labelFontSize: 12,\n backgroundColor: \"#ffffff\",\n labelDays: \"Days\",\n labelHours: \"Hours\",\n labelMinutes: \"Minutes\",\n labelSeconds: \"Seconds\",\n expiredMessage: \"This offer has expired\",\n expiredImageUrl: \"\",\n hideOnExpiry: false,\n};\n\nexport const DEFAULT_BLOCK_DEFAULTS: Required<BlockDefaults> = {\n title: TITLE_BLOCK_DEFAULTS,\n paragraph: PARAGRAPH_BLOCK_DEFAULTS,\n image: IMAGE_BLOCK_DEFAULTS,\n button: BUTTON_BLOCK_DEFAULTS,\n divider: DIVIDER_BLOCK_DEFAULTS,\n section: SECTION_BLOCK_DEFAULTS,\n video: VIDEO_BLOCK_DEFAULTS,\n social: SOCIAL_ICONS_BLOCK_DEFAULTS,\n spacer: SPACER_BLOCK_DEFAULTS,\n html: HTML_BLOCK_DEFAULTS,\n menu: MENU_BLOCK_DEFAULTS,\n table: TABLE_BLOCK_DEFAULTS,\n countdown: COUNTDOWN_BLOCK_DEFAULTS,\n};\n\nexport const DEFAULT_TEMPLATE_DEFAULTS: TemplateDefaults = {\n width: 600,\n backgroundColor: \"#ffffff\",\n textColor: \"#1a1a1a\",\n linkUnderline: true,\n fontFamily: \"Arial\",\n locale: \"en\",\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nexport function deepMergeDefaults<T extends object>(\n base: T,\n overrides: Partial<T>,\n): T {\n const result = { ...base };\n\n for (const key of Object.keys(overrides) as Array<keyof T>) {\n const baseVal = base[key];\n const overrideVal = overrides[key];\n\n if (overrideVal === undefined) {\n continue;\n }\n\n if (isPlainObject(baseVal) && isPlainObject(overrideVal)) {\n result[key] = deepMergeDefaults(\n baseVal,\n overrideVal as Partial<typeof baseVal>,\n ) as T[keyof T];\n } else {\n result[key] = overrideVal as T[keyof T];\n }\n }\n\n return result;\n}\n","import type { Block } from \"./blocks\";\nimport { DEFAULT_TEMPLATE_DEFAULTS } from \"./defaults\";\nimport type { TemplateDefaults } from \"./defaults\";\nimport type { ContentDirection } from \"./direction\";\nimport type { SettingsLocaleLayer } from \"./localization\";\n\nexport interface TemplateSettings {\n width: number;\n backgroundColor: string;\n /**\n * Document-level default text color: the `<mj-text>` default in the rendered\n * MJML, inherited by every text block (Title, Paragraph, Menu, Table) that\n * doesn't set its own `color`. Required, defaulting to `#1a1a1a` (see\n * `DEFAULT_TEMPLATE_DEFAULTS`); customize the default per-consumer via\n * `templateDefaults`. A block's explicit `color` or an inline text-color\n * mark overrides it.\n */\n textColor: string;\n /**\n * Document-level link color: emitted as the global `a { color }` rule in the\n * rendered MJML, so it cascades to every link — rich-text and menu alike.\n * Optional: when unset, links inherit the surrounding text color\n * (`color: inherit`), preserving the pre-#352 default. A per-block or\n * per-item color (a Menu item's `color`, `MenuBlock.linkColor`) still\n * overrides it.\n */\n linkColor?: string;\n /**\n * Whether links are underlined document-wide: drives the global\n * `a { text-decoration }` rule (`underline` when true, `none` when false).\n * Required, defaulting to `true` (see `DEFAULT_TEMPLATE_DEFAULTS`) — the\n * common, more accessible email default. Applies to body (rich-text) links;\n * buttons and menu items carry their own inline `text-decoration` and are\n * unaffected. Set `false` to render links without an underline.\n */\n linkUnderline: boolean;\n fontFamily: string;\n preheaderText?: string;\n /**\n * BCP-47 language code for the rendered email's `<html lang>`. Drives\n * screen-reader pronunciation. Default `'en'` via `DEFAULT_TEMPLATE_DEFAULTS`.\n */\n locale: string;\n /** Other language versions; the default is `locale`. */\n locales?: string[];\n /** Per-language layers, keyed by BCP 47 tag; see `resolveLocale`. */\n l10n?: Record<string, SettingsLocaleLayer>;\n /**\n * Writing direction of the delivered email: the canvas `dir` and the\n * rendered `<mjml dir>`. Independent of the editor chrome\n * (`init({ locale })`). Optional: when unset, `resolveContentDirection`\n * falls through to the content language (`ar` / `he` / `fa` / … → `\"rtl\"`,\n * otherwise `\"ltr\"`). An explicit `\"ltr\"` on an Arabic template is a\n * stated decision, not a missing value.\n */\n direction?: ContentDirection;\n}\n\nexport interface TemplateContent {\n blocks: Block[];\n settings: TemplateSettings;\n}\n\nexport function createDefaultTemplateContent(\n defaultFontFamily = \"Arial\",\n templateDefaults?: TemplateDefaults,\n): TemplateContent {\n return {\n blocks: [],\n settings: {\n ...DEFAULT_TEMPLATE_DEFAULTS,\n fontFamily: defaultFontFamily,\n ...templateDefaults,\n } as TemplateSettings,\n };\n}\n","/**\n * Writing direction of the delivered email — the canvas `dir` and the\n * rendered `<mjml dir>`. Independent of the editor chrome language\n * (`init({ locale })`).\n */\nexport type ContentDirection = \"ltr\" | \"rtl\";\n\n/**\n * Primary BCP-47 subtags whose default writing direction is right-to-left.\n * Region tags (`ar-SA`) resolve through the primary subtag. `\"iw\"` is the\n * legacy Hebrew tag. Not a CLDR dump — extend the list when a script is\n * needed; do not infer from `lang` at the call site.\n */\nexport const RTL_LANGUAGE_PRIMARY_SUBTAGS: readonly string[] = [\n \"ar\",\n \"he\",\n \"iw\",\n \"fa\",\n \"ur\",\n \"yi\",\n \"dv\",\n \"ps\",\n \"sd\",\n \"ug\",\n \"ckb\",\n \"ks\",\n];\n\n/**\n * Whether a BCP-47 (or underscore-separated) language tag is an RTL language\n * by primary subtag. Missing, empty, and unknown tags are not RTL.\n */\nexport function isRtlLanguageTag(tag: string | undefined): boolean {\n const primary = tag?.trim().replace(/_/g, \"-\").split(\"-\")[0]?.toLowerCase();\n return !!primary && RTL_LANGUAGE_PRIMARY_SUBTAGS.includes(primary);\n}\n\n/**\n * The email's writing direction. An explicit `settings.direction` of `\"ltr\"`\n * or `\"rtl\"` wins; anything else (unset, or a garbage JS value) falls through\n * to the content language, then to `\"ltr\"`.\n *\n * This is the single reader — renderer, canvas, and settings UI all go\n * through it, so a later per-block override can wrap it without forking the\n * locale table.\n */\nexport function resolveContentDirection(settings: {\n locale: string;\n direction?: ContentDirection;\n}): ContentDirection {\n if (settings.direction === \"ltr\" || settings.direction === \"rtl\") {\n return settings.direction;\n }\n return isRtlLanguageTag(settings.locale) ? \"rtl\" : \"ltr\";\n}\n","export type TranslationErrorCode =\n \"rate_limited\" | \"limit_reached\" | \"content_too_large\" | \"translation_failed\";\n\nexport interface TranslationField {\n /** A block field id, or `settings/<path>`. */\n id: string;\n /** Merge and logic tags masked as numbered placeholders. */\n text: string;\n format: \"html\" | \"text\";\n}\n\nexport interface TranslationRequest {\n templateId: string | null;\n sourceLocale: string;\n targetLocale: string;\n /** At most 50 fields and 20,000 characters of text per call. */\n fields: TranslationField[];\n}\n\nexport interface TranslationResult {\n fields: { id: string; text: string }[];\n}\n\n/** A translation backend. Reject with an SdkError or, when aborted, an AbortError. */\nexport interface TranslationProvider {\n translate(\n request: TranslationRequest,\n signal: AbortSignal,\n ): Promise<TranslationResult>;\n}\n\nexport const TRANSLATION_MAX_FIELDS = 50;\nexport const TRANSLATION_MAX_CHARS = 20_000;\n","/**\n * Minimal, allocation-free primitives for reading an HTML open tag out of a\n * markup string. They exist because merge-tag markup is rewritten from a raw\n * string in two packages — `@templatical/types` (label / sample resolution for\n * the previews) and `@templatical/renderer` (converting spans back to tokens on\n * export) — and both need the same two answers: where does this open tag end,\n * and what is the value of one of its attributes.\n *\n * Both are hand-written character scans rather than regexes. A regex over an\n * attribute string with no closing quote backtracks across the whole input,\n * which is the ReDoS class the span scanners were rewritten to avoid; a scan\n * that only moves forward cannot.\n */\n\nconst QUOTES = new Set(['\"', \"'\"]);\n\n/**\n * Index of the `>` that closes the open tag whose name ends at `from`, or `-1`\n * when the tag never closes.\n *\n * Quote-aware: a `>` inside a quoted attribute value does not end the tag. As\n * in the HTML tokenizer, a quote opens a value only right after `=`; inside an\n * unquoted value (`title=don't`) it is an ordinary character, or the scan would\n * run past the real tag end into the content.\n * That matters because a consumer may configure a merge-tag syntax whose tag\n * values contain `<` / `>` — Smarty-style `<% $email %>` — and HTML attribute\n * serialization escapes only `&`, `\"` and U+00A0, so those characters reach the\n * markup literally. A plain `indexOf(\">\")` stops mid-attribute there and every\n * caller downstream sees a truncated attribute string.\n *\n * An unterminated quote yields `-1` rather than a guessed tag end: callers\n * treat that as \"not markup I can rewrite\" and emit the input untouched, which\n * is the safe answer for malformed HTML.\n */\nexport function findOpenTagEnd(html: string, from: number): number {\n let quote: string | null = null;\n let state: \"tag\" | \"beforeValue\" | \"unquotedValue\" = \"tag\";\n for (let i = from; i < html.length; i++) {\n const char = html[i];\n if (quote !== null) {\n if (char === quote) quote = null;\n continue;\n }\n if (state === \"beforeValue\") {\n if (isWhitespace(char)) continue;\n if (QUOTES.has(char)) {\n quote = char;\n state = \"tag\";\n continue;\n }\n state = \"unquotedValue\";\n }\n if (state === \"unquotedValue\") {\n if (char === \">\") return i;\n if (isWhitespace(char)) state = \"tag\";\n continue;\n }\n if (char === \"=\") {\n state = \"beforeValue\";\n continue;\n }\n if (char === \">\") return i;\n }\n return -1;\n}\n\n/** End of a span's opening tag, or the next span start if this one is malformed. */\nexport function findOpenSpanBoundary(\n html: string,\n from: number,\n): { end: number; nextSpan: number } {\n let quote: string | null = null;\n for (let i = from; i < html.length; i++) {\n const char = html[i];\n if (quote !== null) {\n if (char === quote) quote = null;\n } else if (QUOTES.has(char)) {\n quote = char;\n } else if (char === \">\") {\n return { end: i, nextSpan: -1 };\n } else if (char === \"<\" && html.startsWith(\"<span\", i)) {\n return { end: -1, nextSpan: i };\n }\n }\n return { end: -1, nextSpan: -1 };\n}\n\nfunction isAttrNameChar(char: string): boolean {\n return (\n char !== \" \" &&\n char !== \"\\t\" &&\n char !== \"\\n\" &&\n char !== \"\\r\" &&\n char !== \"\\f\" &&\n char !== \"=\" &&\n char !== \">\" &&\n char !== \"/\"\n );\n}\n\nfunction isWhitespace(char: string): boolean {\n return (\n char === \" \" ||\n char === \"\\t\" ||\n char === \"\\n\" ||\n char === \"\\r\" ||\n char === \"\\f\"\n );\n}\n\n// HTML 4.01 named references, legacy aliases and the previously supported apos.\nconst NAMED_ENTITIES: Record<string, string> = {\n AMP: \"&\",\n COPY: \"\\u00a9\",\n GT: \">\",\n LT: \"<\",\n QUOT: '\"',\n REG: \"\\u00ae\",\n AElig: \"\\u00c6\",\n Aacute: \"\\u00c1\",\n Acirc: \"\\u00c2\",\n Agrave: \"\\u00c0\",\n Alpha: \"\\u0391\",\n Aring: \"\\u00c5\",\n Atilde: \"\\u00c3\",\n Auml: \"\\u00c4\",\n Beta: \"\\u0392\",\n Ccedil: \"\\u00c7\",\n Chi: \"\\u03a7\",\n Dagger: \"\\u2021\",\n Delta: \"\\u0394\",\n ETH: \"\\u00d0\",\n Eacute: \"\\u00c9\",\n Ecirc: \"\\u00ca\",\n Egrave: \"\\u00c8\",\n Epsilon: \"\\u0395\",\n Eta: \"\\u0397\",\n Euml: \"\\u00cb\",\n Gamma: \"\\u0393\",\n Iacute: \"\\u00cd\",\n Icirc: \"\\u00ce\",\n Igrave: \"\\u00cc\",\n Iota: \"\\u0399\",\n Iuml: \"\\u00cf\",\n Kappa: \"\\u039a\",\n Lambda: \"\\u039b\",\n Mu: \"\\u039c\",\n Ntilde: \"\\u00d1\",\n Nu: \"\\u039d\",\n OElig: \"\\u0152\",\n Oacute: \"\\u00d3\",\n Ocirc: \"\\u00d4\",\n Ograve: \"\\u00d2\",\n Omega: \"\\u03a9\",\n Omicron: \"\\u039f\",\n Oslash: \"\\u00d8\",\n Otilde: \"\\u00d5\",\n Ouml: \"\\u00d6\",\n Phi: \"\\u03a6\",\n Pi: \"\\u03a0\",\n Prime: \"\\u2033\",\n Psi: \"\\u03a8\",\n Rho: \"\\u03a1\",\n Scaron: \"\\u0160\",\n Sigma: \"\\u03a3\",\n THORN: \"\\u00de\",\n Tau: \"\\u03a4\",\n Theta: \"\\u0398\",\n Uacute: \"\\u00da\",\n Ucirc: \"\\u00db\",\n Ugrave: \"\\u00d9\",\n Upsilon: \"\\u03a5\",\n Uuml: \"\\u00dc\",\n Xi: \"\\u039e\",\n Yacute: \"\\u00dd\",\n Yuml: \"\\u0178\",\n Zeta: \"\\u0396\",\n aacute: \"\\u00e1\",\n acirc: \"\\u00e2\",\n acute: \"\\u00b4\",\n aelig: \"\\u00e6\",\n agrave: \"\\u00e0\",\n alefsym: \"\\u2135\",\n alpha: \"\\u03b1\",\n amp: \"&\",\n and: \"\\u2227\",\n ang: \"\\u2220\",\n apos: \"'\",\n aring: \"\\u00e5\",\n asymp: \"\\u2248\",\n atilde: \"\\u00e3\",\n auml: \"\\u00e4\",\n bdquo: \"\\u201e\",\n beta: \"\\u03b2\",\n brvbar: \"\\u00a6\",\n bull: \"\\u2022\",\n cap: \"\\u2229\",\n ccedil: \"\\u00e7\",\n cedil: \"\\u00b8\",\n cent: \"\\u00a2\",\n chi: \"\\u03c7\",\n circ: \"\\u02c6\",\n clubs: \"\\u2663\",\n cong: \"\\u2245\",\n copy: \"\\u00a9\",\n crarr: \"\\u21b5\",\n cup: \"\\u222a\",\n curren: \"\\u00a4\",\n dArr: \"\\u21d3\",\n dagger: \"\\u2020\",\n darr: \"\\u2193\",\n deg: \"\\u00b0\",\n delta: \"\\u03b4\",\n diams: \"\\u2666\",\n divide: \"\\u00f7\",\n eacute: \"\\u00e9\",\n ecirc: \"\\u00ea\",\n egrave: \"\\u00e8\",\n empty: \"\\u2205\",\n emsp: \"\\u2003\",\n ensp: \"\\u2002\",\n epsilon: \"\\u03b5\",\n equiv: \"\\u2261\",\n eta: \"\\u03b7\",\n eth: \"\\u00f0\",\n euml: \"\\u00eb\",\n euro: \"\\u20ac\",\n exist: \"\\u2203\",\n fnof: \"\\u0192\",\n forall: \"\\u2200\",\n frac12: \"\\u00bd\",\n frac14: \"\\u00bc\",\n frac34: \"\\u00be\",\n frasl: \"\\u2044\",\n gamma: \"\\u03b3\",\n ge: \"\\u2265\",\n gt: \">\",\n hArr: \"\\u21d4\",\n harr: \"\\u2194\",\n hearts: \"\\u2665\",\n hellip: \"\\u2026\",\n iacute: \"\\u00ed\",\n icirc: \"\\u00ee\",\n iexcl: \"\\u00a1\",\n igrave: \"\\u00ec\",\n image: \"\\u2111\",\n infin: \"\\u221e\",\n int: \"\\u222b\",\n iota: \"\\u03b9\",\n iquest: \"\\u00bf\",\n isin: \"\\u2208\",\n iuml: \"\\u00ef\",\n kappa: \"\\u03ba\",\n lArr: \"\\u21d0\",\n lambda: \"\\u03bb\",\n lang: \"\\u2329\",\n laquo: \"\\u00ab\",\n larr: \"\\u2190\",\n lceil: \"\\u2308\",\n ldquo: \"\\u201c\",\n le: \"\\u2264\",\n lfloor: \"\\u230a\",\n lowast: \"\\u2217\",\n loz: \"\\u25ca\",\n lrm: \"\\u200e\",\n lsaquo: \"\\u2039\",\n lsquo: \"\\u2018\",\n lt: \"<\",\n macr: \"\\u00af\",\n mdash: \"\\u2014\",\n micro: \"\\u00b5\",\n middot: \"\\u00b7\",\n minus: \"\\u2212\",\n mu: \"\\u03bc\",\n nabla: \"\\u2207\",\n nbsp: \"\\u00a0\",\n ndash: \"\\u2013\",\n ne: \"\\u2260\",\n ni: \"\\u220b\",\n not: \"\\u00ac\",\n notin: \"\\u2209\",\n nsub: \"\\u2284\",\n ntilde: \"\\u00f1\",\n nu: \"\\u03bd\",\n oacute: \"\\u00f3\",\n ocirc: \"\\u00f4\",\n oelig: \"\\u0153\",\n ograve: \"\\u00f2\",\n oline: \"\\u203e\",\n omega: \"\\u03c9\",\n omicron: \"\\u03bf\",\n oplus: \"\\u2295\",\n or: \"\\u2228\",\n ordf: \"\\u00aa\",\n ordm: \"\\u00ba\",\n oslash: \"\\u00f8\",\n otilde: \"\\u00f5\",\n otimes: \"\\u2297\",\n ouml: \"\\u00f6\",\n para: \"\\u00b6\",\n part: \"\\u2202\",\n permil: \"\\u2030\",\n perp: \"\\u22a5\",\n phi: \"\\u03c6\",\n pi: \"\\u03c0\",\n piv: \"\\u03d6\",\n plusmn: \"\\u00b1\",\n pound: \"\\u00a3\",\n prime: \"\\u2032\",\n prod: \"\\u220f\",\n prop: \"\\u221d\",\n psi: \"\\u03c8\",\n quot: '\"',\n rArr: \"\\u21d2\",\n radic: \"\\u221a\",\n rang: \"\\u232a\",\n raquo: \"\\u00bb\",\n rarr: \"\\u2192\",\n rceil: \"\\u2309\",\n rdquo: \"\\u201d\",\n real: \"\\u211c\",\n reg: \"\\u00ae\",\n rfloor: \"\\u230b\",\n rho: \"\\u03c1\",\n rlm: \"\\u200f\",\n rsaquo: \"\\u203a\",\n rsquo: \"\\u2019\",\n sbquo: \"\\u201a\",\n scaron: \"\\u0161\",\n sdot: \"\\u22c5\",\n sect: \"\\u00a7\",\n shy: \"\\u00ad\",\n sigma: \"\\u03c3\",\n sigmaf: \"\\u03c2\",\n sim: \"\\u223c\",\n spades: \"\\u2660\",\n sub: \"\\u2282\",\n sube: \"\\u2286\",\n sum: \"\\u2211\",\n sup: \"\\u2283\",\n sup1: \"\\u00b9\",\n sup2: \"\\u00b2\",\n sup3: \"\\u00b3\",\n supe: \"\\u2287\",\n szlig: \"\\u00df\",\n tau: \"\\u03c4\",\n there4: \"\\u2234\",\n theta: \"\\u03b8\",\n thetasym: \"\\u03d1\",\n thinsp: \"\\u2009\",\n thorn: \"\\u00fe\",\n tilde: \"\\u02dc\",\n times: \"\\u00d7\",\n trade: \"\\u2122\",\n uArr: \"\\u21d1\",\n uacute: \"\\u00fa\",\n uarr: \"\\u2191\",\n ucirc: \"\\u00fb\",\n ugrave: \"\\u00f9\",\n uml: \"\\u00a8\",\n upsih: \"\\u03d2\",\n upsilon: \"\\u03c5\",\n uuml: \"\\u00fc\",\n weierp: \"\\u2118\",\n xi: \"\\u03be\",\n yacute: \"\\u00fd\",\n yen: \"\\u00a5\",\n yuml: \"\\u00ff\",\n zeta: \"\\u03b6\",\n zwj: \"\\u200d\",\n zwnj: \"\\u200c\",\n};\n\n/**\n * Decode the character references an HTML serializer writes into an attribute\n * value, so callers get the characters the author wrote.\n *\n * Supports HTML 4.01 named references, apos, legacy aliases and numeric references.\n * An unknown or malformed reference is left as literal text, which is what\n * a browser does. Single-pass — `&lt;` decodes to the text `<`\n * and stops, never to `<`, so an escaped entity inside a consumer's tag value\n * survives as itself.\n */\nexport function decodeHtmlEntities(value: string): string {\n if (!value.includes(\"&\")) return value;\n return value.replace(\n /&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g,\n (match, ref: string) => {\n if (ref[0] === \"#\") {\n const code =\n ref[1] === \"x\" || ref[1] === \"X\"\n ? Number.parseInt(ref.slice(2), 16)\n : Number.parseInt(ref.slice(1), 10);\n // Surrogates and out-of-range code points would throw; leave them be.\n if (!Number.isFinite(code) || code < 1 || code > 0x10ffff) return match;\n if (code >= 0xd800 && code <= 0xdfff) return match;\n return String.fromCodePoint(code);\n }\n return Object.hasOwn(NAMED_ENTITIES, ref) ? NAMED_ENTITIES[ref] : match;\n },\n );\n}\n\n/**\n * The value of the `name` attribute within an open tag's attribute string (the\n * text between the tag name and its closing `>`), or `null` when the attribute\n * is absent or its quoted value is never closed.\n *\n * Handles double-quoted, single-quoted and unquoted values, and matches the\n * attribute name case-insensitively, as HTML does. The value is\n * entity-decoded, because that is what the attribute means: the editor\n * serializes a tag value of `<% $email %>` as\n * `data-merge-tag=\"<% $email %>\"`, and every caller compares the result\n * against a configured merge-tag token written in raw characters.\n */\nexport function getTagAttrValue(attrs: string, name: string): string | null {\n const target = name.toLowerCase();\n let i = 0;\n\n while (i < attrs.length) {\n while (i < attrs.length && (isWhitespace(attrs[i]) || attrs[i] === \"/\")) {\n i++;\n }\n if (i >= attrs.length) break;\n\n const nameStart = i;\n while (i < attrs.length && isAttrNameChar(attrs[i])) i++;\n const attrName = attrs.substring(nameStart, i).toLowerCase();\n if (attrName === \"\") {\n // Not a name character and not whitespace — e.g. a stray `=`. Step over\n // it so the scan always advances.\n i++;\n continue;\n }\n\n while (i < attrs.length && isWhitespace(attrs[i])) i++;\n if (attrs[i] !== \"=\") {\n // A boolean attribute (`hidden`); the cursor already sits on the next\n // attribute name, so don't consume anything here.\n continue;\n }\n i++; // past `=`\n while (i < attrs.length && isWhitespace(attrs[i])) i++;\n\n const quote = attrs[i];\n if (QUOTES.has(quote)) {\n const valueStart = i + 1;\n const valueEnd = attrs.indexOf(quote, valueStart);\n if (valueEnd === -1) return null; // unterminated value — nothing readable follows\n if (attrName === target)\n return decodeHtmlEntities(attrs.substring(valueStart, valueEnd));\n i = valueEnd + 1;\n continue;\n }\n\n const valueStart = i;\n while (i < attrs.length && !isWhitespace(attrs[i]) && attrs[i] !== \">\") i++;\n if (attrName === target)\n return decodeHtmlEntities(attrs.substring(valueStart, i));\n }\n\n return null;\n}\n","import {\n findOpenSpanBoundary,\n findOpenTagEnd,\n getTagAttrValue,\n} from \"./html-scan\";\n\n/**\n * Replace merge tag span elements with their data attribute values.\n * Converts `<span data-merge-tag=\"{{name}}\">Label</span>` to `{{name}}`.\n * Also handles `data-logic-merge-tag` attributes.\n *\n * Each span opening tag is scanned once, with quoted attribute values kept\n * intact and malformed prefixes skipped before a later span candidate.\n */\nexport function convertMergeTagsToValues(html: string): string {\n // Preserve the renderer's existing first-close handling of nested spans.\n return rewriteMergeTagSpans(html, (value) => value, false);\n}\n\n/**\n * Walk `html`, find every `<span …>…</span>`, and replace the entire span\n * with `replace`'s result for its decoded merge-tag attribute value. Other\n * spans stay intact. Replacements are never scanned again, so callers can\n * substitute opaque placeholders without parsing decoded tokens as HTML.\n */\nexport function replaceMergeTagSpans(\n html: string,\n replace: (value: string) => string,\n): string {\n return rewriteMergeTagSpans(html, replace, true);\n}\n\n/** Merge-tag chips with their original markup and end-exclusive offsets. */\nexport function scanMergeTagSpans(\n html: string,\n): { start: number; end: number; markup: string }[] {\n const spans: { start: number; end: number; markup: string }[] = [];\n rewriteMergeTagSpans(\n html,\n (_value, start, end) => {\n const markup = html.slice(start, end);\n spans.push({ start, end, markup });\n return markup;\n },\n true,\n );\n return spans;\n}\n\nfunction rewriteMergeTagSpans(\n html: string,\n replace: (value: string, start: number, end: number) => string,\n wholeElement: boolean,\n): string {\n let out = \"\";\n let i = 0;\n while (i < html.length) {\n const open = html.indexOf(\"<span\", i);\n if (open === -1) {\n out += html.substring(i);\n break;\n }\n // `<span` must be followed by `>` or whitespace to be a real opening tag.\n const afterTagName = html[open + 5];\n if (\n afterTagName !== \">\" &&\n afterTagName !== \" \" &&\n afterTagName !== \"\\t\" &&\n afterTagName !== \"\\n\" &&\n afterTagName !== \"\\r\" &&\n afterTagName !== \"/\"\n ) {\n out += html.substring(i, open + 5);\n i = open + 5;\n continue;\n }\n const { end: openEnd, nextSpan } = findOpenSpanBoundary(html, open + 5);\n if (nextSpan !== -1) {\n out += html.substring(i, nextSpan);\n i = nextSpan;\n continue;\n }\n if (openEnd === -1) {\n out += html.substring(i);\n break;\n }\n const attrs = html.substring(open + 5, openEnd);\n const value =\n findAttr(attrs, \"data-merge-tag\") ??\n findAttr(attrs, \"data-logic-merge-tag\");\n if (value === null) {\n // Keep this opening tag and continue through its contents, where a\n // nested merge-tag span may appear.\n out += html.substring(i, openEnd + 1);\n i = openEnd + 1;\n continue;\n }\n const closeEnd = findSpanClose(html, openEnd + 1, wholeElement);\n if (closeEnd === -1) {\n out += html.substring(i);\n break;\n }\n out += html.substring(i, open);\n out += replace(value, open, closeEnd);\n i = closeEnd;\n }\n return out;\n}\n\n/** End of the matching close tag, including any nested spans in the label. */\nfunction findSpanClose(\n html: string,\n from: number,\n wholeElement: boolean,\n): number {\n if (!wholeElement) {\n const close = html.indexOf(\"</span>\", from);\n return close === -1 ? -1 : close + 7;\n }\n let depth = 1;\n let cursor = from;\n while (cursor < html.length) {\n const open = html.indexOf(\"<\", cursor);\n if (open === -1) return -1;\n const end = findOpenTagEnd(html, open + 1);\n if (end === -1) return -1;\n const closing = html.startsWith(\"</span\", open);\n const opening = html.startsWith(\"<span\", open);\n const boundary = html[open + (closing ? 6 : 5)];\n if (\n (opening || closing) &&\n (boundary === \">\" || boundary === \"/\" || /\\s/.test(boundary))\n ) {\n depth += closing ? -1 : 1;\n if (depth === 0) return end + 1;\n }\n cursor = end + 1;\n }\n return -1;\n}\n\n/**\n * Extract the value of `name=\"…\"` from an HTML attribute string, or `null`\n * if absent.\n *\n * Delegates to `@templatical/types` so the editor's preview rewriter and this\n * export rewriter read markup identically. They were separate regexes once, and\n * both excluded `<` / `>` from the value — which silently left the whole span\n * in the rendered MJML whenever a consumer configured a merge-tag syntax whose\n * values contain those characters (`<% $email %>`), so the ESP never received\n * the token.\n */\nfunction findAttr(attrs: string, name: string): string | null {\n return getTagAttrValue(attrs, name);\n}\n","import type { MergeTag } from \"./config\";\nimport { findOpenSpanBoundary, getTagAttrValue } from \"./html-scan\";\n\n// --- Syntax Presets ---\n\nexport interface SyntaxPreset {\n value: RegExp;\n logic: RegExp;\n /**\n * The characters that open a data tag, e.g. `{` for `{first_name}` or `%`\n * for `%FIRSTNAME%`. Typing them opens merge-tag autocomplete. Every\n * built-in preset declares its own, so a syntax spread from one keeps it;\n * a custom syntax without one, or with only whitespace, gets no\n * autocomplete. A space inside it is kept, for tags written with one: the\n * query ends at whitespace, so `{{ first_name }}` needs `'{{ '`.\n */\n opener?: string;\n /**\n * The characters that close a data tag, e.g. `}`. Inserting a suggestion\n * absorbs a closer already typed after the caret, so `{fir}` becomes\n * `{first_name}`, not `{first_name}}`. It may equal `opener`. Whitespace\n * only counts as unset.\n */\n closer?: string;\n}\n\nexport type SyntaxPresetName =\n \"liquid\" | \"handlebars\" | \"mailchimp\" | \"ampscript\";\n\n/**\n * The built-in syntaxes. Each is a custom syntax with every field filled in,\n * so the type makes a preset without its delimiters fail to compile.\n */\nexport const SYNTAX_PRESETS: Record<\n SyntaxPresetName,\n Required<SyntaxPreset>\n> = {\n liquid: {\n value: /\\{\\{.+?\\}\\}/g,\n logic: /\\{%-?\\s*(\\w+).*?-?%\\}/g,\n opener: \"{{\",\n closer: \"}}\",\n },\n handlebars: {\n value: /\\{\\{\\{?.+?\\}?\\}\\}/g,\n logic: /\\{\\{[#/](\\w+).*?\\}\\}/g,\n opener: \"{{\",\n closer: \"}}\",\n },\n mailchimp: {\n value: /\\*\\|\\w+\\|\\*/g,\n logic: /\\*\\|(\\w+)[:|].*?\\|\\*/g,\n opener: \"*|\",\n closer: \"|*\",\n },\n ampscript: {\n value: /%%=.+?=%%/g,\n logic: /%%\\[\\s*(\\w+).*?\\]%%/g,\n opener: \"%%=\",\n closer: \"=%%\",\n },\n};\n\n/** The built-in scanner is valid when both tag patterns match a preset. */\nexport function builtInPresetOf(\n syntax: SyntaxPreset,\n): SyntaxPresetName | undefined {\n return (Object.keys(SYNTAX_PRESETS) as SyntaxPresetName[]).find((name) => {\n const preset = SYNTAX_PRESETS[name];\n return (\n (syntax.value === preset.value ||\n (syntax.value.source === preset.value.source &&\n syntax.value.flags.replace(/[gy]/g, \"\") ===\n preset.value.flags.replace(/[gy]/g, \"\"))) &&\n (syntax.logic === preset.logic ||\n (syntax.logic.source === preset.logic.source &&\n syntax.logic.flags.replace(/[gy]/g, \"\") ===\n preset.logic.flags.replace(/[gy]/g, \"\")))\n );\n });\n}\n\nexport interface SyntaxMatch {\n index: number;\n value: string;\n}\n\nfunction findCloserOnLine(\n text: string,\n closer: string,\n from: number,\n): { close: number; lineBreak: number } {\n for (let index = from; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code === 10 || code === 13 || code === 0x2028 || code === 0x2029) {\n return { close: -1, lineBreak: index };\n }\n if (text.startsWith(closer, index)) {\n return { close: index, lineBreak: -1 };\n }\n }\n return { close: -1, lineBreak: -1 };\n}\n\n/** Find global matches without retrying a built-in regex at each opener. */\nexport function scanSyntaxMatches(\n text: string,\n syntax: SyntaxPreset,\n kind: \"value\" | \"logic\",\n from = 0,\n limit = Infinity,\n): SyntaxMatch[] {\n const preset = builtInPresetOf(syntax);\n if (!preset) {\n const regex = syntax[kind];\n const pattern = new RegExp(\n regex.source,\n regex.flags.replace(/[gy]/g, \"\") + \"g\",\n );\n pattern.lastIndex = from;\n return [...text.matchAll(pattern)].slice(0, limit).map((match) => ({\n index: match.index,\n value: match[0],\n }));\n }\n\n const pattern = syntax[kind];\n const opener =\n preset === \"ampscript\"\n ? kind === \"value\"\n ? \"%%=\"\n : \"%%[\"\n : preset === \"liquid\" && kind === \"logic\"\n ? \"{%\"\n : preset === \"mailchimp\"\n ? \"*|\"\n : \"{{\";\n const closer =\n preset === \"ampscript\"\n ? kind === \"value\"\n ? \"=%%\"\n : \"]%%\"\n : preset === \"liquid\" && kind === \"logic\"\n ? \"%}\"\n : preset === \"mailchimp\"\n ? \"|*\"\n : \"}}\";\n const prefixSource =\n kind === \"logic\"\n ? {\n liquid: String.raw`\\{%-?\\s*\\w+`,\n handlebars: String.raw`\\{\\{[#/]\\w+`,\n mailchimp: String.raw`\\*\\|\\w+[:|]`,\n ampscript: String.raw`%%\\[\\s*\\w+`,\n }[preset]\n : preset === \"mailchimp\"\n ? String.raw`\\*\\|\\w+`\n : null;\n const prefix = prefixSource ? new RegExp(prefixSource, \"y\") : null;\n const sticky = new RegExp(pattern.source, \"y\");\n const matches: SyntaxMatch[] = [];\n let cursor = from;\n while (cursor < text.length && matches.length < limit) {\n const open = text.indexOf(opener, cursor);\n if (open < 0) break;\n if (prefix) {\n prefix.lastIndex = open;\n if (!prefix.exec(text)) {\n cursor = open + 1;\n continue;\n }\n }\n const afterPrefix = prefix?.lastIndex ?? open + opener.length;\n const closeSearch =\n preset === \"mailchimp\" && kind === \"value\"\n ? {\n close: text.startsWith(closer, afterPrefix) ? afterPrefix : -1,\n lineBreak: -1,\n }\n : findCloserOnLine(\n text,\n closer,\n Math.max(\n afterPrefix,\n open + opener.length + (kind === \"value\" ? 1 : 0),\n ),\n );\n if (closeSearch.lineBreak >= 0) {\n const breakAt = closeSearch.lineBreak;\n const next =\n kind === \"logic\" && (preset === \"liquid\" || preset === \"ampscript\")\n ? text.lastIndexOf(opener, breakAt)\n : -1;\n cursor = next > open ? next : breakAt + 1;\n continue;\n }\n if (closeSearch.close < 0) {\n if (preset === \"mailchimp\" && kind === \"value\") {\n cursor = open + 1;\n continue;\n }\n break;\n }\n sticky.lastIndex = open;\n const match = sticky.exec(text);\n if (match) {\n matches.push({ index: open, value: match[0] });\n cursor = sticky.lastIndex;\n } else {\n cursor = open + 1;\n }\n }\n return matches;\n}\n\n/** Match the value-first alternation used by plain-text field displays. */\nexport function scanCombinedSyntaxMatches(\n text: string,\n syntax: SyntaxPreset,\n): SyntaxMatch[] {\n const preset = builtInPresetOf(syntax);\n if (!preset) {\n const pattern = new RegExp(\n `(${syntax.value.source}|${syntax.logic.source})`,\n \"g\",\n );\n return [...text.matchAll(pattern)].map((match) => ({\n index: match.index,\n value: match[0],\n }));\n }\n if (preset === \"handlebars\") {\n return scanSyntaxMatches(text, syntax, \"value\");\n }\n if (preset === \"mailchimp\") {\n const matches: SyntaxMatch[] = [];\n const value = new RegExp(syntax.value.source, \"y\");\n const logic = new RegExp(syntax.logic.source, \"y\");\n const logicPrefix = /\\*\\|\\w+[:|]/y;\n let cursor = 0;\n while (cursor < text.length) {\n const open = text.indexOf(\"*|\", cursor);\n if (open < 0) break;\n value.lastIndex = open;\n const valueMatch = value.exec(text);\n if (valueMatch) {\n matches.push({ index: open, value: valueMatch[0] });\n cursor = value.lastIndex;\n continue;\n }\n logicPrefix.lastIndex = open;\n if (!logicPrefix.exec(text)) {\n cursor = open + 2;\n continue;\n }\n const closeSearch = findCloserOnLine(text, \"|*\", logicPrefix.lastIndex);\n if (closeSearch.lineBreak >= 0) {\n cursor = closeSearch.lineBreak + 1;\n continue;\n }\n if (closeSearch.close < 0) break;\n logic.lastIndex = open;\n const logicMatch = logic.exec(text);\n if (logicMatch) {\n matches.push({ index: open, value: logicMatch[0] });\n cursor = logic.lastIndex;\n } else {\n cursor = open + 2;\n }\n }\n return matches;\n }\n const matches: SyntaxMatch[] = [];\n let cursor = 0;\n let nextValue = scanSyntaxMatches(text, syntax, \"value\", cursor, 1)[0];\n let nextLogic = scanSyntaxMatches(text, syntax, \"logic\", cursor, 1)[0];\n while (nextValue || nextLogic) {\n const next =\n !nextLogic || (nextValue && nextValue.index <= nextLogic.index)\n ? nextValue\n : nextLogic;\n matches.push(next);\n cursor = next.index + next.value.length;\n if (next === nextValue || (nextValue && nextValue.index < cursor)) {\n nextValue = scanSyntaxMatches(text, syntax, \"value\", cursor, 1)[0];\n }\n if (next === nextLogic || (nextLogic && nextLogic.index < cursor)) {\n nextLogic = scanSyntaxMatches(text, syntax, \"logic\", cursor, 1)[0];\n }\n }\n return matches;\n}\n\n/** A declared delimiter counts only when it has a non-whitespace character. */\nfunction declaredDelimiter(value: string | undefined): string | null {\n return typeof value === \"string\" && value.trim() !== \"\" ? value : null;\n}\n\n/**\n * The built-in preset whose `value` regex `syntax` uses. Compared by source,\n * so a preset re-created with other flags still resolves.\n */\nfunction presetWithSource(syntax: SyntaxPreset): Required<SyntaxPreset> | null {\n return (\n Object.values(SYNTAX_PRESETS).find(\n (preset) => preset.value.source === syntax.value.source,\n ) ?? null\n );\n}\n\n/**\n * Resolves the autocomplete trigger for a syntax: its declared `opener`, else\n * the opener of the built-in preset whose `value` regex it uses. Returns null\n * for a custom syntax without an opener, which turns autocomplete off.\n */\nexport function getSyntaxTriggerChar(syntax: SyntaxPreset): string | null {\n return (\n declaredDelimiter(syntax.opener) ?? presetWithSource(syntax)?.opener ?? null\n );\n}\n\n/**\n * Resolves the closing delimiter for a syntax (e.g. `}}` for liquid, `|*` for\n * mailchimp): its declared `closer`, else the closer of the built-in preset\n * whose `value` regex it uses. Autocomplete absorbs it after the caret on\n * insert. Returns null for a custom syntax without a closer.\n */\nexport function getSyntaxClosingChar(syntax: SyntaxPreset): string | null {\n return (\n declaredDelimiter(syntax.closer) ?? presetWithSource(syntax)?.closer ?? null\n );\n}\n\nexport function resolveSyntax(\n syntax?: SyntaxPresetName | SyntaxPreset,\n): SyntaxPreset {\n if (!syntax) {\n return SYNTAX_PRESETS.liquid;\n }\n\n if (typeof syntax === \"string\") {\n return SYNTAX_PRESETS[syntax] ?? SYNTAX_PRESETS.liquid;\n }\n\n return syntax;\n}\n\n// --- Merge Tag Utilities ---\n\nfunction anchoredRegex(pattern: RegExp): RegExp {\n const source = pattern.source;\n const flags = pattern.flags.replace(\"g\", \"\");\n return new RegExp(`^${source}$`, flags);\n}\n\nexport function isMergeTagValue(value: string, syntax: SyntaxPreset): boolean {\n const trimmed = value?.trim() || \"\";\n // Handlebars (and similar) value regex is liberal enough to also match\n // logic tags like `{{#each items}}`. Exclude logic-shaped tags so callers\n // that rely on this discriminator (UI segmentation, label rendering)\n // don't misclassify them.\n if (anchoredRegex(syntax.logic).test(trimmed)) {\n return false;\n }\n return anchoredRegex(syntax.value).test(trimmed);\n}\n\nexport function getMergeTagLabel(value: string, mergeTags: MergeTag[]): string {\n const found = mergeTags.find((p) => p.value === value);\n if (found) {\n return found.label;\n }\n return value;\n}\n\nexport function resolveHtmlMergeTagLabels(\n html: string,\n mergeTags: MergeTag[],\n): string {\n return rewriteSpanByAttr(html, \"data-merge-tag\", (value) =>\n getMergeTagLabel(value, mergeTags),\n );\n}\n\n/**\n * The example value configured for `value`, or `undefined` when the tag is\n * unknown or declares none. Unlike `getMergeTagLabel`, which falls back to the\n * raw token, absence is reported as `undefined` so callers can choose their own\n * fallback — Sample mode falls back to the label, never to a raw token.\n */\nexport function getMergeTagSample(\n value: string,\n mergeTags: MergeTag[],\n): string | undefined {\n return mergeTags.find((p) => p.value === value)?.sample;\n}\n\n/**\n * Rewrite rich-text HTML for the previews' Sample mode.\n *\n * A tag **with** a sample is replaced by that value as bare text, wrapper and\n * all — dropping the `<span>` is what removes the merge-tag highlight, so the\n * value reads as ordinary content. A tag **without** one keeps its span and\n * shows its label, so it stays visibly dynamic; that difference is deliberate,\n * and it doubles as a signal that a sample is still unset.\n *\n * The unwrapped output is inert — `data-merge-tag` is gone from it — so this\n * result must only ever reach a preview surface, never `getContent()`, an\n * export or a send.\n */\nexport function substituteHtmlMergeTagSamples(\n html: string,\n mergeTags: MergeTag[],\n): string {\n return rewriteSpanByAttr(\n html,\n \"data-merge-tag\",\n (value) =>\n escapeTagText(\n getMergeTagSample(value, mergeTags) ??\n getMergeTagLabel(value, mergeTags),\n ),\n { unwrap: (value) => getMergeTagSample(value, mergeTags) !== undefined },\n );\n}\n\n/**\n * Whether any configured tag declares a `sample`.\n *\n * Gates the whole feature: with no samples anywhere the previews' Sample view\n * would be identical to the Label view, so the editor defaults to Label and\n * renders no toggle. That keeps the feature invisible until a consumer opts in.\n */\nexport function hasMergeTagSamples(mergeTags: MergeTag[]): boolean {\n return mergeTags.some((tag) => tag.sample !== undefined);\n}\n\n/**\n * Replace declared tokens with their sample values in a plain string — used for\n * values that reach no label-resolving component, namely `html` block content\n * and custom-block field values.\n *\n * Matching is on the exact configured `value`, so consumer text cannot\n * false-positive and `href=\"{{link}}\"` resolves correctly. Tags without a\n * sample are left untouched, which is what keeps a missing sample visible.\n */\nexport function substituteTextMergeTagSamples(\n text: string,\n mergeTags: MergeTag[],\n): string {\n if (!text) return text;\n\n let out = text;\n for (const tag of mergeTags) {\n if (tag.sample === undefined) continue;\n // split/join rather than a RegExp: the token is a literal, so this needs no\n // escaping of regex metacharacters (`{`, `|`, `*` all appear in real syntaxes).\n out = out.split(tag.value).join(tag.sample);\n }\n return out;\n}\n\n/**\n * Escape a sample before it is inlined into rich-text HTML. Samples are\n * consumer-authored strings, so `<`, `&` and quotes would otherwise alter the\n * surrounding markup.\n */\nfunction escapeTagText(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\nexport function containsMergeTag(value: string, syntax: SyntaxPreset): boolean {\n if (!value) return false;\n\n if (builtInPresetOf(syntax)) {\n return (\n scanSyntaxMatches(value, syntax, \"value\", 0, 1).length > 0 ||\n scanSyntaxMatches(value, syntax, \"logic\", 0, 1).length > 0\n );\n }\n\n const valueRegex = new RegExp(syntax.value.source, syntax.value.flags);\n const logicRegex = new RegExp(syntax.logic.source, syntax.logic.flags);\n\n return valueRegex.test(value) || logicRegex.test(value);\n}\n\nexport function isLogicMergeTagValue(\n value: string,\n syntax: SyntaxPreset,\n): boolean {\n return anchoredRegex(syntax.logic).test(value?.trim() || \"\");\n}\n\nexport function getLogicMergeTagKeyword(\n value: string,\n syntax: SyntaxPreset,\n): string {\n const regex = new RegExp(\n syntax.logic.source,\n syntax.logic.flags.replace(\"g\", \"\"),\n );\n const match = value.match(regex);\n return match && match[1] ? match[1].toUpperCase() : value;\n}\n\nexport function resolveHtmlLogicMergeTagLabels(\n html: string,\n syntax: SyntaxPreset,\n): string {\n return rewriteSpanByAttr(html, \"data-logic-merge-tag\", (value) =>\n getLogicMergeTagKeyword(value, syntax),\n );\n}\n\n/**\n * Walk `html` and rewrite the inner text of every `<span … {attrName}=\"…\">…</span>`\n * by passing the attribute value through `relabel`. Linear in `html.length`:\n * each `indexOf` advances the cursor monotonically, and no regex backtracking\n * can run over the whole string.\n *\n * Tag boundaries and attribute values are resolved by `findOpenSpanBoundary` /\n * `getTagAttrValue`, which are quote-aware. A merge-tag value may itself\n * contain `<` / `>` when the consumer configures a custom syntax — Smarty-style\n * `<% $email %>` — and those characters survive attribute serialization\n * verbatim, so anything that treats the first `>` as the tag end reads a\n * truncated attribute and resolves nothing.\n */\nfunction rewriteSpanByAttr(\n html: string,\n attrName: string,\n relabel: (value: string) => string,\n options?: { unwrap?: (value: string) => boolean },\n): string {\n let out = \"\";\n let i = 0;\n while (i < html.length) {\n const open = html.indexOf(\"<span\", i);\n if (open === -1) {\n out += html.substring(i);\n break;\n }\n const afterTagName = html[open + 5];\n if (\n afterTagName !== \">\" &&\n afterTagName !== \" \" &&\n afterTagName !== \"\\t\" &&\n afterTagName !== \"\\n\" &&\n afterTagName !== \"\\r\" &&\n afterTagName !== \"/\"\n ) {\n out += html.substring(i, open + 5);\n i = open + 5;\n continue;\n }\n const { end: openEnd, nextSpan } = findOpenSpanBoundary(html, open + 5);\n if (nextSpan !== -1) {\n out += html.substring(i, nextSpan);\n i = nextSpan;\n continue;\n }\n if (openEnd === -1) {\n out += html.substring(i);\n break;\n }\n const attrs = html.substring(open + 5, openEnd);\n const value = getTagAttrValue(attrs, attrName);\n if (value === null) {\n // Keep this opening tag and continue through its contents, where a\n // nested merge-tag span may appear.\n out += html.substring(i, openEnd + 1);\n i = openEnd + 1;\n continue;\n }\n const closeStart = html.indexOf(\"</span>\", openEnd + 1);\n if (closeStart === -1) {\n out += html.substring(i);\n break;\n }\n const newLabel = relabel(value);\n if (options?.unwrap?.(value)) {\n // Emit the text before the span, then the replacement alone — the open\n // and close tags are dropped, so the span's styling (the merge-tag\n // highlight) no longer applies to it. Decided per tag, so a tag that\n // resolved to a sample loses the highlight while one that fell back to\n // its label keeps it.\n out += html.substring(i, open);\n out += newLabel;\n } else {\n out += html.substring(i, openEnd + 1);\n out += newLabel;\n out += \"</span>\";\n }\n i = closeStart + 7;\n }\n return out;\n}\n","import type { Block } from \"./blocks\";\nimport type { CustomBlockDefinition } from \"./custom-blocks\";\nimport { decodeHtmlEntities, findOpenTagEnd } from \"./html-scan\";\nimport {\n defaultLocaleOf,\n localeCoverage,\n readPath,\n SETTINGS_TRANSLATABLE_FIELDS,\n sourceHash,\n translatableFields,\n type LocalizedText,\n} from \"./localization\";\nimport { scanMergeTagSpans } from \"./merge-tag-html\";\nimport {\n builtInPresetOf,\n scanSyntaxMatches,\n type SyntaxPreset,\n} from \"./merge-tags\";\nimport type { Operation } from \"./operations\";\nimport type { TemplateContent } from \"./template\";\n\n/** Only these translatable fields contain rich-text HTML. */\nexport const TRANSLATABLE_HTML_FIELDS: Readonly<\n Record<string, readonly string[]>\n> = {\n title: [\"content\"],\n paragraph: [\"content\"],\n};\n\ntype Format = \"html\" | \"text\";\ntype Range = {\n start: number;\n end: number;\n markup: string;\n attribute: boolean;\n term?: string;\n};\n\nfunction attributeRanges(html: string): { start: number; end: number }[] {\n const ranges: { start: number; end: number }[] = [];\n const tags = /<[a-z][\\w:-]*\\b/gi;\n while (tags.exec(html)) {\n const end = findOpenTagEnd(html, tags.lastIndex);\n if (end < 0) break;\n const from = tags.lastIndex;\n const attrs = html.slice(from, end);\n const pattern =\n /[^\\s\"'<>/=]+\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))/g;\n for (let attr; (attr = pattern.exec(attrs));) {\n const value = attr[1] ?? attr[2] ?? attr[3];\n const valueEnd =\n from + pattern.lastIndex - (attr[3] === undefined ? 1 : 0);\n ranges.push({ start: valueEnd - value.length, end: valueEnd });\n }\n tags.lastIndex = end + 1;\n }\n return ranges;\n}\n\nfunction tagRanges(\n text: string,\n syntax: SyntaxPreset,\n format: Format,\n): Range[] {\n const chips = format === \"html\" ? scanMergeTagSpans(text) : [];\n const attributes = format === \"html\" ? attributeRanges(text) : [];\n const ranges: Range[] = chips.map((chip) => ({ ...chip, attribute: false }));\n let attributeIndex = 0;\n const builtin = builtInPresetOf(syntax) !== undefined;\n const raw = (start: number, end: number) => {\n const segment = text.slice(start, end);\n const kinds = [\"logic\", \"value\"] as const;\n const nextMatches: ({ index: number; value: string } | null | undefined)[] =\n builtin\n ? kinds.map((kind) => scanSyntaxMatches(segment, syntax, kind, 0, 1)[0])\n : [undefined, undefined];\n const regexes = builtin\n ? null\n : [syntax.logic, syntax.value].map(\n (pattern) =>\n new RegExp(\n pattern.source,\n pattern.flags.replace(/[gy]/g, \"\") + \"g\",\n ),\n );\n let cursor = 0;\n while (cursor < segment.length) {\n const matches = builtin\n ? nextMatches.flatMap((match) => (match ? [match] : []))\n : regexes!.flatMap((pattern, index) => {\n const cached = nextMatches[index];\n if (\n cached === undefined ||\n (cached !== null && cached.index < cursor)\n ) {\n pattern.lastIndex = cursor;\n let match = pattern.exec(segment);\n while (match && match[0].length === 0) {\n pattern.lastIndex = match.index + 1;\n match = pattern.exec(segment);\n }\n nextMatches[index] = match\n ? { index: match.index, value: match[0] }\n : null;\n }\n return nextMatches[index] ? [nextMatches[index]!] : [];\n });\n matches.sort(\n (a, b) => a.index - b.index || a.value.length - b.value.length,\n );\n const match = matches[0];\n if (!match) break;\n const from = start + match.index;\n const to = from + match.value.length;\n while (attributes[attributeIndex]?.end <= from) attributeIndex++;\n ranges.push({\n start: from,\n end: to,\n markup: match.value,\n attribute:\n attributes[attributeIndex] !== undefined &&\n from >= attributes[attributeIndex].start &&\n to <= attributes[attributeIndex].end,\n });\n cursor = match.index + match.value.length;\n if (builtin) {\n for (let index = 0; index < kinds.length; index++) {\n if (nextMatches[index] && nextMatches[index]!.index < cursor) {\n nextMatches[index] = scanSyntaxMatches(\n segment,\n syntax,\n kinds[index],\n cursor,\n 1,\n )[0];\n }\n }\n }\n }\n };\n let cursor = 0;\n for (const chip of chips) {\n raw(cursor, chip.start);\n cursor = chip.end;\n }\n raw(cursor, text.length);\n return ranges.sort((a, b) => a.start - b.start);\n}\n\n/** Map decoded boundaries to source offsets, excluding reference interiors. */\nfunction decodedTermText(text: string): { text: string; offsets?: number[] } {\n if (!text.includes(\"&\")) return { text };\n let decoded = \"\";\n const offsets = [0];\n let cursor = 0;\n const literal = (end: number) => {\n decoded += text.slice(cursor, end);\n while (cursor < end) offsets.push(++cursor);\n };\n for (const match of text.matchAll(\n /&(?:#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g,\n )) {\n literal(match.index);\n const value = decodeHtmlEntities(match[0]);\n decoded += value;\n for (let i = 1; i < value.length; i++) offsets.push(-1);\n cursor = match.index + match[0].length;\n offsets.push(cursor);\n }\n literal(text.length);\n return { text: decoded, offsets };\n}\n\n/**\n * Compiled term patterns, keyed by the terms' content so a list changed in\n * place compiles again. `null` when no term is left after trimming. Only the\n * most recent lists are kept.\n */\nconst termPatterns = new Map<string, RegExp | null>();\nconst TERM_PATTERN_LIMIT = 32;\n\nfunction termPattern(terms: readonly string[]): RegExp | null {\n const key = JSON.stringify(terms);\n let pattern = termPatterns.get(key);\n if (pattern === undefined) {\n const alternatives = terms\n .map((term) => term.trim())\n .filter(Boolean)\n .sort((a, b) => b.length - a.length)\n .map((term) => term.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"));\n pattern = alternatives.length\n ? new RegExp(\n `(?<![\\\\p{L}\\\\p{N}_])(?:${alternatives.join(\"|\")})(?![\\\\p{L}\\\\p{N}_])`,\n \"gu\",\n )\n : null;\n if (termPatterns.size >= TERM_PATTERN_LIMIT)\n termPatterns.delete(termPatterns.keys().next().value!);\n termPatterns.set(key, pattern);\n }\n return pattern;\n}\n\nfunction termRanges(\n text: string,\n format: Format,\n terms: readonly string[],\n): Range[] {\n const pattern = terms.length ? termPattern(terms) : null;\n if (!pattern) return [];\n const segments: { start: number; end: number; attribute: boolean }[] = [];\n if (format === \"text\")\n segments.push({ start: 0, end: text.length, attribute: false });\n else {\n segments.push(\n ...attributeRanges(text).map((range) => ({ ...range, attribute: true })),\n );\n const markup = /<(?:\\/?[a-z][\\w:-]*\\b|!--|!|\\?)/gi;\n let cursor = 0;\n for (let match; (match = markup.exec(text));) {\n segments.push({ start: cursor, end: match.index, attribute: false });\n const end =\n match[0] === \"<!--\"\n ? text.indexOf(\"-->\", markup.lastIndex)\n : findOpenTagEnd(text, markup.lastIndex);\n if (end < 0) return [];\n cursor = end + (match[0] === \"<!--\" ? 3 : 1);\n markup.lastIndex = cursor;\n }\n segments.push({ start: cursor, end: text.length, attribute: false });\n }\n const ranges: Range[] = [];\n for (const segment of segments) {\n pattern.lastIndex = 0;\n const value = text.slice(segment.start, segment.end);\n const decoded =\n format === \"html\"\n ? decodedTermText(value)\n : { text: value, offsets: undefined };\n for (let match; (match = pattern.exec(decoded.text));) {\n const from = decoded.offsets?.[match.index] ?? match.index;\n const to =\n decoded.offsets?.[match.index + match[0].length] ??\n match.index + match[0].length;\n if (from < 0 || to < 0) continue;\n const start = segment.start + from;\n const end = segment.start + to;\n ranges.push({\n start,\n end,\n markup: text.slice(start, end),\n attribute: segment.attribute,\n term: match[0],\n });\n }\n }\n return ranges;\n}\n\nfunction maskingRanges(\n text: string,\n syntax: SyntaxPreset,\n format: Format,\n options?: { doNotTranslate?: readonly string[] },\n): Range[] {\n const tags = tagRanges(text, syntax, format);\n const terms = termRanges(text, format, options?.doNotTranslate ?? []).filter(\n (term) => !tags.some((tag) => term.start < tag.end && term.end > tag.start),\n );\n return [...tags, ...terms].sort((a, b) => a.start - b.start);\n}\n\nfunction maskedText(text: string, ranges: Range[], ids: number[]): string {\n let out = \"\";\n let cursor = 0;\n ranges.forEach((range, i) => {\n out += text.slice(cursor, range.start);\n out += range.attribute ? `__x${ids[i]}__` : `<x id=\"${ids[i]}\"/>`;\n cursor = range.end;\n });\n return out + text.slice(cursor);\n}\n\n/** Mask chips whole in HTML, raw tags and configured terms in both formats. */\nexport function maskTags(\n text: string,\n syntax: SyntaxPreset,\n format: Format,\n options?: { doNotTranslate?: readonly string[] },\n): { text: string; tokens: string[] } {\n const ranges = maskingRanges(text, syntax, format, options);\n return {\n text: maskedText(\n text,\n ranges,\n ranges.map((_, i) => i + 1),\n ),\n tokens: ranges.map((range) => range.markup),\n };\n}\n\n/** Restore original bytes only when every source placeholder occurs exactly once. */\nexport function unmaskTags(text: string, tokens: string[]): string | null {\n const seen = new Set<number>();\n let valid = true;\n const result = text.replace(\n /<x id=\"(\\d+)\"\\s*\\/>|<x id=\"(\\d+)\"><\\/x>|__x(\\d+)__/g,\n (_match, self: string, paired: string, attribute: string) => {\n const id = Number(self ?? paired ?? attribute);\n if (id < 1 || id > tokens.length || seen.has(id)) valid = false;\n seen.add(id);\n return tokens[id - 1] ?? \"\";\n },\n );\n return valid && seen.size === tokens.length ? result : null;\n}\n\nfunction maskTranslation(\n text: string,\n tokens: string[],\n syntax: SyntaxPreset,\n format: Format,\n options?: { doNotTranslate?: readonly string[] },\n): string | null {\n const ranges = maskingRanges(text, syntax, format, options);\n const used = new Set<number>();\n const claim = (matches: (token: string) => boolean) => {\n const index = tokens.findIndex(\n (token, i) => !used.has(i) && matches(token),\n );\n if (index >= 0) used.add(index);\n return index;\n };\n // Exact spellings first, so another spelling of a term keeps its own bytes.\n const indexes = ranges.map((range) =>\n claim((token) => token === range.markup),\n );\n ranges.forEach((range, i) => {\n if (indexes[i] < 0 && range.term !== undefined && format === \"html\")\n indexes[i] = claim((token) => decodeHtmlEntities(token) === range.term);\n });\n // A term beyond the protected occurrences is plain text; a tag isn't.\n if (\n used.size !== tokens.length ||\n ranges.some((range, i) => indexes[i] < 0 && range.term === undefined)\n )\n return null;\n const matched = ranges.filter((_, i) => indexes[i] >= 0);\n return maskedText(\n text,\n matched,\n indexes.filter((index) => index >= 0).map((index) => index + 1),\n );\n}\n\nexport interface LocaleString {\n id: string;\n format: \"html\" | \"text\";\n /** The masked default value. */\n source: string;\n /** The hash of the unmasked default at extraction time. */\n sourceHash: string;\n /** The stored translation masked with the source's token ids. */\n text?: string;\n}\n\ntype Field = {\n target: { kind: \"block\"; blockId: string } | { kind: \"settings\" };\n path: string;\n source: string;\n format: Format;\n text?: LocalizedText;\n};\n\nfunction eligibleFields(\n content: TemplateContent,\n locale: string,\n definitions: readonly CustomBlockDefinition[] = [],\n): Map<string, Field> {\n const fields = new Map<string, Field>();\n if (\n locale === defaultLocaleOf(content) ||\n !content.settings.locales?.includes(locale)\n )\n return fields;\n const visit = (\n fieldTarget: Field[\"target\"],\n target: Block | TemplateContent[\"settings\"],\n paths: readonly string[],\n type?: string,\n ) => {\n const layer = target.l10n?.[locale];\n for (const path of paths) {\n const source = readPath(target, path);\n if (\n typeof source !== \"string\" ||\n source === \"\" ||\n Object.keys(layer?.set ?? {}).some(\n (key) => key === path || path.startsWith(`${key}.`),\n )\n )\n continue;\n const prefix =\n fieldTarget.kind === \"block\" ? fieldTarget.blockId : \"settings\";\n fields.set(`${prefix}/${path}`, {\n target: fieldTarget,\n path,\n source,\n format:\n type && TRANSLATABLE_HTML_FIELDS[type]?.includes(path)\n ? \"html\"\n : \"text\",\n text: layer?.text?.[path],\n });\n }\n };\n const walk = (blocks: Block[]) => {\n for (const block of blocks) {\n if (block.l10n?.[locale]?.hidden) continue;\n if (block.type !== \"html\")\n visit(\n { kind: \"block\", blockId: block.id },\n block,\n translatableFields(block, definitions),\n block.type,\n );\n if (block.type === \"section\")\n for (const column of block.children) walk(column);\n else if (block.type === \"wrapper\") walk(block.children);\n }\n };\n walk(content.blocks);\n visit({ kind: \"settings\" }, content.settings, SETTINGS_TRANSLATABLE_FIELDS);\n return fields;\n}\n\n/** Extract eligible fields in document order, with settings last. */\nexport function localeStrings(\n content: TemplateContent,\n locale: string,\n options: {\n definitions?: readonly CustomBlockDefinition[];\n syntax: SyntaxPreset;\n only: \"gaps\" | \"all\";\n blockId?: string;\n doNotTranslate?: readonly string[];\n },\n): { strings: LocaleString[]; tokens: Record<string, string[]> } {\n // Coverage lists every eligible field (its default isn't empty), so only\n // gaps need it to select.\n const coverage =\n options.only === \"all\"\n ? null\n : localeCoverage(content, locale, options.definitions);\n const selected =\n coverage && new Set([...coverage.missing, ...coverage.stale]);\n const strings: LocaleString[] = [];\n const tokens: Record<string, string[]> = {};\n for (const [id, field] of eligibleFields(\n content,\n locale,\n options.definitions,\n )) {\n if (\n (selected && !selected.has(id)) ||\n (options.blockId !== undefined &&\n (field.target.kind !== \"block\" ||\n field.target.blockId !== options.blockId))\n )\n continue;\n const masked = maskTags(\n field.source,\n options.syntax,\n field.format,\n options,\n );\n const text = field.text\n ? maskTranslation(\n field.text.value,\n masked.tokens,\n options.syntax,\n field.format,\n options,\n )\n : undefined;\n strings.push({\n id,\n format: field.format,\n source: masked.text,\n sourceHash: sourceHash(field.source),\n ...(text === undefined || text === null ? {} : { text }),\n });\n tokens[id] = masked.tokens;\n }\n return { strings, tokens };\n}\n\n/** Build locale operations without mutating content; preserve each extraction hash. */\nexport function applyLocaleStrings(\n content: TemplateContent,\n locale: string,\n values: { id: string; text: string; sourceHash: string }[],\n options: {\n definitions?: readonly CustomBlockDefinition[];\n syntax: SyntaxPreset;\n tokens: Record<string, string[]>;\n doNotTranslate?: readonly string[];\n },\n): {\n operations: Operation[];\n rejected: {\n id: string;\n reason: \"tags_changed\" | \"unknown_field\" | \"not_translatable\";\n }[];\n} {\n const fields = eligibleFields(content, locale, options.definitions);\n const blocks = new Map<string, Block>();\n const walk = (items: Block[]) => {\n for (const block of items) {\n blocks.set(block.id, block);\n if (block.type === \"section\")\n for (const column of block.children) walk(column);\n else if (block.type === \"wrapper\") walk(block.children);\n }\n };\n walk(content.blocks);\n const grouped = new Map<string, Record<string, LocalizedText>>();\n let settingsText: Record<string, LocalizedText> | undefined;\n const rejected: {\n id: string;\n reason: \"tags_changed\" | \"unknown_field\" | \"not_translatable\";\n }[] = [];\n for (const value of values) {\n const field = fields.get(value.id);\n if (!field) {\n const separator = value.id.lastIndexOf(\"/\");\n const blockId = value.id.slice(0, separator);\n const targets =\n blockId === \"settings\"\n ? [blocks.get(blockId), content.settings]\n : [blocks.get(blockId)];\n rejected.push({\n id: value.id,\n reason:\n separator < 0 ||\n !targets.some(\n (target) =>\n target &&\n readPath(target, value.id.slice(separator + 1)) !== undefined,\n )\n ? \"unknown_field\"\n : \"not_translatable\",\n });\n continue;\n }\n const tokens = Object.hasOwn(options.tokens, value.id)\n ? options.tokens[value.id]\n : undefined;\n const text = tokens ? unmaskTags(value.text, tokens) : null;\n if (\n !tokens ||\n text === null ||\n maskTranslation(text, tokens, options.syntax, field.format, options) ===\n null\n ) {\n rejected.push({ id: value.id, reason: \"tags_changed\" });\n continue;\n }\n const texts =\n field.target.kind === \"settings\"\n ? (settingsText ??= {})\n : (grouped.get(field.target.blockId) ?? {});\n texts[field.path] = { value: text, sourceHash: value.sourceHash };\n if (field.target.kind === \"block\") grouped.set(field.target.blockId, texts);\n }\n const operations: Operation[] = [];\n for (const [blockId, text] of grouped)\n operations.push({ op: \"updateBlockLocale\", blockId, locale, text });\n if (settingsText)\n operations.push({ op: \"updateSettingsLocale\", locale, text: settingsText });\n return { operations, rejected };\n}\n","/** The module members needed by the custom-block engine factory. */\nexport interface CustomBlockLiquidModule {\n Liquid: new (...args: any[]) => any;\n}\n\n/** The shared Liquid engine for custom-block templates. Pass the engine module. */\nexport function createCustomBlockLiquid<M extends CustomBlockLiquidModule>(\n module: M,\n): InstanceType<M[\"Liquid\"]> {\n // outputEscape covers {{ }}, echo and cycle output from liquidjs 10.30.1,\n // the peer floor. Registering an escaping tag on top escapes twice.\n return new module.Liquid({\n strictVariables: false,\n strictFilters: false,\n outputEscape: \"escape\",\n // File tags resolve only against this empty map, never disk or network.\n templates: {},\n }) as InstanceType<M[\"Liquid\"]>;\n}\n","import type {\n Block,\n BlockStyles,\n BlockType,\n ButtonBlock,\n CountdownBlock,\n CustomBlock,\n DividerBlock,\n HtmlBlock,\n ImageBlock,\n MenuBlock,\n ParagraphBlock,\n SectionBlock,\n SlotBlock,\n SocialIconsBlock,\n SpacerBlock,\n SpacingValue,\n TableBlock,\n TableCellData,\n TableRowData,\n TitleBlock,\n VideoBlock,\n WrapperBlock,\n} from \"./blocks\";\nimport { safeClone } from \"./clone\";\nimport type { CustomBlockDefinition, CustomBlockField } from \"./custom-blocks\";\nimport type { BlockDefaults } from \"./defaults\";\nimport {\n BUTTON_BLOCK_DEFAULTS,\n COUNTDOWN_BLOCK_DEFAULTS,\n deepMergeDefaults,\n DIVIDER_BLOCK_DEFAULTS,\n HTML_BLOCK_DEFAULTS,\n IMAGE_BLOCK_DEFAULTS,\n MENU_BLOCK_DEFAULTS,\n PARAGRAPH_BLOCK_DEFAULTS,\n SECTION_BLOCK_DEFAULTS,\n SOCIAL_ICONS_BLOCK_DEFAULTS,\n SPACER_BLOCK_DEFAULTS,\n TABLE_BLOCK_DEFAULTS,\n TITLE_BLOCK_DEFAULTS,\n VIDEO_BLOCK_DEFAULTS,\n} from \"./defaults\";\n\n/**\n * `base` is copied because it carries the `*_BLOCK_DEFAULTS` constants' own\n * nested objects (e.g. `buttonPadding`): every block made from it would share\n * them, and mutating one block's would change the defaults and every other\n * block. `partial` is the caller's and is merged as given — whatever it passes\n * directly lands in the block by reference.\n */\nfunction applyDefaults<T extends object>(\n base: T,\n partial: Partial<T> | undefined,\n): T {\n const ownBase = safeClone(base);\n if (!partial || Object.keys(partial).length === 0) return ownBase;\n return deepMergeDefaults(ownBase, partial);\n}\n\n/**\n * A defaults entry copied for one block. Defaults seed every block of their\n * type, so a nested value merged in as-is would be shared by all of them.\n */\nfunction copyDefaults<T>(defaults: T | undefined): T | undefined {\n return defaults === undefined ? undefined : safeClone(defaults);\n}\n\nexport function generateId(): string {\n return crypto.randomUUID();\n}\n\nfunction createDefaultSpacing(value = 0): SpacingValue {\n return { top: value, right: value, bottom: value, left: value };\n}\n\nfunction createDefaultStyles(padding = 10): BlockStyles {\n return {\n padding: createDefaultSpacing(padding),\n };\n}\n\nexport function createTitleBlock(\n partial: Partial<TitleBlock> = {},\n): TitleBlock {\n const base: TitleBlock = {\n id: generateId(),\n type: \"title\",\n ...TITLE_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as TitleBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createParagraphBlock(\n partial: Partial<ParagraphBlock> = {},\n): ParagraphBlock {\n const base: ParagraphBlock = {\n id: generateId(),\n type: \"paragraph\",\n ...PARAGRAPH_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as ParagraphBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createImageBlock(\n partial: Partial<ImageBlock> = {},\n): ImageBlock {\n const base: ImageBlock = {\n id: generateId(),\n type: \"image\",\n ...IMAGE_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as ImageBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createButtonBlock(\n partial: Partial<ButtonBlock> = {},\n): ButtonBlock {\n const base: ButtonBlock = {\n id: generateId(),\n type: \"button\",\n ...BUTTON_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as ButtonBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createDividerBlock(\n partial: Partial<DividerBlock> = {},\n): DividerBlock {\n const base: DividerBlock = {\n id: generateId(),\n type: \"divider\",\n ...DIVIDER_BLOCK_DEFAULTS,\n styles: createDefaultStyles(20),\n } as DividerBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createSectionBlock(\n partial: Partial<SectionBlock> = {},\n): SectionBlock {\n const base: SectionBlock = {\n id: generateId(),\n type: \"section\",\n ...SECTION_BLOCK_DEFAULTS,\n children: [[]],\n styles: createDefaultStyles(20),\n } as SectionBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createVideoBlock(\n partial: Partial<VideoBlock> = {},\n): VideoBlock {\n const base: VideoBlock = {\n id: generateId(),\n type: \"video\",\n ...VIDEO_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as VideoBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createSocialIconsBlock(\n partial: Partial<SocialIconsBlock> = {},\n): SocialIconsBlock {\n const base: SocialIconsBlock = {\n id: generateId(),\n type: \"social\",\n icons: [],\n ...SOCIAL_ICONS_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as SocialIconsBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createSpacerBlock(\n partial: Partial<SpacerBlock> = {},\n): SpacerBlock {\n const base: SpacerBlock = {\n id: generateId(),\n type: \"spacer\",\n ...SPACER_BLOCK_DEFAULTS,\n styles: createDefaultStyles(0),\n } as SpacerBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createHtmlBlock(partial: Partial<HtmlBlock> = {}): HtmlBlock {\n const base: HtmlBlock = {\n id: generateId(),\n type: \"html\",\n ...HTML_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as HtmlBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createMenuBlock(partial: Partial<MenuBlock> = {}): MenuBlock {\n const base: MenuBlock = {\n id: generateId(),\n type: \"menu\",\n items: [],\n ...MENU_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as MenuBlock;\n return applyDefaults(base, partial);\n}\n\nfunction createDefaultTableRows(columns: number, rows: number): TableRowData[] {\n return Array.from({ length: rows }, () => ({\n id: generateId(),\n cells: Array.from({ length: columns }, (): TableCellData => ({\n id: generateId(),\n content: \"\",\n })),\n }));\n}\n\nexport function createTableBlock(\n partial: Partial<TableBlock> = {},\n): TableBlock {\n const base: TableBlock = {\n id: generateId(),\n type: \"table\",\n rows: createDefaultTableRows(3, 3),\n ...TABLE_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as TableBlock;\n return applyDefaults(base, partial);\n}\n\nexport function createCountdownBlock(\n partial: Partial<CountdownBlock> = {},\n): CountdownBlock {\n const base: CountdownBlock = {\n id: generateId(),\n type: \"countdown\",\n ...COUNTDOWN_BLOCK_DEFAULTS,\n styles: createDefaultStyles(),\n } as CountdownBlock;\n return applyDefaults(base, partial);\n}\n\nfunction getFieldDefault(field: CustomBlockField): unknown {\n if (field.type === \"repeatable\") {\n return field.default ?? [];\n }\n if (field.type === \"boolean\") {\n return field.default ?? false;\n }\n if (field.type === \"number\") {\n return field.default ?? 0;\n }\n\n return field.default ?? \"\";\n}\n\nexport function createCustomBlock(\n definition: CustomBlockDefinition,\n): CustomBlock {\n const fieldValues: Record<string, unknown> = {};\n\n for (const field of definition.fields) {\n fieldValues[field.key] = copyDefaults(getFieldDefault(field));\n }\n\n const styles = applyDefaults(\n createDefaultStyles(),\n copyDefaults(definition.defaultStyles),\n );\n\n return {\n id: generateId(),\n type: \"custom\",\n customType: definition.type,\n fieldValues,\n styles,\n ...(definition.dataSource ? { dataSourceFetched: false } : {}),\n };\n}\n\n/** Layout-only. Use this to build a layout; createBlock(\"slot\") throws. */\nexport function createSlotBlock(): SlotBlock {\n return {\n id: generateId(),\n type: \"slot\",\n styles: createDefaultStyles(0),\n };\n}\n\n/** Layout-only. Use this to build a layout; createBlock(\"wrapper\") throws. */\nexport function createWrapperBlock(\n partial: Partial<WrapperBlock> = {},\n): WrapperBlock {\n const base: WrapperBlock = {\n id: generateId(),\n type: \"wrapper\",\n children: [],\n styles: createDefaultStyles(0),\n };\n return applyDefaults(base, partial);\n}\n\nexport function createBlock(\n type: BlockType,\n blockDefaults?: BlockDefaults,\n): Block {\n switch (type) {\n case \"section\":\n return createSectionBlock(copyDefaults(blockDefaults?.section));\n case \"title\":\n return createTitleBlock(copyDefaults(blockDefaults?.title));\n case \"paragraph\":\n return createParagraphBlock(copyDefaults(blockDefaults?.paragraph));\n case \"image\":\n return createImageBlock(copyDefaults(blockDefaults?.image));\n case \"button\":\n return createButtonBlock(copyDefaults(blockDefaults?.button));\n case \"divider\":\n return createDividerBlock(copyDefaults(blockDefaults?.divider));\n case \"video\":\n return createVideoBlock(copyDefaults(blockDefaults?.video));\n case \"social\":\n return createSocialIconsBlock(copyDefaults(blockDefaults?.social));\n case \"spacer\":\n return createSpacerBlock(copyDefaults(blockDefaults?.spacer));\n case \"html\":\n return createHtmlBlock(copyDefaults(blockDefaults?.html));\n case \"menu\":\n return createMenuBlock(copyDefaults(blockDefaults?.menu));\n case \"table\":\n return createTableBlock(copyDefaults(blockDefaults?.table));\n case \"countdown\":\n return createCountdownBlock(copyDefaults(blockDefaults?.countdown));\n case \"slot\":\n throw new Error(\n \"[Templatical] slot cannot be inserted into content. Use createSlotBlock() to build a layout.\",\n );\n case \"wrapper\":\n throw new Error(\n \"[Templatical] wrapper cannot be inserted into content. Use createWrapperBlock() to build a layout.\",\n );\n default:\n throw new Error(`Unknown block type: ${type}`);\n }\n}\n\nfunction remapL10n(\n block: Record<string, unknown>,\n ids: Map<string, Map<string, string>>,\n): void {\n const l10n = block.l10n as\n | Record<\n string,\n { text?: Record<string, unknown>; set?: Record<string, unknown> }\n >\n | undefined;\n if (!l10n || ids.size === 0) return;\n // Scope each id to its original array path; cells in separate rows may\n // reuse an id. Walk the clone's new ids while retaining the old path.\n const rename = (path: string) => {\n let current: unknown = block;\n let parentPath = \"\";\n return path\n .split(\".\")\n .map((segment) => {\n const renamed = Array.isArray(current)\n ? (ids.get(parentPath)?.get(segment) ?? segment)\n : segment;\n current = Array.isArray(current)\n ? current.find((item) => (item as { id?: string }).id === renamed)\n : (current as Record<string, unknown> | undefined)?.[segment];\n parentPath = parentPath ? `${parentPath}.${segment}` : segment;\n return renamed;\n })\n .join(\".\");\n };\n for (const layer of Object.values(l10n)) {\n for (const kind of [\"text\", \"set\"] as const) {\n const entries = layer[kind];\n if (entries)\n layer[kind] = Object.fromEntries(\n Object.entries(entries).map(([k, v]) => [rename(k), v]),\n );\n }\n }\n}\n\nexport function cloneBlock(block: Block): Block {\n const cloned = JSON.parse(JSON.stringify(block)) as Block;\n cloned.id = generateId();\n const ids = new Map<string, Map<string, string>>();\n const remint = (element: { id: string }, parentPath: string): string => {\n const oldId = element.id;\n element.id = generateId();\n let scoped = ids.get(parentPath);\n if (!scoped) {\n scoped = new Map();\n ids.set(parentPath, scoped);\n }\n scoped.set(oldId, element.id);\n return oldId;\n };\n\n if (cloned.type === \"table\") {\n for (const row of cloned.rows) {\n const oldRowId = remint(row, \"rows\");\n for (const cell of row.cells) remint(cell, `rows.${oldRowId}.cells`);\n }\n }\n\n if (cloned.type === \"menu\") {\n for (const item of cloned.items) remint(item, \"items\");\n }\n\n if (cloned.type === \"social\") {\n for (const icon of cloned.icons) remint(icon, \"icons\");\n }\n\n if (cloned.type === \"section\") {\n cloned.children = cloned.children.map((column) =>\n column.map((child) => cloneBlock(child)),\n );\n }\n\n if (cloned.type === \"wrapper\") {\n cloned.children = cloned.children.map((c) => cloneBlock(c));\n }\n\n remapL10n(cloned as unknown as Record<string, unknown>, ids);\n return cloned;\n}\n","import type { Block, WrapperBlock } from \"./blocks\";\nimport { safeClone } from \"./clone\";\nimport { cloneBlock } from \"./factory\";\nimport { isSection, isSlot, isWrapper } from \"./guards\";\nimport type { TemplateContent } from \"./template\";\n\nconst EXACTLY_ONE_SLOT =\n \"[Templatical] layout: must contain exactly one slot block\";\nconst SLOT_NESTED_IN_SECTION =\n \"[Templatical] layout: slot must be a top-level or wrapper child, not nested in a section\";\nconst WRAPPER_IN_WRAPPER =\n \"[Templatical] layout: a wrapper cannot contain a wrapper\";\nconst NESTED_MJ_WRAPPER =\n \"[Templatical] layout: a wrapper around the slot cannot contain blocks that emit mj-wrapper (section.wrapper)\";\nconst SLOT_IN_CONTENT = \"[Templatical] slot is not a valid content block\";\nconst SECTION_WRAPPER_IN_WRAPPER =\n \"[Templatical] layout: a wrapper cannot contain a section with its own wrapper (section.wrapper)\";\nconst WRAPPER_IN_CONTENT = \"[Templatical] wrapper is not a valid content block\";\n\nfunction walkBlocks(\n blocks: Block[],\n visit: (\n block: Block,\n parent: Block | null,\n insideSection: boolean,\n insideWrapper: boolean,\n ) => void,\n parent: Block | null = null,\n insideSection = false,\n insideWrapper = false,\n): void {\n for (const block of blocks) {\n visit(block, parent, insideSection, insideWrapper);\n if (isSection(block)) {\n for (const column of block.children) {\n walkBlocks(column, visit, block, true, insideWrapper);\n }\n } else if (isWrapper(block)) {\n walkBlocks(block.children, visit, block, insideSection, true);\n }\n }\n}\n\n/** Throw if `layout` does not contain exactly one legal slot. */\nexport function validateLayout(layout: TemplateContent): void {\n let slotCount = 0;\n walkBlocks(layout.blocks, (block, _parent, insideSection, insideWrapper) => {\n if (insideWrapper && isSection(block) && block.wrapper) {\n throw new Error(SECTION_WRAPPER_IN_WRAPPER);\n }\n if (isSlot(block)) {\n slotCount += 1;\n if (insideSection) {\n throw new Error(SLOT_NESTED_IN_SECTION);\n }\n }\n if (isWrapper(block)) {\n if (insideSection) {\n throw new Error(SLOT_NESTED_IN_SECTION);\n }\n if (block.children.some(isWrapper)) {\n throw new Error(WRAPPER_IN_WRAPPER);\n }\n }\n });\n if (slotCount !== 1) {\n throw new Error(EXACTLY_ONE_SLOT);\n }\n}\n\nexport function assertNoSlotInContent(content: TemplateContent): void {\n walkBlocks(content.blocks, (block) => {\n if (isSlot(block)) {\n throw new Error(SLOT_IN_CONTENT);\n }\n });\n}\n\nexport function assertNoWrapperInContent(content: TemplateContent): void {\n walkBlocks(content.blocks, (block) => {\n if (isWrapper(block)) {\n throw new Error(WRAPPER_IN_CONTENT);\n }\n });\n}\n\n/** True iff the one slot is a direct child of a wrapper (the card). */\nexport function layoutWrapsSlot(layout: TemplateContent): boolean {\n let wrapped = false;\n walkBlocks(layout.blocks, (block, parent) => {\n if (isSlot(block) && parent !== null && isWrapper(parent)) {\n wrapped = true;\n }\n });\n return wrapped;\n}\n\nfunction cloneLayoutBlock(block: Block): Block {\n if (isSlot(block)) return block;\n if (isWrapper(block)) {\n const cloned = cloneBlock({ ...block, children: [] }) as WrapperBlock;\n cloned.children = block.children.map(cloneLayoutBlock);\n return cloned;\n }\n return cloneBlock(block);\n}\n\nfunction findSlotLocation(\n blocks: Block[],\n): { parent: Block[]; index: number } | null {\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (isSlot(block)) {\n return { parent: blocks, index: i };\n }\n if (isWrapper(block)) {\n const nested = findSlotLocation(block.children);\n if (nested) return nested;\n }\n }\n return null;\n}\n\nfunction emitsMjWrapper(blocks: Block[]): boolean {\n for (const block of blocks) {\n if (isSection(block)) {\n if (block.wrapper) return true;\n for (const column of block.children) {\n if (emitsMjWrapper(column)) return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Overlay `layout` around `content`. Clones both; remints layout ids.\n * Layout wins only `settings.backgroundColor`.\n */\nexport function applyLayout(\n layout: TemplateContent,\n content: TemplateContent,\n): TemplateContent {\n validateLayout(layout);\n assertNoSlotInContent(content);\n assertNoWrapperInContent(content);\n\n if (layoutWrapsSlot(layout) && emitsMjWrapper(content.blocks)) {\n throw new Error(NESTED_MJ_WRAPPER);\n }\n\n const blocks = layout.blocks.map(cloneLayoutBlock);\n const location = findSlotLocation(blocks);\n if (!location) {\n throw new Error(EXACTLY_ONE_SLOT);\n }\n location.parent.splice(location.index, 1, ...safeClone(content.blocks));\n\n return {\n blocks,\n settings: {\n ...safeClone(content.settings),\n backgroundColor: layout.settings.backgroundColor,\n },\n };\n}\n","/** URL schemes accepted in links displayed in the editor. */\nexport const SAFE_LINK_SCHEMES = Object.freeze([\n \"http\",\n \"https\",\n \"mailto\",\n \"tel\",\n \"ftp\",\n \"ftps\",\n \"sms\",\n \"xmpp\",\n \"cid\",\n] as const);\n\n/** Script-capable or arbitrary-payload URL schemes reported by the link linter. */\nexport const DANGEROUS_SCRIPT_SCHEMES = Object.freeze([\n \"javascript\",\n \"data\",\n \"vbscript\",\n] as const);\n\n/** Normalize a URL before checking its scheme, as the WHATWG URL parser does. */\nexport function normalizeUrlForSchemeCheck(value: string): string {\n return value\n .replace(/[\\t\\n\\r]/g, \"\")\n .replace(/^[\\u0000-\\u0020]+/, \"\")\n .trimEnd();\n}\n\n/** Return the lower-case scheme, or null for a relative or fragment URL. */\nexport function extractUrlScheme(value: string): string | null {\n const match = /^([a-z][a-z0-9+.-]*):/i.exec(\n normalizeUrlForSchemeCheck(value),\n );\n return match ? match[1].toLowerCase() : null;\n}\n\n/** Only these image data MIME types are accepted, and only in src. */\nexport const DATA_IMAGE_SRC_PATTERN =\n /^data:image\\/(png|jpe?g|gif|webp|svg\\+xml);/i;\n\n/** URL-bearing attributes checked by the editor's HTML and SVG sanitizer hook. */\nexport const HTML_URL_ATTRIBUTES = Object.freeze([\n \"href\",\n \"xlink:href\",\n \"background\",\n \"poster\",\n \"src\",\n] as const);\n\n/** Attributes removed regardless of value by the HTML and SVG sanitizer config. */\nexport const HTML_FORBIDDEN_ATTRIBUTES = Object.freeze([\n \"srcdoc\",\n \"ping\",\n \"formaction\",\n \"action\",\n] as const);\n\n/** URL rule for HTML attributes at the editor's browser insertion boundary. */\nexport function isSafeHtmlUrl(value: string, attribute: string): boolean {\n const normalized = normalizeUrlForSchemeCheck(value);\n const scheme = extractUrlScheme(normalized);\n if (scheme === null) return true;\n if (SAFE_LINK_SCHEMES.some((safe) => safe === scheme)) return true;\n return (\n attribute.toLowerCase() === \"src\" && DATA_IMAGE_SRC_PATTERN.test(normalized)\n );\n}\n\n/**\n * Apply the editor's URL hook and forbidden-attribute policy. Pass character\n * references decoded, as a browser reads them. Other attributes return true;\n * callers must check tags and on* handlers separately.\n */\nexport function isSafeUrlAttribute(name: string, value: string): boolean {\n const attribute = name.toLowerCase();\n if (HTML_FORBIDDEN_ATTRIBUTES.some((forbidden) => forbidden === attribute))\n return false;\n return (\n !HTML_URL_ATTRIBUTES.some((urlAttribute) => urlAttribute === attribute) ||\n isSafeHtmlUrl(value, attribute)\n );\n}\n","/**\n * A paragraph tag, open or close. `[^<>]*` rather than `[^>]*` keeps the\n * match linear: `[^>]*` runs across nested `<` and then backtracks one\n * character at a time when no `>` follows, which is O(n²) over inputs like\n * `<p<p<p…`. Real attributes never contain a raw `<`, so nothing valid is lost.\n */\nconst PARAGRAPH_TAG = /<\\/?p\\b[^<>]*>/gi;\n\n/** A paragraph with nothing in it, keeping its attributes in group 1. */\nconst EMPTY_PARAGRAPH = /<p\\b([^<>]*)>\\s*<\\/p>/gi;\n\n/**\n * Whether rich text holds nothing but paragraph tags and whitespace — what a\n * title or paragraph block stores once its text is cleared.\n */\nexport function isBlankRichText(html: string): boolean {\n return html.replace(PARAGRAPH_TAG, \"\").trim() === \"\";\n}\n\n/**\n * Gives every empty paragraph a non-breaking space, so a blank line the author\n * typed is one line tall wherever the text is shown.\n *\n * TipTap stores a blank line as `<p></p>`. ProseMirror draws it a line tall\n * while editing, because it adds a `<br>` for the caret, but anywhere else an\n * empty block has no height and its margins collapse into its neighbours'.\n * Unfilled, the line is missing from the canvas and from the sent email.\n *\n * Applied where rich text is displayed — the renderer and the editor canvas —\n * and never to stored content: a stored `<br>` parses back into a hard break,\n * which ProseMirror draws two lines tall, and a stored ` ` is a character\n * the caret can land on.\n *\n * Blank text comes back unchanged. The renderer emits nothing for a blank\n * paragraph block, so the canvas must not show a line for one either.\n */\nexport function fillEmptyParagraphs(html: string): string {\n if (isBlankRichText(html)) {\n return html;\n }\n return html.replace(EMPTY_PARAGRAPH, \"<p$1> </p>\");\n}\n","/**\n * Font-stack primitives shared by the renderer, the editor's canvas and font\n * selects, and every importer, so all of them read a CSS `font-family` value\n * the same way.\n *\n * A value is a comma-separated list of families, each either quoted\n * (`'Times New Roman'`, `\"Helvetica Neue\"`) or a run of identifiers\n * (`Helvetica Neue`, `sans-serif`). The split is a forward character scan, not\n * a regex: a quoted family may contain a comma (`\"Foo, Bar\"`), and an\n * unterminated quote must fail fast rather than backtrack.\n */\n\nimport type { CustomFont } from \"./config\";\n\nexport interface FontFamily {\n /** The family name, quotes removed and backslash escapes resolved. */\n name: string;\n /**\n * Whether the source quoted it. Quoting matters for generic keywords:\n * unquoted `serif` is the generic family, quoted `'serif'` names a font.\n */\n quoted: boolean;\n}\n\n/**\n * The built-in web-safe families, keyed by lowercased name, and the stack the\n * renderer emits for each.\n */\nexport const BUILT_IN_FONT_STACKS: Readonly<Record<string, string>> = {\n arial: \"Arial, sans-serif\",\n helvetica: \"Helvetica, sans-serif\",\n georgia: \"Georgia, serif\",\n \"times new roman\": \"'Times New Roman', serif\",\n verdana: \"Verdana, sans-serif\",\n \"trebuchet ms\": \"'Trebuchet MS', sans-serif\",\n \"courier new\": \"'Courier New', monospace\",\n tahoma: \"Tahoma, sans-serif\",\n};\n\nconst CSS_WIDE_KEYWORDS = new Set([\n \"inherit\",\n \"initial\",\n \"unset\",\n \"revert\",\n \"revert-layer\",\n]);\n\nconst GENERIC_FAMILIES = new Set([\n \"serif\",\n \"sans-serif\",\n \"monospace\",\n \"cursive\",\n \"fantasy\",\n \"system-ui\",\n \"ui-serif\",\n \"ui-sans-serif\",\n \"ui-monospace\",\n \"ui-rounded\",\n \"emoji\",\n \"math\",\n \"fangsong\",\n]);\n\nfunction isSpace(char: string): boolean {\n return (\n char === \" \" ||\n char === \"\\t\" ||\n char === \"\\n\" ||\n char === \"\\r\" ||\n char === \"\\f\"\n );\n}\n\n/**\n * The families in a `font-family` value, or `[]` when it sets no font. That\n * covers blank, a CSS-wide keyword, and any list a browser would reject (an\n * empty entry, a CSS-wide keyword among other families, an unterminated\n * quote), because a browser drops an invalid declaration and renders no font\n * from it. A trailing `!important` is ignored.\n */\nexport function parseFontFamilies(value: unknown): FontFamily[] {\n if (typeof value !== \"string\") return [];\n const text = value.replace(/!\\s*important\\s*$/i, \"\");\n const families: FontFamily[] = [];\n let i = 0;\n for (;;) {\n while (i < text.length && isSpace(text[i])) i++;\n if (i >= text.length) return [];\n const open = text[i];\n if (open === '\"' || open === \"'\") {\n let name = \"\";\n let j = i + 1;\n let closed = false;\n while (j < text.length) {\n const char = text[j];\n if (char === \"\\\\\" && j + 1 < text.length) {\n name += text[j + 1];\n j += 2;\n continue;\n }\n if (char === open) {\n closed = true;\n j++;\n break;\n }\n name += char;\n j++;\n }\n if (!closed) return [];\n while (j < text.length && isSpace(text[j])) j++;\n if (j < text.length && text[j] !== \",\") return [];\n families.push({ name, quoted: true });\n i = j;\n } else {\n const comma = text.indexOf(\",\", i);\n const end = comma === -1 ? text.length : comma;\n const name = text.slice(i, end).trim().split(/\\s+/).join(\" \");\n if (name === \"\") return [];\n if (name.includes('\"') || name.includes(\"'\")) return [];\n if (CSS_WIDE_KEYWORDS.has(name.toLowerCase())) return [];\n families.push({ name, quoted: false });\n i = end;\n }\n if (i >= text.length) return families;\n // Past the comma. A trailing comma leaves nothing, which returns [].\n i++;\n }\n}\n\n/** `name` as a single-quoted CSS string. */\nexport function quoteFontFamily(name: string): string {\n return `'${name.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/** Families back into a `font-family` value, quoted ones in single quotes. */\nexport function formatFontFamilies(families: readonly FontFamily[]): string {\n return families\n .map((family) =>\n family.quoted ? quoteFontFamily(family.name) : family.name,\n )\n .join(\", \");\n}\n\n/** An unquoted generic family keyword such as `sans-serif` or `system-ui`. */\nexport function isGenericFontFamily(family: FontFamily): boolean {\n return !family.quoted && GENERIC_FAMILIES.has(family.name.toLowerCase());\n}\n\n/**\n * `value` re-serialised: single-quoted names, `\", \"` separators, no\n * `!important`. `\"\"` when it sets no font. Never contains `\"`, so it can sit\n * inside a double-quoted `style` attribute.\n */\nexport function normalizeFontStack(value: unknown): string {\n return formatFontFamilies(parseFontFamilies(value));\n}\n\n/** The first family's name, unquoted; `\"\"` when `value` sets no font. */\nexport function firstFontFamily(value: unknown): string {\n return parseFontFamilies(value)[0]?.name ?? \"\";\n}\n\nfunction sameFamilies(\n a: readonly FontFamily[],\n b: readonly FontFamily[],\n): boolean {\n return (\n a.length === b.length &&\n a.every(\n (family, index) =>\n family.name.toLowerCase() === b[index].name.toLowerCase() &&\n isGenericFontFamily(family) === isGenericFontFamily(b[index]),\n )\n );\n}\n\n/**\n * How an importer stores a font: `value` normalised, except that a built-in\n * stated alone, or as exactly the stack the renderer emits for it\n * (`Arial, sans-serif`), becomes the built-in's bare name. That collapse is\n * lossless under any render config, because the renderer re-expands a\n * built-in from its fixed table. Every other stack is kept, so its fallbacks\n * survive. `\"\"` when `value` sets no font.\n */\nexport function canonicalFontStack(value: unknown): string {\n const families = parseFontFamilies(value);\n if (families.length === 0) return \"\";\n const builtInStack = BUILT_IN_FONT_STACKS[families[0].name.toLowerCase()];\n if (builtInStack) {\n const builtIn = parseFontFamilies(builtInStack);\n if (families.length === 1 || sameFamilies(families, builtIn)) {\n return builtIn[0].name;\n }\n }\n return formatFontFamilies(families);\n}\n\n/**\n * The `font-family` an email sets for a stored value, given the fonts the\n * template renders with. The renderer emits it, and the editor canvas applies\n * it, so a font previews with the same fallbacks the recipient gets.\n *\n * Only a lone family is resolved: a built-in expands to its stack, a custom\n * font is followed by its own fallback (or `defaultFallback`), and any other\n * named family by `defaultFallback`. A stack, a generic family, a CSS-wide\n * keyword or an invalid value is returned as written.\n *\n * A custom font also matches by its bare name, which is how the font picker\n * stores it, even when that name isn't valid CSS unquoted (`Ma'am Sans`).\n */\nexport function resolveFontStack(\n value: string,\n fonts: { customFonts: readonly CustomFont[]; defaultFallback: string },\n): string {\n const withFallback = (font: CustomFont): string =>\n `${quoteFontFamily(font.name)}, ${font.fallback ?? fonts.defaultFallback}`;\n\n // `value` is typed, but untyped template JSON can omit it; like\n // `parseFontFamilies`, a non-string then passes through as written.\n const bareName = typeof value === \"string\" ? value.trim().toLowerCase() : \"\";\n const namedFont = fonts.customFonts.find(\n (font) => font.name.toLowerCase() === bareName,\n );\n if (namedFont) {\n return withFallback(namedFont);\n }\n\n const families = parseFontFamilies(value);\n if (families.length !== 1) {\n return value;\n }\n const [family] = families;\n const key = family.name.toLowerCase();\n\n const customFont = fonts.customFonts.find(\n (font) => font.name.toLowerCase() === key,\n );\n if (customFont) {\n return withFallback(customFont);\n }\n\n const builtIn = BUILT_IN_FONT_STACKS[key];\n if (builtIn) {\n return builtIn;\n }\n\n if (isGenericFontFamily(family)) {\n return value;\n }\n\n return `${quoteFontFamily(family.name)}, ${fonts.defaultFallback}`;\n}\n","import type { TemplateContent } from \"./template\";\n\n/**\n * Context handed to `resolvePreview`.\n *\n * `recipient` is present only on surfaces that have one — the test-email\n * dialog — and absent in the editor's own preview mode. Treat its absence as\n * \"no particular recipient\", not as an error: a resolver should still return\n * something renderable, typically its own default or sample data.\n */\nexport interface PreviewResolveContext {\n /**\n * The template as it currently stands. Already a copy — mutating it has no\n * effect on the editor, and returning it unchanged is a valid no-op.\n */\n content: TemplateContent;\n /** The address the preview is being shown for, when the surface has one. */\n recipient?: string;\n}\n\n/**\n * Resolves a template for display on preview surfaces — typically substituting\n * merge tags and **evaluating logic tags** against real data.\n *\n * Logic tags are the reason this hook exists. `MergeTag.sample` already covers\n * value tags client-side, but branching (`{% if %}` … `{% endif %}`) cannot be\n * evaluated in a browser for every supported syntax — mailchimp and ampscript\n * logic are server-side dialects — so only the consumer's own backend can do it.\n *\n * Display-only. The returned content reaches preview surfaces and nothing else:\n * it is never written to the editor's state, never returned from\n * `getContent()`, never sent, and never exported. Rejecting is safe — the\n * preview falls back to the unresolved template and says so.\n */\nexport type ResolvePreview = (\n context: PreviewResolveContext,\n) => Promise<TemplateContent>;\n\n/**\n * Whether `value` is shaped enough like `TemplateContent` to render.\n *\n * A resolver is consumer code returning data that often came from an HTTP\n * response, so the declared return type guarantees nothing at runtime. A\n * mis-shaped result is treated as a resolution failure — the preview degrades\n * to the unresolved template — rather than throwing inside the render.\n */\nexport function isRenderableTemplateContent(\n value: unknown,\n): value is TemplateContent {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { blocks?: unknown };\n return Array.isArray(candidate.blocks);\n}\n"],"mappings":";AAoBA,IAAaQ,IAAsC;CACjD;CACA;CACA;CACA;AACF;AAsBA,SAAgBC,EAAc,GAAoC;CAChE,OAAO;EACL,KAAK,EAAE,GAAGC,EAAK;EACf,OAAO,EAAE,GAAGA,EAAK;EACjB,QAAQ,EAAE,GAAGA,EAAK;EAClB,MAAM,EAAE,GAAGA,EAAK;CAClB;AACF;AAOA,SAAgBC,EAAY,GAAkD;CAU5E,OARE,CAACD,KACD,OAAOA,EAAK,SAAU,YACtB,CAAC,OAAO,SAASA,EAAK,KAAK,KAC3BA,EAAK,SAAS,IAEP,OAGF,GAAGA,EAAK,MAAM,KAAKA,EAAK,MAAM,GAAGA,EAAK;AAC/C;AAWA,SAAgBE,EACd,GAC4D;CAC5D,IAAI,CAACC,GACH,OAAO,CAAC;CAGV,IAAMC,IAAMN,EAAa,KAAK,MAASG,E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