//#region src/blocks.d.ts
interface SpacingValue {
  top: number;
  right: number;
  bottom: number;
  left: number;
}
interface BlockStyles {
  padding: SpacingValue;
  backgroundColor?: string;
}
type BorderStyle = "solid" | "dashed" | "dotted";
type BorderSide = "top" | "right" | "bottom" | "left";
export declare const BORDER_SIDES: readonly BorderSide[];
/** One side of a border. A width of `0` leaves that side undrawn. */
interface BorderSideValue {
  /** Width in px. `0` means no border on this side. */
  width: number;
  style: BorderStyle;
  color: string;
}
/**
 * A border described per side, like `SpacingValue`. Only elements MJML can
 * border natively carry one: sections, images and buttons.
 */
interface BorderValue {
  top: BorderSideValue;
  right: BorderSideValue;
  bottom: BorderSideValue;
  left: BorderSideValue;
}
/** The same side value on all four sides. */
export declare function uniformBorder(side: BorderSideValue): BorderValue;
/**
 * Convert one side of a border to a CSS `border` value like
 * `"1px solid #cccccc"`. Returns `null` when the side is absent or its width is
 * not a positive number, so callers emit nothing rather than a `0px` border.
 */
export declare function toBorderCss(side: BorderSideValue | undefined): string | null;
/**
 * Resolve a border to the CSS declarations that draw it, keyed by kebab-case
 * property: one `border` when all four sides are drawn identically, otherwise
 * one `border-<side>` per drawn side. Empty when there is nothing to draw.
 *
 * The keys double as MJML attribute names (`mj-section`, `mj-image` and
 * `mj-button` accept `border` and every `border-<side>`), so the renderer and
 * the editor canvas both go through this and can't disagree about a border.
 */
export declare function toBorderDeclarations(border: BorderValue | undefined): Partial<Record<"border" | `border-${BorderSide}`, string>>;
type BorderCorner = "topLeft" | "topRight" | "bottomRight" | "bottomLeft";
/** In CSS shorthand order: top-left, top-right, bottom-right, bottom-left. */
export declare const BORDER_CORNERS: readonly BorderCorner[];
/** A radius per corner, in px. */
type CornerRadius = Record<BorderCorner, number>;
/**
 * A corner radius in px: one number for all four corners, or a radius per
 * corner.
 */
type BorderRadiusValue = number | CornerRadius;
/**
 * Convert a corner radius to a CSS `border-radius` value: `"8px"` when all
 * corners match, otherwise the four-value shorthand `"8px 8px 0px 0px"`
 * (top-left, top-right, bottom-right, bottom-left). Returns `null` when every
 * corner is square, so callers emit nothing.
 *
 * A non-finite or negative corner counts as square — hand-authored JSON is the
 * only way to produce one, and the export must not carry it.
 */
export declare function toBorderRadiusCss(radius: BorderRadiusValue | undefined): string | null;
interface BlockVisibility {
  desktop: boolean;
  mobile: boolean;
}
interface BaseBlock {
  id: string;
  type: string;
  styles: BlockStyles;
  visibility?: BlockVisibility;
  displayCondition?: {
    label: string;
    before: string;
    after: string;
    group?: string;
    description?: string;
  };
}
type ColumnLayout = "1" | "2" | "3" | "2-1" | "1-2";
/**
 * Optional outer frame for a section. When present, the section is rendered
 * inside an `mj-wrapper` — a band (its own background + padding) that frames
 * the section, e.g. a white card sitting on a colored band. The band is as
 * wide as the email body (`settings.width`), not the recipient's viewport.
 */
interface SectionWrapper {
  backgroundColor?: string;
  padding?: SpacingValue;
  /**
   * Corner radius in px for the outer frame — one number, or a radius per
   * corner. Omitted/0 = square corners.
   */
  borderRadius?: BorderRadiusValue;
}
interface SectionBlock extends BaseBlock {
  type: "section";
  columns: ColumnLayout;
  children: Block[][];
  /**
   * Whether columns stack vertically on mobile. Absent or `true` keeps MJML's
   * default responsive behavior (columns stack below 480px). `false` renders
   * the columns inside an `<mj-group>` so they stay side-by-side on mobile,
   * proportionally shrunk to fit.
   */
  stackOnMobile?: boolean;
  /**
   * Corner radius in px — one number, or a radius per corner. Omitted/0 =
   * square corners.
   */
  borderRadius?: BorderRadiusValue;
  /**
   * Border around the section box, per side. Omitted = no border; a side with
   * width 0 is not drawn.
   */
  border?: BorderValue;
  /** Optional outer frame (rendered as an `mj-wrapper` around the section). */
  wrapper?: SectionWrapper;
}
type HeadingLevel = 1 | 2 | 3 | 4;
export declare const HEADING_LEVEL_FONT_SIZE: Record<HeadingLevel, number>;
/**
 * Spacing (px) for the HTML a rich-text block stores — the `<p>`, `<ul>`,
 * `<ol>` and `<li>` elements TipTap produces.
 *
 * The editor canvas and the exported email must agree on these to the pixel,
 * so this is the one place they are stated. `@templatical/renderer` reads them
 * to build the global rule it emits; the editor's canvas CSS restates them as
 * literals (CSS cannot import a constant) and a parity test holds the two
 * together.
 *
 * Fixed px, never a `rem`- or base-size-derived scale: an email body is a
 * fixed-width document, so content spacing must not move when a consumer
 * scales the editor chrome.
 */
export declare const RICH_TEXT_SPACING: {
  /** Gap below every `<p>` except the last — the space between paragraphs. */
  readonly paragraphGap: 8;
  /** Vertical margin on `<ul>` / `<ol>`. */
  readonly listMarginY: 8;
  /** Left padding on `<ul>` / `<ol>` — the bullet indent. */
  readonly listPaddingLeft: 24;
  /** Vertical margin on `<li>`. */
  readonly listItemMarginY: 4;
};
interface TitleBlock extends BaseBlock {
  type: "title";
  content: string;
  level: HeadingLevel;
  /** Text color. Unset = inherit the document-level `textColor`. */
  color?: string;
  textAlign: "left" | "center" | "right";
  fontFamily?: string;
}
interface ParagraphBlock extends BaseBlock {
  type: "paragraph";
  content: string;
  /**
   * Gap in px between this block's paragraphs — the space below every `<p>`
   * except the last. Absent means `RICH_TEXT_SPACING.paragraphGap`.
   *
   * Only affects a block holding more than one paragraph; a single `<p>` has no
   * internal gap, and the space around the block is `styles.padding`.
   *
   * `0` is a valid choice (paragraphs butted together) and is distinct from the
   * field being absent, so readers must test for `undefined` rather than
   * falsiness.
   */
  paragraphSpacing?: number;
}
interface ImageBlock extends BaseBlock {
  type: "image";
  src: string;
  alt: string;
  width: number | "full";
  /**
   * Height in pixels. Absent means the height is derived from the width, so the
   * image keeps its aspect ratio — setting both stretches it, since email
   * clients don't support `object-fit`.
   */
  height?: number;
  align: "left" | "center" | "right";
  /**
   * Corner radius in px. Omitted/0 = square corners. A radius of at least half
   * the rendered size rounds a square image to a circle, which is how avatar
   * and portrait layouts are built. A radius per corner is also accepted.
   */
  borderRadius?: BorderRadiusValue;
  /**
   * Border around the image itself, per side. Omitted = no border; a side with
   * width 0 is not drawn.
   */
  border?: BorderValue;
  linkUrl?: string;
  linkOpenInNewTab?: boolean;
  placeholderUrl?: string;
  decorative?: boolean;
}
interface ButtonBlock extends BaseBlock {
  type: "button";
  text: string;
  url: string;
  openInNewTab?: boolean;
  backgroundColor: string;
  textColor: string;
  /** Corner radius in px — one number, or a radius per corner. */
  borderRadius: BorderRadiusValue;
  /**
   * Border around the button itself, per side. Omitted = no border; a side
   * with width 0 is not drawn. For an outline ("ghost") button, set
   * `backgroundColor` to the keyword `"transparent"` (the background control
   * stores it) and set `textColor` too — a new button is `#333333` with white
   * text. An empty fill exports as `transparent`, because MJML paints
   * `#414141` when the attribute is omitted.
   */
  border?: BorderValue;
  fontSize: number;
  buttonPadding: SpacingValue;
  fontFamily?: string;
  width?: number | "full";
  /**
   * Placement of the button within its column. No visible effect when `width`
   * is `"full"`, since the button then spans the column.
   */
  align: "left" | "center" | "right";
}
/**
 * A share of the column, from `"0%"` to `"100%"`.
 * @pattern ^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)%$
 */
type DividerPercentWidth = `${number}%`;
interface DividerBlock extends BaseBlock {
  type: "divider";
  lineStyle: "solid" | "dashed" | "dotted";
  color: string;
  thickness: number;
  /**
   * `"full"` spans the column and a number is pixels. A percentage is a share
   * of the column: MJML renders it natively, and it shrinks with the column on
   * a phone where a pixel width would overflow.
   */
  width: number | "full" | DividerPercentWidth;
}
interface VideoBlock extends BaseBlock {
  type: "video";
  url: string;
  openInNewTab?: boolean;
  thumbnailUrl: string;
  alt: string;
  width: number | "full";
  /**
   * Height in pixels for the thumbnail. Absent means the height is derived from
   * the width, so the thumbnail keeps its aspect ratio — setting both stretches
   * it, since email clients don't support `object-fit`.
   */
  height?: number;
  align: "left" | "center" | "right";
  placeholderUrl?: string;
}
type SocialPlatform = "facebook" | "twitter" | "instagram" | "linkedin" | "youtube" | "tiktok" | "pinterest" | "email" | "whatsapp" | "telegram" | "discord" | "snapchat" | "reddit" | "github" | "dribbble" | "behance" | "website";
/**
 * The icon's shape. `plain` is the glyph alone, with no badge or outline.
 */
type SocialIconStyle = "solid" | "outlined" | "rounded" | "square" | "circle" | "plain";
/**
 * The colors an icon is drawn in: each platform's own brand color, or one
 * tone (dark or light) for every icon.
 */
type SocialIconTone = "brand" | "dark" | "light";
type SocialIconSize = "small" | "medium" | "large";
interface SocialIcon {
  id: string;
  platform: SocialPlatform;
  url: string;
}
interface SocialIconsBlock extends BaseBlock {
  type: "social";
  icons: SocialIcon[];
  iconStyle: SocialIconStyle;
  /** Absent means `"brand"`. */
  iconTone?: SocialIconTone;
  iconSize: SocialIconSize;
  spacing: number;
  align: "left" | "center" | "right";
}
interface SpacerBlock extends BaseBlock {
  type: "spacer";
  height: number;
}
interface HtmlBlock extends BaseBlock {
  type: "html";
  content: string;
}
interface MenuItemData {
  id: string;
  text: string;
  url: string;
  openInNewTab: boolean;
  bold: boolean;
  underline: boolean;
  color?: string;
}
interface MenuBlock extends BaseBlock {
  type: "menu";
  items: MenuItemData[];
  fontSize: number;
  fontFamily?: string;
  /** Base text/link color. Unset = inherit the document-level `textColor`. */
  color?: string;
  linkColor?: string;
  textAlign: "left" | "center" | "right";
  separator: string;
  separatorColor: string;
  spacing: number;
}
interface TableCellData {
  id: string;
  content: string;
}
interface TableRowData {
  id: string;
  cells: TableCellData[];
}
interface TableBlock extends BaseBlock {
  type: "table";
  rows: TableRowData[];
  hasHeaderRow: boolean;
  headerBackgroundColor?: string;
  borderColor: string;
  borderWidth: number;
  cellPadding: number;
  fontSize: number;
  fontFamily?: string;
  /** Text color. Unset = inherit the document-level `textColor`. */
  color?: string;
  textAlign: "left" | "center" | "right";
}
interface CountdownBlock extends BaseBlock {
  type: "countdown";
  targetDate: string;
  timezone: string;
  showDays: boolean;
  showHours: boolean;
  showMinutes: boolean;
  showSeconds: boolean;
  separator: ":" | "-" | " ";
  digitFontSize: number;
  digitColor: string;
  labelColor: string;
  labelFontSize: number;
  backgroundColor: string;
  fontFamily?: string;
  labelDays: string;
  labelHours: string;
  labelMinutes: string;
  labelSeconds: string;
  expiredMessage: string;
  expiredImageUrl: string;
  hideOnExpiry: boolean;
}
interface CustomBlock extends BaseBlock {
  type: "custom";
  customType: string;
  fieldValues: Record<string, unknown>;
  renderedHtml?: string;
  dataSourceFetched?: boolean;
}
/**
 * Layout-only hole where authored content is spliced in. Extends BaseBlock so
 * Block walkers stay typed (`styles` unused; spliced out before render).
 */
interface SlotBlock extends BaseBlock {
  type: "slot";
}
/**
 * Layout-only band rendered as `mj-wrapper`. The block is the band:
 * `styles.backgroundColor` / `styles.padding` / `borderRadius` map to the
 * wrapper. Legal in layout only this ship.
 */
interface WrapperBlock extends BaseBlock {
  type: "wrapper";
  children: Block[];
  borderRadius?: number;
}
type Block = SectionBlock | TitleBlock | ParagraphBlock | ImageBlock | ButtonBlock | DividerBlock | VideoBlock | SocialIconsBlock | SpacerBlock | HtmlBlock | MenuBlock | TableBlock | CountdownBlock | CustomBlock | SlotBlock | WrapperBlock;
type BlockType = Block["type"];
//#endregion
//#region src/social.d.ts
/**
 * SVG glyph (24×24 path) + brand color for each social platform.
 *
 * Single source of truth shared by two consumers that render icons in
 * different formats: the editor draws them as inline SVG (`SocialIconSvg.vue`)
 * and `@templatical/renderer` rasterizes them to PNGs
 * (`scripts/rasterize-social.mjs`) because Outlook's Word engine has no SVG
 * support. Typing as `Record<SocialPlatform, ...>` makes adding a platform to
 * the union a compile error until its glyph is supplied here, keeping both
 * consumers in lockstep.
 */
interface SocialIconGlyph {
  /** SVG path data on a 24×24 viewBox. */
  path: string;
  /** Brand color as a 6-digit hex string. */
  color: string;
}
export declare const SOCIAL_ICON_GLYPHS: Record<SocialPlatform, SocialIconGlyph>;
export declare const SOCIAL_ICON_STYLES: readonly SocialIconStyle[];
export declare const SOCIAL_ICON_TONES: readonly SocialIconTone[];
/** The color of each one-color tone, as a 6-digit hex string. */
export declare const SOCIAL_ICON_TONE_COLORS: Record<Exclude<SocialIconTone, "brand">, string>;
/**
 * The two colors an icon is drawn with, shared by the editor's inline SVG
 * and the renderer's PNGs. `fill` is the icon's color: the badge of a filled
 * style, the outline and glyph of `outlined`, the glyph of `plain`. `onFill`
 * is the glyph on a badge: white, or near-black on a light one. An unknown
 * tone falls back to the brand color.
 */
export declare function socialIconColors(platform: SocialPlatform, tone: SocialIconTone | undefined): {
  fill: string;
  onFill: string;
};
/**
 * The folder an icon's PNG sits in under `socialIconsBaseUrl`: the style for
 * brand colors, which keeps every existing URL as it was, and
 * `{style}-{tone}` for a one-color tone.
 */
export declare function socialIconAssetDir(style: SocialIconStyle, tone: SocialIconTone | undefined): string;
/**
 * The halo a dark `plain` or `outlined` icon is drawn with, shared by the
 * editor's inline SVG and the renderer's PNGs. Neither has a badge behind it,
 * and nearly every dark-mode client darkens a light background without
 * touching images, which would hide the icon. The faint white halo is barely
 * visible on light backgrounds and traces the icon once the background turns
 * dark. A light icon has none: a dark halo would outline it on every colored
 * band it's meant for. `width` is in the icon's 24-unit grid, centered on the
 * edge it traces.
 */
export declare function socialIconHalo(style: SocialIconStyle, tone: SocialIconTone | undefined): {
  color: string;
  opacity: number;
  width: number;
} | undefined;
/**
 * The glyph's share of the icon's width: larger when it stands alone
 * (`plain`) than inside a badge or outline.
 */
export declare function socialIconGlyphScale(style: SocialIconStyle): number;
//#endregion
//#region src/saved-blocks.d.ts
/**
 * A reusable, user-authored group of blocks — saved from the canvas and
 * re-insertable into any template.
 *
 * Distinct from a *custom block* (`CustomBlockDefinition`), which is a
 * developer-defined block **type** with its own template and field schema.
 * A saved block is an instance-level snapshot of ordinary blocks.
 */
interface SavedBlock {
  /**
   * Store-assigned identifier. Returned by {@link SavedBlocksProvider.create}
   * — the editor never generates it, so the store stays the authority on
   * identity (database primary key, storage slug, etc.).
   */
  id: string;
  name: string;
  /**
   * Top-level blocks captured in this saved block. A `section` carries its own
   * `children`, so a whole section-with-columns round-trips as one entry.
   *
   * Blocks are re-identified on insert (via `cloneBlock`), so the IDs stored
   * here never collide with the blocks already on a canvas.
   */
  content: Block[];
  /**
   * Optional free-text grouping, surfaced in the browser as a filter.
   *
   * Flat and free-text by design — there is no category registry and no
   * nesting. The editor derives the set of available categories from the
   * entries it has loaded, so a category exists exactly as long as something
   * carries it; an entry without one is simply uncategorised.
   */
  category?: string;
  /**
   * Per-entry permission carve-outs. **Absent means allowed** — the provider's
   * `update` / `delete` already say whether the capability exists at all, so
   * these exist only to forbid it on *particular* entries (a shared block a
   * viewer may insert but not edit, someone else's block, a locked entry).
   *
   * Return them from your API alongside the row, where the answer is already
   * known — the editor never second-guesses them and never computes its own.
   * When one is `false` the corresponding control is not rendered for that
   * entry.
   */
  canUpdate?: boolean;
  canDelete?: boolean;
  /**
   * Store-assigned timestamps, used for display only: the browser shows a
   * relative "5m ago" label per entry (preferring `updatedAt`, falling back to
   * `createdAt`) with the absolute date on hover.
   *
   * They do **not** affect ordering — the editor renders whatever order
   * `list()` returns and never re-sorts. Both are optional; omit them and the
   * label is simply not shown.
   */
  createdAt?: string;
  updatedAt?: string;
}
/**
 * Parameters for {@link SavedBlocksProvider.list}. An object (rather than
 * positional arguments) so future filters can be added without breaking
 * existing provider implementations.
 *
 * **These are only sent by headless callers.** The editor's own browser calls
 * `list()` with no parameters and filters the loaded entries in memory — that
 * way a provider stays a dumb store and still gets a working search box and
 * category filter. They arrive only when you drive `useSavedBlocks`
 * yourself (see the guide's "Headless use"), so implement them if you want
 * server-side filtering for your own UI and ignore them otherwise.
 */
interface SavedBlocksListParams {
  /** Free-text filter over the saved block's `name`. */
  search?: string;
  /** Exact-match filter over {@link SavedBlock.category}. */
  category?: string;
}
/** Payload for {@link SavedBlocksProvider.create}. */
interface SavedBlockInput {
  name: string;
  content: Block[];
  category?: string;
}
/**
 * Partial patch for {@link SavedBlocksProvider.update}. Only the keys present
 * are being changed — `category: ""` clears the category, whereas omitting the
 * key leaves it alone.
 */
type SavedBlockPatch = Partial<{
  name: string;
  content: Block[];
  category: string;
}>;
/**
 * Outward notifications for saved-block mutations. Every member is optional.
 *
 * Separate from the storage methods so `initCloud()` can accept this half
 * alone: these fire the same way whichever store holds the entries, Cloud's
 * own or yours. {@link SavedBlocksProvider} extends this, so one object
 * satisfies both entry points.
 */
interface SavedBlocksOptions {
  /** A saved block was created and prepended to the list. */
  onCreated?: (block: SavedBlock) => void;
  /** A saved block was updated and its list entry replaced. */
  onUpdated?: (block: SavedBlock) => void;
  /**
   * A saved block was deleted and filtered out of the list. `delete` resolves
   * to nothing, so this carries the entry the editor captured before removing
   * it — not an id.
   *
   * Fires only when the entry was present in the locally loaded list at the
   * time of the delete, since that capture is where the entry comes from.
   * Deleting an id that was never loaded — e.g. a headless caller acting on
   * an id from elsewhere — still deletes successfully; there is just nothing
   * to pass, so this does not fire.
   */
  onDeleted?: (block: SavedBlock) => void;
}
/**
 * Storage contract for saved blocks. Implement it to back the editor's saved
 * blocks UI with your own persistence — the editor owns the save dialog, the
 * browser, and insertion; you own the transport.
 *
 * Pass an implementation as `savedBlocks` to `init()`. When omitted, the
 * feature stays off entirely and none of its UI renders.
 *
 * Every method may reject; the editor surfaces the failure through the
 * editor's `onError` callback and leaves its in-memory list untouched.
 *
 * **Each mutation can be turned off by passing `false` instead of a function.**
 * The editor then hides the affordance rather than letting the user try and
 * fail. They are required rather than optional precisely so that disabling is a
 * decision you state, never something you get by forgetting a method. Setting
 * all three yields a **read-only library**: users still browse, preview and
 * insert, because insertion only touches the canvas and never your store.
 *
 * ```ts
 * const provider: SavedBlocksProvider = {
 *   list: ({ search } = {}) =>
 *     fetch(`/api/saved-blocks?search=${search ?? ""}`).then((r) => r.json()),
 *   create: (input) =>
 *     fetch("/api/saved-blocks", {
 *       method: "POST",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify(input),
 *     }).then((r) => r.json()),
 *   update: (id, patch) =>
 *     fetch(`/api/saved-blocks/${id}`, {
 *       method: "PUT",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify(patch),
 *     }).then((r) => r.json()),
 *   delete: (id) =>
 *     fetch(`/api/saved-blocks/${id}`, { method: "DELETE" }).then(() => undefined),
 * };
 * ```
 */
interface SavedBlocksProvider extends SavedBlocksOptions {
  /**
   * Fetch saved blocks. The editor calls this with no arguments and expects
   * everything the current user may see — scoping the result per user, tenant
   * or permission is yours to do here. {@link SavedBlocksListParams} is only
   * populated by headless callers; honouring it is optional.
   *
   * The one method that cannot be disabled: without it the feature has nothing
   * to show.
   */
  list(params?: SavedBlocksListParams): Promise<SavedBlock[]>;
  /**
   * Persist a new saved block and return it with its store-assigned `id`, or
   * `false` to disable saving entirely — the block chrome's bookmark action
   * disappears and no pick session can be started.
   */
  create: false | ((input: SavedBlockInput) => Promise<SavedBlock>);
  /**
   * Apply a partial update and return the stored result, or `false` to disable
   * editing entirely. Renaming is `update(id, { name })` and recategorising is
   * `update(id, { category })` — there are no separate methods for either.
   *
   * To allow editing in general but forbid it on particular entries, keep the
   * function and set {@link SavedBlock.canUpdate} to `false` on those.
   */
  update: false | ((id: string, patch: SavedBlockPatch) => Promise<SavedBlock>);
  /**
   * Remove a saved block, resolving once the store has applied the delete, or
   * `false` to disable deletion entirely. Per-entry exceptions go through
   * {@link SavedBlock.canDelete}.
   */
  delete: false | ((id: string) => Promise<void>);
}
//#endregion
//#region src/defaults.d.ts
type BlockDefaultsFor<T> = Partial<Omit<T, "id" | "type">>;
interface BlockDefaults {
  title?: BlockDefaultsFor<TitleBlock>;
  paragraph?: BlockDefaultsFor<ParagraphBlock>;
  image?: BlockDefaultsFor<ImageBlock>;
  button?: BlockDefaultsFor<ButtonBlock>;
  divider?: BlockDefaultsFor<DividerBlock>;
  section?: BlockDefaultsFor<SectionBlock>;
  video?: BlockDefaultsFor<VideoBlock>;
  social?: BlockDefaultsFor<SocialIconsBlock>;
  spacer?: BlockDefaultsFor<SpacerBlock>;
  html?: BlockDefaultsFor<HtmlBlock>;
  menu?: BlockDefaultsFor<MenuBlock>;
  table?: BlockDefaultsFor<TableBlock>;
  countdown?: BlockDefaultsFor<CountdownBlock>;
}
type TemplateDefaults = Partial<TemplateSettings>;
export declare const TITLE_BLOCK_DEFAULTS: BlockDefaultsFor<TitleBlock>;
export declare const PARAGRAPH_BLOCK_DEFAULTS: BlockDefaultsFor<ParagraphBlock>;
export declare const IMAGE_BLOCK_DEFAULTS: BlockDefaultsFor<ImageBlock>;
export declare const BUTTON_BLOCK_DEFAULTS: BlockDefaultsFor<ButtonBlock>;
export declare const DIVIDER_BLOCK_DEFAULTS: BlockDefaultsFor<DividerBlock>;
export declare const SECTION_BLOCK_DEFAULTS: BlockDefaultsFor<SectionBlock>;
export declare const VIDEO_BLOCK_DEFAULTS: BlockDefaultsFor<VideoBlock>;
export declare const SOCIAL_ICONS_BLOCK_DEFAULTS: BlockDefaultsFor<SocialIconsBlock>;
export declare const SPACER_BLOCK_DEFAULTS: BlockDefaultsFor<SpacerBlock>;
export declare const HTML_BLOCK_DEFAULTS: BlockDefaultsFor<HtmlBlock>;
export declare const MENU_BLOCK_DEFAULTS: BlockDefaultsFor<MenuBlock>;
export declare const TABLE_BLOCK_DEFAULTS: BlockDefaultsFor<TableBlock>;
export declare const COUNTDOWN_BLOCK_DEFAULTS: BlockDefaultsFor<CountdownBlock>;
export declare const DEFAULT_BLOCK_DEFAULTS: Required<BlockDefaults>;
export declare const DEFAULT_TEMPLATE_DEFAULTS: TemplateDefaults;
export declare function deepMergeDefaults<T extends object>(base: T, overrides: Partial<T>): T;
//#endregion
//#region src/direction.d.ts
/**
 * Writing direction of the delivered email — the canvas `dir` and the
 * rendered `<mjml dir>`. Independent of the editor chrome language
 * (`init({ locale })`).
 */
type ContentDirection = "ltr" | "rtl";
/**
 * Primary BCP-47 subtags whose default writing direction is right-to-left.
 * Region tags (`ar-SA`) resolve through the primary subtag. `"iw"` is the
 * legacy Hebrew tag. Not a CLDR dump — extend the list when a script is
 * needed; do not infer from `lang` at the call site.
 */
export declare const RTL_LANGUAGE_PRIMARY_SUBTAGS: readonly string[];
/**
 * Whether a BCP-47 (or underscore-separated) language tag is an RTL language
 * by primary subtag. Missing, empty, and unknown tags are not RTL.
 */
export declare function isRtlLanguageTag(tag: string | undefined): boolean;
/**
 * The email's writing direction. An explicit `settings.direction` of `"ltr"`
 * or `"rtl"` wins; anything else (unset, or a garbage JS value) falls through
 * to the content language, then to `"ltr"`.
 *
 * This is the single reader — renderer, canvas, and settings UI all go
 * through it, so a later per-block override can wrap it without forking the
 * locale table.
 */
export declare function resolveContentDirection(settings: {
  locale: string;
  direction?: ContentDirection;
}): ContentDirection;
//#endregion
//#region src/template.d.ts
interface TemplateSettings {
  width: number;
  backgroundColor: string;
  /**
   * Document-level default text color: the `<mj-text>` default in the rendered
   * MJML, inherited by every text block (Title, Paragraph, Menu, Table) that
   * doesn't set its own `color`. Required, defaulting to `#1a1a1a` (see
   * `DEFAULT_TEMPLATE_DEFAULTS`); customize the default per-consumer via
   * `templateDefaults`. A block's explicit `color` or an inline text-color
   * mark overrides it.
   */
  textColor: string;
  /**
   * Document-level link color: emitted as the global `a { color }` rule in the
   * rendered MJML, so it cascades to every link — rich-text and menu alike.
   * Optional: when unset, links inherit the surrounding text color
   * (`color: inherit`), preserving the pre-#352 default. A per-block or
   * per-item color (a Menu item's `color`, `MenuBlock.linkColor`) still
   * overrides it.
   */
  linkColor?: string;
  /**
   * Whether links are underlined document-wide: drives the global
   * `a { text-decoration }` rule (`underline` when true, `none` when false).
   * Required, defaulting to `true` (see `DEFAULT_TEMPLATE_DEFAULTS`) — the
   * common, more accessible email default. Applies to body (rich-text) links;
   * buttons and menu items carry their own inline `text-decoration` and are
   * unaffected. Set `false` to render links without an underline.
   */
  linkUnderline: boolean;
  fontFamily: string;
  preheaderText?: string;
  /**
   * BCP-47 language code for the rendered email's `<html lang>`. Drives
   * screen-reader pronunciation. Default `'en'` via `DEFAULT_TEMPLATE_DEFAULTS`.
   */
  locale: string;
  /**
   * Writing direction of the delivered email: the canvas `dir` and the
   * rendered `<mjml dir>`. Independent of the editor chrome
   * (`init({ locale })`). Optional: when unset, `resolveContentDirection`
   * falls through to the content language (`ar` / `he` / `fa` / … → `"rtl"`,
   * otherwise `"ltr"`). An explicit `"ltr"` on an Arabic template is a
   * stated decision, not a missing value.
   */
  direction?: ContentDirection;
}
interface TemplateContent {
  blocks: Block[];
  settings: TemplateSettings;
}
export declare function createDefaultTemplateContent(defaultFontFamily?: string, templateDefaults?: TemplateDefaults): TemplateContent;
//#endregion
//#region src/test-email.d.ts
/**
 * What a {@link TestEmailProvider} receives when the user asks to send a test.
 */
interface TestEmailPayload {
  recipient: string;
  /**
   * The editor's current content, exactly as `getContent()` would return it.
   * Always present.
   */
  content: TemplateContent;
  /**
   * The template rendered to MJML.
   *
   * Present only when {@link TestEmailOptions.includeMjml} is set **and**
   * `@templatical/renderer` resolved. Always guard for absence: opting in
   * without the renderer installed still sends, just without this field (the
   * editor logs one warning naming the package).
   *
   * You still have to compile MJML to HTML — the editor never does, and
   * deliberately doesn't bundle a compiler.
   */
  mjml?: string;
  /**
   * Echo of {@link TestEmailOptions.allowedRecipients}, present only when one
   * was configured.
   *
   * **Untrusted.** It is read out of the browser and carries no signature, so it
   * is not authoritative about anything. Two things it is genuinely useful for:
   * keeping one `send` implementation portable between your own backend and
   * Templatical Cloud, and comparing it against `recipient` server-side — a
   * mismatch means the client was tampered with or is buggy, which is worth
   * logging. Never treat it *as* the allowlist; that list belongs on your
   * server.
   */
  allowedRecipients?: string[];
}
/**
 * Configuration and outward notifications for test-email sending. Every
 * member is optional.
 *
 * Separate from `send` so `initCloud()` can accept this half alone: these are
 * meaningful whichever backend does the sending, Cloud's own or yours.
 * {@link TestEmailProvider} extends this, adding only `send`.
 */
interface TestEmailOptions {
  /**
   * Also render the template to MJML and pass it as
   * {@link TestEmailPayload.mjml}, saving you a `renderToMjml()` call.
   *
   * **Requires `@templatical/renderer`**, an optional peer dependency. If it
   * isn't installed the send still happens with JSON only and one warning is
   * logged — opting in never breaks sending. A *rendering* failure is different:
   * that fails the send, because it means the template itself is broken and
   * silently sending without the MJML would hide it.
   */
  includeMjml?: boolean;
  /**
   * Restrict who may be sent to:
   *
   * - **omitted** — the dialog accepts free text, validated for shape only;
   * - **one entry** — a read-only field, pre-filled with it;
   * - **several** — a picker of exactly those addresses;
   * - **empty array** — nobody may be sent to, so the feature reports itself
   *   unavailable and no trigger renders. `[]` is read as a decision, not as
   *   "unset".
   *
   * A picker constraint, **not a security boundary**: this array lives in the
   * user's browser and is trivially edited there. Validate the recipient on your
   * server regardless of what the dialog offered.
   */
  allowedRecipients?: string[];
  /**
   * Pre-fills the recipient field. Ignored when it isn't in
   * {@link allowedRecipients}.
   */
  defaultRecipient?: string;
  /**
   * A test send completed. Fires once `send` resolves, with the same payload
   * it was given — never for a rejected send, since that surfaces through the
   * dialog's own inline error instead.
   */
  onSent?: (payload: TestEmailPayload) => void;
}
/**
 * Sending contract for test emails. Implement it to let users send a test of the
 * template they're editing through your own infrastructure — the editor owns the
 * trigger, the dialog, recipient validation and the sending/success/error
 * states; you own delivery.
 *
 * Pass an implementation as `testEmail` to `init()`. When omitted the feature
 * stays off entirely and no trigger renders.
 *
 * ```ts
 * const provider: TestEmailProvider = {
 *   send: ({ recipient, content }) =>
 *     fetch("/api/test-email", {
 *       method: "POST",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify({ recipient, content }),
 *     }).then((r) => {
 *       if (!r.ok) throw new Error("Could not send the test email");
 *     }),
 * };
 * ```
 */
interface TestEmailProvider extends TestEmailOptions {
  /**
   * Deliver a test of the current template.
   *
   * Resolve on success — the dialog confirms, then closes. Reject with a
   * **user-presentable** message on failure: the dialog renders `error.message`
   * inline and stays open so the user can retry.
   */
  send(payload: TestEmailPayload): Promise<void>;
}
//#endregion
//#region src/media.d.ts
/**
 * Which kind of file a listing or picker is constrained to.
 *
 * Image fields and the video thumbnail pass `["images"]`. Custom blocks may
 * pass other categories. The modal forces `list({ category })` to that set.
 */
type MediaCategory = "images" | "documents" | "videos" | "audio";
/**
 * One file in a media library — the row `list` returns and `create` persists.
 *
 * Distinct from `MediaResult` in `./config` (`{ url, alt? }`): that is what
 * an image field stores. A picked asset is reduced to a result at confirm;
 * the library itself talks in assets.
 *
 * The store owns `id` — it is returned by {@link MediaProvider.create} and
 * never generated by the editor, so identity stays a property of your storage.
 *
 * There is no conversion set (`small` / `medium` / `large`) on this type. The
 * grid uses {@link thumbnailUrl} falling back to {@link url}; confirm always
 * inserts `url`. If a derivative belongs in the email, put that URL on `url`.
 */
interface MediaAsset {
  /** Store-assigned. The editor never generates one. */
  id: string;
  /** The URL that lands on the block when the asset is confirmed. */
  url: string;
  alt?: string;
  filename?: string;
  mimeType?: string;
  width?: number;
  height?: number;
  /** Size in bytes. */
  size?: number;
  /**
   * Grid thumbnail. Falls back to {@link url} when omitted, so a store that
   * only has one URL still renders.
   */
  thumbnailUrl?: string;
  /** Folder this asset sits in, or `null` / omitted for the root. */
  folderId?: string | null;
  /**
   * Store-assigned timestamps, ISO 8601, used for display only. They do not
   * affect ordering — the editor renders whatever order `list()` returns.
   */
  createdAt?: string;
  updatedAt?: string;
  /**
   * Per-entry permission carve-outs. **Absent means allowed** — the provider's
   * `update` / `delete` already say whether the capability exists at all, so
   * these exist only to forbid it on *particular* entries.
   *
   * They compose one-way: `canUpdate: true` cannot re-enable an `update: false`.
   */
  canUpdate?: boolean;
  canDelete?: boolean;
}
/**
 * One folder in the library. {@link MediaFoldersProvider.list} returns these
 * **flat**; the UI trees them via {@link parentId}.
 */
interface MediaFolder {
  id: string;
  name: string;
  /** `null` / omitted = root. */
  parentId?: string | null;
}
/**
 * Parameters for {@link MediaProvider.list}.
 *
 * Unlike saved-blocks (which the editor calls bare and filters in memory),
 * these are **real**: galleries outgrow one response, so search, folder,
 * category and cursor are sent on every listing. A provider that ignores them
 * cannot page or search.
 *
 * `templateId` is opportunistic — present when a template is loaded, omitted
 * on a blank canvas. Cloud's store ignores it; a CMS that scopes a gallery
 * per template reads it here.
 */
interface MediaListParams {
  search?: string;
  cursor?: string;
  folderId?: string | null;
  category?: MediaCategory;
  /** When a template is loaded; Cloud ignores. */
  templateId?: string;
}
/**
 * One page of {@link MediaProvider.list}.
 *
 * An envelope rather than a bare array so pagination never needs a breaking
 * change: a cursor has somewhere to live from day one. A provider that returns
 * everything at once omits {@link nextCursor}.
 */
interface MediaListPage {
  items: MediaAsset[];
  nextCursor?: string;
}
/**
 * How many templates reference an asset, for the bulk-delete warning.
 *
 * Returned from {@link MediaProvider.checkUsage} keyed by asset id.
 */
interface MediaUsageInfo {
  templateCount: number;
  templateNames: string[];
}
/**
 * Quota snapshot for the storage ring. `storage()` may resolve `null` when
 * the store does not track quota (or, for Cloud, until plan config has loaded).
 */
interface MediaStorageInfo {
  usedBytes: number;
  limitBytes: number;
}
/**
 * Why the media picker opened. Passed to `onRequestMedia` and used by the
 * modal to constrain the listing.
 *
 * `files` is the drop path: image files dragged onto an image block. Absent
 * on click → Browse.
 */
interface MediaRequestContext {
  accept?: MediaCategory[];
  /** Drop path; absent on Browse. */
  files?: File[];
}
/** Payload for {@link MediaProvider.create}. */
interface MediaCreateInput {
  file: File;
  folderId?: string | null;
  alt?: string;
  filename?: string;
  templateId?: string;
}
/**
 * Partial patch for {@link MediaProvider.update}. Only the keys present are
 * being changed.
 */
interface MediaAssetPatch {
  alt?: string;
  filename?: string;
}
/** Payload for {@link MediaFoldersProvider.create}. */
interface MediaFolderInput {
  name: string;
  parentId?: string | null;
}
/**
 * Nested folder + move contract, so an OSS gallery writes `folders: false`
 * once rather than stubbing five methods.
 *
 * `list` returns a **flat** array; the UI trees it via {@link MediaFolder.parentId}.
 * A store whose HTTP API returns a tree flattens it here.
 */
interface MediaFoldersProvider {
  /** Flat listing. The one method that cannot be `false` when folders exist. */
  list(): Promise<MediaFolder[]>;
  create: false | ((input: MediaFolderInput) => Promise<MediaFolder>);
  update: false | ((id: string, patch: {
    name: string;
  }) => Promise<MediaFolder>);
  delete: false | ((id: string) => Promise<void>);
  /**
   * Move assets into a folder (`folderId: null` = root) and return the stored
   * results. Bulk — the grid is multi-select.
   */
  move: false | ((ids: string[], folderId: string | null) => Promise<MediaAsset[]>);
}
/**
 * Configuration and outward notifications for the media library. Every member
 * is optional.
 *
 * Separate from the storage methods so `initCloud()` can accept this half
 * alone: these fire the same way whichever store holds the assets, Cloud's
 * own or yours. {@link MediaProvider} extends this, so one object satisfies
 * both entry points.
 *
 * `maxFileSize` / `mimeTypes` are a **client pre-check**, not a security
 * boundary — the backend must enforce too.
 */
interface MediaOptions {
  /** Bytes; client pre-check only. */
  maxFileSize?: number;
  mimeTypes?: Partial<Record<MediaCategory, string[]>>;
  /** An asset was created and prepended to the listing. */
  onCreated?: (asset: MediaAsset) => void;
  /** An asset was updated and its listing entry replaced. */
  onUpdated?: (asset: MediaAsset) => void;
  /**
   * An asset was deleted and filtered out of the listing. `delete` resolves
   * to nothing, so this carries the entry the editor captured before removing
   * it — not an id.
   *
   * Fires only when the entry was present in the locally loaded list at the
   * time of the delete. Deleting an id that was never loaded still deletes
   * successfully; there is just nothing to pass, so this does not fire.
   */
  onDeleted?: (asset: MediaAsset) => void;
}
/**
 * Storage contract for a media library. Implement it to back the editor's
 * media picker with your own persistence — the editor owns the modal, the
 * grid, crop (client-side; persisting a crop is `create` or `replace` of the
 * resulting `File`) and insertion; you own the transport.
 *
 * Pass an implementation as `media` to `init()`. When omitted, the feature
 * stays off entirely and image fields are URL-only. `onRequestMedia` remains
 * the UI override (a host widget); it is not this store.
 *
 * Every method may reject; the editor surfaces the failure through `onError`
 * and leaves its in-memory list untouched. Provider messages are
 * user-presentable.
 *
 * **Each method other than `list` can be turned off by passing `false`
 * instead of a function.** The editor then hides the affordance rather than
 * letting the user try and fail. They are required rather than optional
 * precisely so that disabling is a decision you state, never something you
 * get by forgetting a method. Setting every mutation to `false` yields a
 * **read-only library**: users still browse, search and pick, because picking
 * only copies a URL onto the canvas.
 *
 * `list` cannot be `false`: without it there is nothing to show.
 *
 * ```ts
 * const media: MediaProvider = {
 *   list: ({ search, cursor, templateId }) =>
 *     myCms.page({ search, cursor, templateId }),
 *   create: ({ file }) => myCms.upload(file),
 *   update: false,
 *   delete: false,
 *   folders: false,
 *   replace: false,
 *   importFromUrl: false,
 *   checkUsage: false,
 *   frequentlyUsed: false,
 *   storage: false,
 * };
 * ```
 */
interface MediaProvider extends MediaOptions {
  /**
   * Fetch one page of assets. Search, folder, category and cursor are real
   * params — this is not an in-memory filter over a full dump.
   *
   * The one method that cannot be disabled: without it the feature has nothing
   * to show.
   */
  list(params?: MediaListParams): Promise<MediaListPage>;
  /**
   * Persist a new asset from a `File` and return it with its store-assigned
   * `id`, or `false` to disable upload — the drop zone and upload control then
   * do not render. There is no progress callback; resolve with the asset.
   */
  create: false | ((input: MediaCreateInput) => Promise<MediaAsset>);
  /**
   * Apply a partial update and return the stored result, or `false` to disable
   * editing entirely. Per-entry exceptions go through
   * {@link MediaAsset.canUpdate}.
   */
  update: false | ((id: string, patch: MediaAssetPatch) => Promise<MediaAsset>);
  /**
   * Remove assets by id, resolving once the store has applied the delete, or
   * `false` to disable deletion entirely. **Bulk** — the grid is multi-select.
   * Per-entry exceptions go through {@link MediaAsset.canDelete}.
   */
  delete: false | ((ids: string[]) => Promise<void>);
  /**
   * Folder tree + move, or `false` to hide folders entirely. Nested so a
   * gallery without folders writes `folders: false` once.
   */
  folders: false | MediaFoldersProvider;
  /**
   * Replace an asset's file in place and return the stored result, or `false`
   * to disable replace.
   */
  replace: false | ((id: string, file: File) => Promise<MediaAsset>);
  /**
   * Import a remote URL into the library and return the stored asset, or
   * `false` to hide import. `folderId` / `templateId` are the same opportunistic
   * scoping as {@link MediaCreateInput}.
   */
  importFromUrl: false | ((url: string, folderId?: string | null, templateId?: string) => Promise<MediaAsset>);
  /**
   * Look up how many templates reference each asset, or `false` to skip the
   * usage warning on delete. **Bulk** — keyed by the same id array `delete`
   * takes.
   */
  checkUsage: false | ((ids: string[]) => Promise<Record<string, MediaUsageInfo>>);
  /**
   * Assets the current user reaches for often, or `false` to hide that tab.
   */
  frequentlyUsed: false | (() => Promise<MediaAsset[]>);
  /**
   * Current quota, or `false` to hide the storage ring. May resolve `null`
   * when the store does not (yet) know.
   */
  storage: false | (() => Promise<MediaStorageInfo | null>);
}
//#endregion
//#region src/templates.d.ts
/**
 * A stored template: its identity, an optional human-readable name, and the
 * content the editor edits.
 *
 * The store owns `id` — it is returned by {@link TemplatesProvider.create} and
 * never generated by the editor, so identity stays a property of your storage
 * (database primary key, slug, document id).
 */
interface Template {
  id: string;
  /**
   * Optional display name, shown in the editor header and editable inline.
   *
   * Optional because a store may not have a name column, in which case the
   * header renders nothing to edit. A rename is persisted as an ordinary
   * `save(id, { name })` patch — there is no separate rename method.
   */
  name?: string;
  /**
   * When your store created the template, ISO 8601.
   *
   * A fallback for {@link Template.updatedAt}: the header prefers `updatedAt`
   * and reads this only in its absence, so a store that records creation but not
   * modification still shows something.
   */
  createdAt?: string;
  /**
   * When your store last wrote the template, ISO 8601.
   *
   * Display-only — the header renders it as a relative label ("Updated 5m ago")
   * with the absolute date on hover. Both timestamps are absent from
   * {@link TemplatePatch}, so the editor never writes them: they are yours to
   * set, and the value the editor shows is whatever `load` or `save` returned.
   * Absent, or a value that does not parse, renders nothing.
   */
  updatedAt?: string;
  content: TemplateContent;
}
/**
 * Partial patch for {@link TemplatesProvider.save}. Only the keys present are
 * being changed, so a rename can travel without content and vice versa.
 *
 * A patch (rather than bare content) because retrofitting `save(id, content)`
 * into `save(id, patch)` later would break every implementation — the same
 * reasoning, and the same shape, as `SavedBlockPatch`.
 */
type TemplatePatch = Partial<{
  name: string;
  content: TemplateContent;
}>;
/**
 * Why a save happened, as reported to {@link TemplatesOptions.onSaved}.
 *
 * `manual` covers both the header's Save button and Cmd+S: one intent, and
 * splitting them would invite handling one and silently missing the other.
 *
 * The other three are separate because treating them as a Save press is wrong.
 * A `rename` writes through `save()` but the user only edited the name, and a
 * `restore` write is the confirmation step of restoring a version — navigating
 * away on either strands the user mid-task.
 */
type TemplateSaveTrigger = "manual" | "autosave" | "rename" | "restore" | "api";
/**
 * Configuration and outward notifications for the template lifecycle. Every
 * member is optional.
 *
 * Separate from the storage methods so `initCloud()` can accept this half alone:
 * Cloud owns template storage, because the id it issues is the join key for
 * collaboration, version history, comments, AI rewrite, scoring and the
 * server-side export. {@link TemplatesProvider} extends this, so one object
 * satisfies both entry points and moving to Cloud edits nothing.
 */
interface TemplatesOptions {
  /**
   * Save automatically, debounced, after the user stops editing.
   *
   * Lives here because it is meaningless without somewhere to save to. The
   * cadence is `changeDebounce` at the config root, since one timer drives both
   * this and the `onChange` notification, and `onChange` works with no provider.
   *
   * Defaults to off for `init()` and on for `initCloud()` — a Cloud session
   * always has a store.
   */
  autoSave?: boolean;
  /**
   * Warn before the tab closes with unsaved changes. Defaults to on.
   *
   * Cannot cover client-side route changes; `onDirtyChange` at the config root
   * is what guards a router, and it fires with or without a provider.
   */
  unsavedChangesGuard?: boolean;
  /**
   * Render the inline template-name field in the header. Defaults to on.
   *
   * `false` hides the field and nothing else: `create({ name })`, `setName()`
   * and the `name` in each save patch keep working, so your own chrome can still
   * manage names.
   */
  nameField?: boolean;
  /**
   * A save completed, with `isDirty` cleared and `isSaving` false — so a
   * handler may navigate without tripping the consumer's own unsaved-changes
   * guard. Never fires for a failed save; that reaches `onError`.
   *
   * `template` is the provider's response to `save()` as returned, not
   * necessarily what got adopted: a rename that lands mid-flight keeps the
   * local name, and under a concurrent `load()` it may describe a template
   * that is no longer open.
   */
  onSaved?: (template: Template, meta: {
    trigger: TemplateSaveTrigger;
  }) => void;
  /** A template was created and attached to the editor. */
  onCreated?: (template: Template) => void;
  /** A template was fetched and its content put on the canvas. */
  onLoaded?: (template: Template) => void;
}
/**
 * Storage contract for the template itself — the save/load lifecycle around
 * whatever the editor is editing.
 *
 * Deliberately **not** CRUD: there is no `list` and no `delete`, and the editor
 * has no template browser. Choosing *which* template to open belongs to your
 * own application, which then hands the id to `editor.load(id)`.
 *
 * Pass an implementation as `templates` to `init()`. When omitted, the header's
 * name field, save button and save-status indicator do not render, and
 * `create()` / `load()` / `save()` reject with an explanatory error.
 *
 * Every method may reject; the editor reports the failure through `onError`,
 * surfaces it in the header, and leaves its state untouched — nothing is marked
 * saved that wasn't.
 *
 * **Each mutation can be turned off by passing `false` instead of a function**,
 * mirroring `SavedBlocksProvider`. They are required rather than optional
 * precisely so that disabling is a decision you state, never something you get
 * by forgetting a method. `save: false` yields a genuine read-only mode (a
 * template still loads and can be edited locally, there is simply nothing to
 * persist); `create: false` yields a no-new-templates mode.
 *
 * ```ts
 * const provider: TemplatesProvider = {
 *   load: (id) => fetch(`/api/templates/${id}`).then((r) => r.json()),
 *   create: (input) =>
 *     fetch("/api/templates", {
 *       method: "POST",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify(input),
 *     }).then((r) => r.json()),
 *   save: (id, patch) =>
 *     fetch(`/api/templates/${id}`, {
 *       method: "PATCH",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify(patch),
 *     }).then((r) => r.json()),
 * };
 * ```
 */
interface TemplatesProvider extends TemplatesOptions {
  /**
   * Fetch a template by id. The one method that cannot be disabled: without it
   * there is nothing to open.
   */
  load(id: string): Promise<Template>;
  /**
   * Persist a new template and return it with its store-assigned `id`, or
   * `false` to disable creation entirely.
   */
  create: false | ((input: {
    name?: string;
    content: TemplateContent;
  }) => Promise<Template>);
  /**
   * Apply a partial update to an existing template and return the stored
   * result, or `false` to disable saving entirely — the editor then hides both
   * the save button and the save-status indicator.
   */
  save: false | ((id: string, patch: TemplatePatch) => Promise<Template>);
}
//#endregion
//#region src/merge-tags.d.ts
interface SyntaxPreset {
  value: RegExp;
  logic: RegExp;
}
type SyntaxPresetName = "liquid" | "handlebars" | "mailchimp" | "ampscript";
export declare const SYNTAX_PRESETS: Record<SyntaxPresetName, SyntaxPreset>;
/**
 * Resolves the autocomplete trigger string for a syntax preset.
 * Returns null when the syntax doesn't match any built-in preset
 * (custom regex syntax — autocomplete cannot be enabled safely).
 */
export declare function getSyntaxTriggerChar(syntax: SyntaxPreset): string | null;
/**
 * Resolves the closing delimiter for a syntax preset (e.g. `}}` for liquid,
 * `|*` for mailchimp). The autocomplete trigger detector uses it to tell an
 * open tag (`{{first`) from a completed one (`{{first_name}}`) so the popup
 * doesn't reappear over a finished tag. Returns null for custom syntaxes —
 * the same set for which `getSyntaxTriggerChar` returns null.
 */
export declare function getSyntaxClosingChar(syntax: SyntaxPreset): string | null;
export declare function resolveSyntax(syntax?: SyntaxPresetName | SyntaxPreset): SyntaxPreset;
export declare function isMergeTagValue(value: string, syntax: SyntaxPreset): boolean;
export declare function getMergeTagLabel(value: string, mergeTags: MergeTag[]): string;
export declare function resolveHtmlMergeTagLabels(html: string, mergeTags: MergeTag[]): string;
/**
 * The example value configured for `value`, or `undefined` when the tag is
 * unknown or declares none. Unlike `getMergeTagLabel`, which falls back to the
 * raw token, absence is reported as `undefined` so callers can choose their own
 * fallback — Sample mode falls back to the label, never to a raw token.
 */
export declare function getMergeTagSample(value: string, mergeTags: MergeTag[]): string | undefined;
/**
 * Rewrite rich-text HTML for the previews' Sample mode.
 *
 * A tag **with** a sample is replaced by that value as bare text, wrapper and
 * all — dropping the `<span>` is what removes the merge-tag highlight, so the
 * value reads as ordinary content. A tag **without** one keeps its span and
 * shows its label, so it stays visibly dynamic; that difference is deliberate,
 * and it doubles as a signal that a sample is still unset.
 *
 * The unwrapped output is inert — `data-merge-tag` is gone from it — so this
 * result must only ever reach a preview surface, never `getContent()`, an
 * export or a send.
 */
export declare function substituteHtmlMergeTagSamples(html: string, mergeTags: MergeTag[]): string;
/**
 * Whether any configured tag declares a `sample`.
 *
 * Gates the whole feature: with no samples anywhere the previews' Sample view
 * would be identical to the Label view, so the editor defaults to Label and
 * renders no toggle. That keeps the feature invisible until a consumer opts in.
 */
export declare function hasMergeTagSamples(mergeTags: MergeTag[]): boolean;
/**
 * Replace declared tokens with their sample values in a plain string — used for
 * values that reach no label-resolving component, namely `html` block content
 * and custom-block field values.
 *
 * Matching is on the exact configured `value`, so consumer text cannot
 * false-positive and `href="{{link}}"` resolves correctly. Tags without a
 * sample are left untouched, which is what keeps a missing sample visible.
 */
export declare function substituteTextMergeTagSamples(text: string, mergeTags: MergeTag[]): string;
export declare function containsMergeTag(value: string, syntax: SyntaxPreset): boolean;
export declare function isLogicMergeTagValue(value: string, syntax: SyntaxPreset): boolean;
export declare function getLogicMergeTagKeyword(value: string, syntax: SyntaxPreset): string;
export declare function resolveHtmlLogicMergeTagLabels(html: string, syntax: SyntaxPreset): string;
//#endregion
//#region src/config.d.ts
type ViewportSize = "desktop" | "mobile";
type UiTheme = "light" | "dark" | "auto";
interface CustomFont {
  name: string;
  url: string;
  fallback?: string;
}
interface FontsConfig {
  defaultFallback?: string;
  defaultFont?: string;
  customFonts?: CustomFont[];
  /**
   * Restrict which of the seven built-in fonts the font picker offers.
   *
   * - `true` / omitted — every built-in is offered (the default).
   * - `false` — no built-ins; the picker lists only `customFonts`. Use this to
   *   keep authors on an embedded brand kit's typefaces.
   * - `string[]` — an allowlist of built-in names to keep, matched
   *   case-insensitively (`['Georgia', 'arial']`). A name that isn't a built-in
   *   is logged with a warning and skipped — consistent with how
   *   `paletteBlocks` treats an unknown entry — so a typo narrows the list
   *   rather than silently offering all seven.
   *
   * Independent of `customFonts`: excluding the built-ins never removes a custom
   * font, and a custom font can still be the `defaultFont` when every built-in
   * is excluded. Filtering the picker never affects rendering — content already
   * using an excluded built-in still resolves to its proper fallback stack.
   */
  builtIns?: boolean | string[];
}
interface ColorsConfig {
  /**
   * Preset colors rendered as a clickable grid inside every color picker
   * popover. Each entry is a hex string (`'#0b5cff'`); clicking one applies it,
   * and the preset matching the current value is marked selected (matched
   * case-insensitively). The grid supplements the wheel and hex input unless
   * `allowCustom` is `false`.
   */
  presets?: string[];
  /**
   * Allow free-form color entry — the wheel and hex input — alongside the
   * presets. Defaults to `true`.
   *
   * Set to `false` together with `presets` to lock authors to the preset
   * palette: the popover then offers only the preset grid, with no wheel or hex
   * field (a white-label / brand-kit constraint). Ignored with a warning when
   * no `presets` are configured — hiding the only inputs would leave the picker
   * with no way to choose a color.
   */
  allowCustom?: boolean;
}
interface TemplateSettingsConfig {
  /**
   * Which template settings the Settings panel exposes.
   *
   * - `true` / omitted — every setting is editable (the default).
   * - `false` — none; the Settings tab itself stops rendering.
   * - `Array<keyof TemplateSettings>` — an allowlist of settings to keep
   *   (`['width', 'backgroundColor', 'fontFamily']`). A card renders when at
   *   least one of its settings survives, so hiding `locale` removes the
   *   Language card and hiding `preheaderText` removes the Preheader card. An
   *   empty array means none, the same as `false`.
   *
   * The list narrows, it never reorders — settings sit in fixed cards, so
   * unlike `paletteBlocks` there is no order to express. An entry that isn't a
   * `TemplateSettings` member is a compile error for TypeScript callers, and is
   * logged with a warning and skipped at runtime, so a typo narrows the panel
   * rather than silently restoring every setting.
   *
   * Presentation only. Hiding a setting never changes its value: whatever the
   * loaded content carries keeps rendering and keeps round-tripping through
   * `getContent()`. Set the values you hide from the content you hand the
   * editor — `init({ content })`, or your own `templates.load`.
   */
  fields?: boolean | Array<keyof TemplateSettings>;
}
interface ExportResult {
  html: string;
  mjml: string;
}
interface MergeTag {
  label: string;
  value: string;
  /**
   * Optional grouping label used by the built-in merge tag picker to
   * section the list. When no tag in the configured array carries
   * `group`, the picker renders a plain flat list with no headers.
   * Ignored by the renderer and by typing-autocomplete.
   */
  group?: string;
  /**
   * Optional helper text shown beneath the tag in the built-in merge
   * tag picker. Not rendered anywhere else (toolbar, autocomplete,
   * MJML output) and not stored on the inserted document node.
   */
  description?: string;
  /**
   * Example value shown in place of this tag on preview surfaces — e.g.
   * `"Ada"` for `{{first_name}}` — so a preview reads like a delivered
   * email instead of a list of field names.
   *
   * Display-only, and only in the previews' Sample mode: never written to
   * the template, never sent, never present in MJML output. Setting it is
   * the whole opt-in; there is no accompanying flag. A tag without a
   * sample keeps showing its `label`.
   */
  sample?: string;
}
interface MediaResult {
  url: string;
  alt?: string;
}
/**
 * Why the merge-tag chooser opened, handed to {@link MergeTagsConfig.onRequest}.
 *
 * `"insert"` is a new tag at the caret. `"edit"` is the user activating a tag
 * that is already in the content, asking to swap it for another one.
 */
interface MergeTagRequestContext {
  reason: "insert" | "edit";
  /**
   * The tag being replaced. Present only when `reason` is `"edit"` AND the
   * token in the content resolves against `tags` — a token that matches no
   * configured tag still opens the chooser, with nothing to preselect.
   */
  current?: MergeTag;
}
interface MergeTagsConfig {
  syntax?: SyntaxPresetName | SyntaxPreset;
  tags?: MergeTag[];
  /**
   * Consumer-owned chooser. Called both to insert a tag at the caret and to
   * replace one already in the content — `context.reason` says which. Return
   * the chosen tag, or `null` to cancel.
   *
   * The parameter is optional, so an existing zero-argument implementation
   * keeps working unchanged.
   */
  onRequest?: (context?: MergeTagRequestContext) => Promise<MergeTag | null>;
  /**
   * Whether a tag's tooltip reveals the raw token behind its label. Defaults
   * to `true`, which suits a readable syntax like `{{first_name}}` — the
   * tooltip tells an author which field they are looking at.
   *
   * Set `false` when `value` is an internal identifier (an opaque id resolved
   * by your backend) that an author should never see. Display-only: the token
   * is unchanged in stored content and in the rendered output.
   */
  showRawValue?: boolean;
  /**
   * Enables typing-based autocomplete in rich text blocks and in every
   * merge-tag-enabled input/textarea field (toolbars, template settings,
   * custom-block text fields). When the user types the syntax opener
   * (e.g. `{{`), a popup lists matching `tags`. Both surfaces share the
   * same popup, so behavior is identical.
   *
   * Defaults to `true`. Effective only when `tags` is non-empty AND
   * `syntax` matches a built-in preset (custom regex syntaxes cannot be
   * mapped to a trigger string and silently disable autocomplete).
   */
  autocomplete?: boolean;
}
/**
 * A standalone logic tag — a control-flow token (e.g. `{% else %}`) inserted
 * at the cursor. Distinct from data merge tags; rendered as a keyword badge.
 */
interface LogicTag {
  label: string;
  value: string;
  /** Optional grouping label used to section the logic picker. */
  group?: string;
  /** Optional helper text shown beneath the tag in the picker. */
  description?: string;
}
/**
 * A paired logic construct — an opening tag (`before`) and its matching closer
 * (`after`), e.g. `{% if vip %}` … `{% endif %}`. Selecting one inserts both
 * pills at once, wrapping the selection (or with the caret placed between
 * them). Shares its `before`/`after` shape with `DisplayCondition`.
 */
interface LogicPair {
  label: string;
  /** Opening logic tag, including delimiters (e.g. `{% if vip %}`). */
  before: string;
  /** Closing logic tag, including delimiters (e.g. `{% endif %}`). */
  after: string;
  /** Optional grouping label used to section the logic picker. */
  group?: string;
  /** Optional helper text shown beneath the pair in the picker. */
  description?: string;
}
/**
 * Standalone logic-tag configuration, independent of `mergeTags`. `tags` are
 * single control-flow tokens inserted at the cursor; `pairs` are open/close
 * constructs inserted around the selection. Both appear in the built-in logic
 * picker, grouped together by `group`. Typed/pasted logic highlighting is
 * always on regardless of this.
 */
interface LogicTagsConfig {
  tags?: LogicTag[];
  pairs?: LogicPair[];
  /**
   * Consumer-owned picker. When set, the "Insert logic" affordance calls this
   * instead of the built-in logic picker — return the chosen tag/pair (or
   * `null` to cancel). Mirrors `MergeTagsConfig.onRequest`; lets consumers use
   * their own UI and custom syntax. Precedence: `onRequest` → built-in picker.
   */
  onRequest?: () => Promise<LogicTag | LogicPair | null>;
}
interface DisplayCondition {
  label: string;
  before: string;
  after: string;
  group?: string;
  description?: string;
}
interface DisplayConditionsConfig {
  conditions: DisplayCondition[];
  allowCustom?: boolean;
}
interface ThemeOverrides {
  bg?: string;
  bgElevated?: string;
  bgHover?: string;
  bgActive?: string;
  border?: string;
  borderLight?: string;
  text?: string;
  textMuted?: string;
  textDim?: string;
  primary?: string;
  primaryHover?: string;
  primaryLight?: string;
  secondary?: string;
  secondaryHover?: string;
  secondaryLight?: string;
  success?: string;
  successLight?: string;
  warning?: string;
  warningLight?: string;
  danger?: string;
  dangerLight?: string;
  canvasBg?: string;
  dark?: Omit<ThemeOverrides, "dark">;
}
export declare class SdkError extends Error {
  readonly statusCode?: number | undefined;
  constructor(message: string, statusCode?: number | undefined);
  get isNotFound(): boolean;
  get isUnauthorized(): boolean;
  get isServerError(): boolean;
}
//#endregion
//#region src/render.d.ts
/**
 * Everything a {@link RenderProvider} needs to render a template, handed over as
 * one object so the editor's obligations are stated rather than implied.
 *
 * The editor guarantees the payload is **render-complete**: whatever a backend
 * cannot know by itself has already been resolved into it.
 */
interface RenderPayload {
  /**
   * The template to render, with every custom block's `renderedHtml` already
   * filled in.
   *
   * This is the part a server genuinely cannot do: a custom block's HTML comes
   * from the consumer's liquid template plus the block's field values, and the
   * template registration lives in the browser. A renderer that receives a
   * custom block with neither a resolver nor `renderedHtml` omits it silently,
   * so pre-rendering is a contract obligation, not an optimisation.
   *
   * A defensive copy — mutating it does not touch what the user is editing.
   */
  content: TemplateContent;
  /**
   * The fonts the editor is actually rendering with: the custom faces it
   * resolved, plus the fallback stack to use for anything unmatched.
   *
   * Optional on the type so a headless caller can omit it; the editor always
   * sends it, because a font list assembled from `init({ fonts })` is not
   * something a backend can reconstruct from `content` alone.
   */
  fonts?: {
    customFonts: CustomFont[];
    defaultFallback: string;
  };
}
/**
 * Rendering backend — how a template becomes MJML, and how MJML becomes the HTML
 * that gets sent.
 *
 * Deliberately separate from `TemplatesProvider`: saving and rendering run
 * at different frequencies (autosave would compile MJML on every debounce tick),
 * fail in different ways, and are wanted by different callers. Rendering is never
 * a field on a save result.
 *
 * Pass an implementation as `render` to `init()` or `initCloud()`. **Every method
 * is independently optional**, and each one the editor resolves on its own:
 *
 * | Call | Order |
 * |---|---|
 * | `editor.toMjml()` | {@link toMjml} → the local `@templatical/renderer` → throw |
 * | `editor.toHtml()` | {@link toHtml} → `toMjml()`'s result + {@link compileMjml} → throw |
 *
 * **There is no local HTML path, ever.** The SDK does not bundle an MJML
 * compiler, so `toHtml()` without either `toHtml` or `compileMjml` rejects with
 * an explanatory error rather than guessing.
 *
 * ```ts
 * // The cheapest useful implementation: one dumb mjml2html endpoint, and the
 * // editor gains `toHtml()` while still rendering MJML locally.
 * const editor = await init({
 *   container,
 *   render: {
 *     compileMjml: (mjml) =>
 *       fetch("/api/mjml", { method: "POST", body: mjml }).then((r) => r.text()),
 *   },
 * });
 *
 * const html = await editor.toHtml();
 * ```
 */
interface RenderProvider {
  /**
   * Render the template to MJML source. Wins over the bundled renderer — a
   * backend can render block types or refinements the browser cannot (a
   * server-generated countdown GIF, a composited video thumbnail), so its output
   * is treated as authoritative.
   */
  toMjml?(payload: RenderPayload): Promise<string>;
  /**
   * Render the template straight to sending-ready HTML, skipping the MJML round
   * trip. Implement this when your backend already owns the whole pipeline.
   */
  toHtml?(payload: RenderPayload): Promise<string>;
  /**
   * Compile MJML to HTML. A dumb `mjml2html` endpoint — it needs no knowledge of
   * the block model, which is exactly the point: MJML compilation is a commodity
   * (an off-the-shelf service, a container, a CLI shell-out), whereas rendering
   * Templatical JSON is not.
   *
   * This is the cheap tier, and the reason the interface has three methods
   * instead of two: without it, every non-Node backend that wants HTML would have
   * to stand up a Node sidecar first.
   */
  compileMjml?(mjml: string): Promise<string>;
}
//#endregion
//#region src/version-history.d.ts
/**
 * One recorded version of a template.
 *
 * Called a *version* rather than a snapshot deliberately: "snapshot" is an
 * implementation word, and it collides with the editor's undo/redo history,
 * which is a different thing entirely (in-session, unsaved, per-keystroke).
 */
interface TemplateVersion {
  /** Store-assigned. The editor never generates one. */
  id: string;
  /** ISO 8601. Drives the relative-time label in the history dropdown. */
  createdAt: string;
  /**
   * Recorded by a save rather than by a person. Drives the "auto" badge, and is
   * where a future filter would key off.
   */
  isAutomatic?: boolean;
  /** Short human label, when your store lets someone name a version. */
  label?: string;
  author?: {
    id?: string;
    name?: string;
  };
  /**
   * Optional eager content — a **cache hint**, never an alternative to
   * {@link VersionHistoryProvider.get}.
   *
   * When present the editor previews this version instantly and never calls
   * `get` for it. Evaluated **per entry**, so a provider may hydrate the recent
   * versions and omit the older ones.
   *
   * This exists because scrubbing through history is synchronous: once the
   * preview is open, stepping to another version swaps the canvas in the same
   * tick. A provider that eager-loads keeps that; one that omits `content` pays
   * a single round-trip the first time each version is visited, and the editor
   * caches it thereafter.
   */
  content?: TemplateContent;
}
/**
 * Page request for {@link VersionHistoryProvider.list}.
 *
 * The editor always calls `list` bare — it loads one page and renders it. Both
 * fields exist for headless callers and for providers that page their own
 * storage; a provider free to return everything at once may ignore them.
 */
interface VersionHistoryListParams {
  /** Maximum entries to return. A provider may return fewer, never more. */
  limit?: number;
  /**
   * Opaque cursor taken from a previous result's
   * {@link VersionHistoryListResult.nextCursor}.
   */
  cursor?: string;
}
/**
 * What {@link VersionHistoryProvider.list} resolves to.
 *
 * An envelope rather than a bare array **so that adding pagination never breaks
 * an implementation**: a cursor has somewhere to live from day one. Reserving
 * only the params object would have solved the request side and left the
 * response side needing a breaking change.
 */
interface VersionHistoryListResult {
  /**
   * The versions to offer, newest first. The editor renders this order verbatim
   * and never re-sorts — ordering is your store's call.
   */
  versions: TemplateVersion[];
  /**
   * Cursor for the next page, or absent when this is the last one. Opaque to
   * the editor: pass it back as {@link VersionHistoryListParams.cursor}.
   * A provider that returns its whole history at once omits it.
   */
  nextCursor?: string;
}
/**
 * Outward notifications about a template's version history. Every member is
 * optional.
 *
 * Separate from the storage methods so `initCloud()` can accept this half
 * alone: a version is keyed to a template id Cloud issued, so Cloud owns
 * version-history storage. {@link VersionHistoryProvider} extends this, so one
 * object satisfies both entry points.
 */
interface VersionHistoryOptions {
  /**
   * A version was recorded through {@link VersionHistoryProvider.create}. Not
   * called for a version your `save` implementation records automatically —
   * that happens inside your own backend, outside anything the editor can see.
   */
  onCreated?: (version: TemplateVersion) => void;
  /**
   * A past version was made current. Takes the **resulting `Template`** that
   * {@link VersionHistoryProvider.restore} resolves to, not the
   * {@link TemplateVersion} that was restored from.
   */
  onRestored?: (template: Template) => void;
}
/**
 * Storage contract for a template's version history.
 *
 * Pass an implementation as `versionHistory` to `init()` or `initCloud()`. With
 * no provider the history control does not render and none of its UI is
 * downloaded.
 *
 * **The editor never creates versions on its own.** Whoever implements
 * `TemplatesProvider.save` decides whether a save also records a version, which
 * keeps throttling, retention and dedupe policy on the side that pays for the
 * storage. {@link create} is for versions a *person* asks for.
 *
 * ```ts
 * const provider: VersionHistoryProvider = {
 *   list: (templateId) =>
 *     fetch(`/api/templates/${templateId}/versions`).then((r) => r.json()),
 *   get: (templateId, versionId) =>
 *     fetch(`/api/templates/${templateId}/versions/${versionId}`)
 *       .then((r) => r.json())
 *       .then((v) => v.content),
 *   create: false,
 *   // No atomic restore endpoint? Compose it: read the old content, save it.
 *   restore: async (templateId, versionId) => {
 *     const content = await provider.get(templateId, versionId);
 *     return templates.save(templateId, { content });
 *   },
 * };
 * ```
 */
interface VersionHistoryProvider extends VersionHistoryOptions {
  /** One page of versions. See {@link VersionHistoryListResult}. */
  list(templateId: string, params?: VersionHistoryListParams): Promise<VersionHistoryListResult>;
  /**
   * Fetch one version's content. **The operation, and always required** — the
   * editor must always be able to obtain a version's content.
   * {@link TemplateVersion.content} is the optimisation, and optimisations don't
   * get to be mandatory.
   */
  get(templateId: string, versionId: string): Promise<TemplateContent>;
  /**
   * Record the current content as a version on demand, or `false` to disable
   * it — the editor then offers no way to create one by hand, and the history
   * is whatever `save` recorded.
   *
   * `false`-able and required rather than optional, mirroring
   * `SavedBlocksProvider` and `TemplatesProvider`: disabling is a decision you
   * state, never something you get by forgetting a method.
   */
  create: false | ((templateId: string, content: TemplateContent, meta?: {
    label?: string;
  }) => Promise<TemplateVersion>);
  /**
   * Make a past version current and return the resulting template, or `false`
   * to make history read-only — versions can then be browsed and previewed, but
   * the Restore action does not render.
   *
   * **History is append-only:** a restore adds an entry rather than rewriting
   * one, so undo stays coherent and two backends can't disagree about what
   * history looks like afterwards. A store with no atomic endpoint composes it
   * in one line — `get` the old content, then `save` it — accepting two
   * round-trips and a narrower failure window.
   */
  restore: false | ((templateId: string, versionId: string) => Promise<Template>);
}
//#endregion
//#region src/comments.d.ts
/**
 * Who wrote a comment, or resolved one.
 *
 * The same shape as {@link EditorUser}, and deliberately so — a comment's author
 * is whoever was editing. It is a separate name only because a store returns
 * authors it did not get from this session.
 */
interface CommentAuthor {
  id: string;
  name: string;
}
/**
 * One comment — a thread root, or a reply to one.
 *
 * Threads are **one level deep**: a root carries {@link replies}, and a reply
 * never does. That is what the editor renders, and flattening a deeper tree is
 * your store's problem rather than the editor's.
 */
interface Comment {
  /** Store-assigned. The editor never generates one. */
  id: string;
  body: string;
  author: CommentAuthor;
  /** ISO 8601. */
  createdAt: string;
  /**
   * ISO 8601, present only when the body has been edited since. Drives the
   * "(edited)" marker, so a store that stamps it on creation makes every comment
   * look edited.
   */
  updatedAt?: string;
  /**
   * The block this comment is anchored to, or `null` for a comment about the
   * template as a whole.
   */
  blockId?: string | null;
  /** The thread root this is a reply to, or `null` for a root. */
  parentId?: string | null;
  /** ISO 8601 when resolved; `null` or absent while the thread is open. */
  resolvedAt?: string | null;
  /** Who resolved it. Absent when unresolved, or when your store doesn't track it. */
  resolvedBy?: CommentAuthor | null;
  /** Replies to this root, oldest first. Absent or empty on a reply. */
  replies?: Comment[];
}
/** What {@link CommentsProvider.create} is asked to store. */
interface CommentInput {
  body: string;
  /** Omitted for a template-level comment. */
  blockId?: string;
  /** Omitted for a thread root. */
  parentId?: string;
}
/**
 * Partial patch for {@link CommentsProvider.update}. A patch rather than a bare
 * body, matching `TemplatePatch` and `SavedBlockPatch` — retrofitting one later
 * would break every implementation, and only the shape is being paid for now.
 */
type CommentPatch = Partial<{
  body: string;
}>;
/**
 * Reserved filter object for {@link CommentsProvider.list}.
 *
 * Empty today. The editor always calls `list` bare and narrows in memory
 * (unresolved / all / this block), so the provider decides *what is visible*
 * and the editor decides how it is filtered within that.
 *
 * **Not a pagination hook, and comments deliberately has none.** `useComments`
 * derives `unresolvedCount` (the header badge) and `commentCountByBlock` (the
 * per-block canvas indicators) over the *whole* loaded list. A partial page
 * would make both under-report silently — wrong rather than slow. Correct
 * paging would mean moving counts and filtering server-side, which is a
 * redesign, not a `loadMore()`. A long-lived template caps its own growth by
 * having `list()` stop returning resolved threads past some age; the panel
 * hides those by default anyway. Contrast {@link VersionHistoryListParams},
 * which does page: its list is a flat menu with nothing aggregating over it.
 */
interface CommentsListParams {}
/**
 * One remote change, as reported by {@link CommentsProvider.subscribe}.
 *
 * A discriminated union rather than a `{ type, comment }` pair, because a delete
 * has no comment to carry — only the id, plus the parent so the editor knows
 * which list to remove it from without looking it up first.
 */
type CommentChange = {
  type: "created";
  comment: Comment;
} | {
  type: "updated";
  comment: Comment;
} | {
  type: "deleted";
  commentId: string;
  parentId?: string | null;
};
/**
 * Where a comment change came from.
 *
 * `local` — the mutation ran through your own `create` / `update` / `delete` /
 * `setResolved`, called by this editor. `remote` — it arrived through
 * {@link CommentsProvider.subscribe} and this editor never called a mutation
 * method: someone else, in another browser.
 *
 * A "new comments" badge counts `remote` only; counting `local` too makes a
 * user's own comment increment their own unread count.
 */
interface CommentEventMeta {
  origin: "local" | "remote";
}
/**
 * Outward notifications about the review conversation. Every member is optional.
 *
 * Separate from the storage methods so `initCloud()` can accept this half alone:
 * a comment is keyed to a template id Cloud issued and its author is signed by
 * the auth token, so Cloud owns the conversation. {@link CommentsProvider}
 * extends this, so one object satisfies both entry points.
 *
 * Each fires once per change the editor applied, after the list reflects it. A
 * handler that throws is reported through `onError` and never fails the write.
 */
interface CommentsOptions {
  onCreated?: (comment: Comment, meta: CommentEventMeta) => void;
  onUpdated?: (comment: Comment, meta: CommentEventMeta) => void;
  onDeleted?: (comment: Comment, meta: CommentEventMeta) => void;
  /**
   * Which of `onResolved` / `onUnresolved` fires is decided by the **stored**
   * result's `resolvedAt`, never by the state that was requested — a store may
   * refuse to reopen, and the handler should hear what happened.
   */
  onResolved?: (comment: Comment, meta: CommentEventMeta) => void;
  onUnresolved?: (comment: Comment, meta: CommentEventMeta) => void;
}
/**
 * Storage contract for **comments** — the review conversation on a template.
 *
 * Pass an implementation as `comments` to `init()`. With no provider the panel,
 * its trigger and the per-block indicators do not render and none of that UI is
 * downloaded.
 *
 * Comments also need to know **who is commenting**, which is not part of this
 * contract: it is the top-level `user` config key, because collaboration presence
 * will want the same answer and a provider-local copy would be the first thing to
 * drift. With no `user` the feature reports itself unavailable — an
 * unattributable comment is worse than no comment feature.
 *
 * **Each mutation can be turned off by passing `false` instead of a function**,
 * mirroring `SavedBlocksProvider`, `TemplatesProvider` and
 * `VersionHistoryProvider`. They are required rather than optional precisely so
 * that disabling is a decision you state, never something you get by forgetting a
 * method. All four `false` yields a read-only review: existing threads are
 * browsable and jump-to-block still works, with no way to add, edit, delete or
 * resolve.
 *
 * ```ts
 * const provider: CommentsProvider = {
 *   list: (templateId) =>
 *     fetch(`/api/templates/${templateId}/comments`).then((r) => r.json()),
 *   create: (templateId, input) =>
 *     fetch(`/api/templates/${templateId}/comments`, {
 *       method: "POST",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify(input),
 *     }).then((r) => r.json()),
 *   update: (templateId, commentId, patch) =>
 *     fetch(`/api/templates/${templateId}/comments/${commentId}`, {
 *       method: "PATCH",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify(patch),
 *     }).then((r) => r.json()),
 *   delete: async (templateId, commentId) => {
 *     await fetch(`/api/templates/${templateId}/comments/${commentId}`, {
 *       method: "DELETE",
 *     });
 *   },
 *   setResolved: (templateId, commentId, resolved) =>
 *     fetch(`/api/templates/${templateId}/comments/${commentId}/resolve`, {
 *       method: "POST",
 *       headers: { "Content-Type": "application/json" },
 *       body: JSON.stringify({ resolved }),
 *     }).then((r) => r.json()),
 * };
 * ```
 */
interface CommentsProvider extends CommentsOptions {
  /**
   * The thread roots to show, each with its `replies`. The editor renders this
   * order verbatim and never re-sorts — ordering is your store's call.
   *
   * The one method that cannot be disabled: without it there is nothing to show.
   */
  list(templateId: string, params?: CommentsListParams): Promise<Comment[]>;
  /**
   * Store a new comment or reply and return it with its store-assigned `id`, or
   * `false` to make the review read-only.
   */
  create: false | ((templateId: string, input: CommentInput) => Promise<Comment>);
  /**
   * Apply a partial update and return the stored result, or `false` to disable
   * editing — the pencil action then does not render on any comment.
   */
  update: false | ((templateId: string, commentId: string, patch: CommentPatch) => Promise<Comment>);
  /**
   * Remove a comment (and, for a root, its replies), or `false` to disable
   * deletion. Resolves to nothing: there is no post-delete state to report.
   */
  delete: false | ((templateId: string, commentId: string) => Promise<void>);
  /**
   * Mark a thread resolved or reopened and return the stored result, or `false`
   * to disable it.
   *
   * Takes the **target state** rather than toggling, so the call is idempotent
   * and a store that receives two clicks in flight cannot end up inverted.
   */
  setResolved: false | ((templateId: string, commentId: string, resolved: boolean) => Promise<Comment>);
  /**
   * **Optional.** Push remote changes into the open panel, so a colleague's
   * comment appears without a reload.
   *
   * Realtime is separable from comments rather than a prerequisite for them:
   * without this the feature works exactly as it does with it, you just don't see
   * someone else's comment until the list is next read. Returns an unsubscribe
   * function; the editor calls it when the template changes and on teardown.
   *
   * ```ts
   * subscribe: (templateId, onChange) => {
   *   const source = new EventSource(`/api/templates/${templateId}/comments/stream`);
   *   source.onmessage = (e) => onChange(JSON.parse(e.data) as CommentChange);
   *   return () => source.close();
   * }
   * ```
   *
   * Your own writes may echo back through here. Neither the list nor
   * {@link CommentsOptions} needs de-duplication on your side: a `created` or
   * `updated` for a comment already in the list replaces the existing entry by
   * id, and the matching handler fires only when that replacement actually
   * changes the stored comment — a same-content echo replaces silently, with
   * nothing to notify. The comparison is structural equality over the stored
   * shape (`sameComment` decides both), so an echo whose transport frame
   * serializes identical content in a different key order is not recognized
   * as the same comment.
   */
  subscribe?: (templateId: string, onChange: (change: CommentChange) => void) => () => void;
}
//#endregion
//#region src/user.d.ts
/**
 * Who is using the editor right now — `init({ user })`.
 *
 * A **top-level config key, not part of any provider.** Comments are the first
 * feature to need it (the panel decides which comments may be edited or deleted
 * by comparing `id` against each author, and a new comment is attributed to
 * `name`), but collaboration presence will want exactly the same answer. Putting
 * it on the comments provider would guarantee a second, drifting copy the moment
 * the second feature landed.
 *
 * Features that need an identity **report themselves unavailable without one**
 * rather than falling back to an anonymous author. An unattributable comment is
 * worse than no comment feature — the same reasoning that makes an explicitly
 * empty `TestEmailProvider.allowedRecipients` disable the feature instead of
 * degrading to free text.
 *
 * Not a security boundary: this identifies the user to the editor's UI, in the
 * user's own browser. Whatever your provider writes must be attributed
 * server-side, from the session your backend already trusts.
 */
interface EditorUser {
  /**
   * Stable identifier, compared against `Comment.author.id`. Whatever your
   * backend calls a user — a primary key, a UUID, an email.
   */
  id: string;
  /** Display name, shown on the comments this session writes. */
  name: string;
}
//#endregion
//#region src/guards.d.ts
export declare function isSection(block: Block): block is SectionBlock;
export declare function isTitle(block: Block): block is TitleBlock;
export declare function isParagraph(block: Block): block is ParagraphBlock;
export declare function isImage(block: Block): block is ImageBlock;
export declare function isButton(block: Block): block is ButtonBlock;
export declare function isDivider(block: Block): block is DividerBlock;
export declare function isVideo(block: Block): block is VideoBlock;
export declare function isSocialIcons(block: Block): block is SocialIconsBlock;
export declare function isSpacer(block: Block): block is SpacerBlock;
export declare function isHtml(block: Block): block is HtmlBlock;
export declare function isMenu(block: Block): block is MenuBlock;
export declare function isTable(block: Block): block is TableBlock;
export declare function isCountdown(block: Block): block is CountdownBlock;
export declare function isCustomBlock(block: Block): block is CustomBlock;
export declare function isSlot(block: Block): block is SlotBlock;
export declare function isWrapper(block: Block): block is WrapperBlock;
//#endregion
//#region src/custom-blocks.d.ts
type CustomBlockFieldType = "text" | "textarea" | "image" | "color" | "number" | "select" | "boolean" | "repeatable";
interface CustomBlockFieldBase {
  key: string;
  label: string;
  required?: boolean;
  placeholder?: string;
  readOnly?: boolean;
}
interface CustomBlockTextField extends CustomBlockFieldBase {
  type: "text";
  default?: string;
}
interface CustomBlockTextareaField extends CustomBlockFieldBase {
  type: "textarea";
  default?: string;
}
interface CustomBlockImageField extends CustomBlockFieldBase {
  type: "image";
  default?: string;
}
/**
 * A color-picker field. Beyond the shared field props it accepts the same flat
 * `presets` / `allowCustom` pair as the editor-wide `colors` config (their
 * shapes are derived from `ColorsConfig`, so the two can't drift), scoping this
 * one field to a color *role* — e.g. a button-color field offering only the
 * brand's accent/ink pair while other color fields inherit the global palette.
 *
 * **Narrowing only — of the author's freedom, not the palette.** A field can
 * restrict what authors may do (lock this field, or give it its own `presets`),
 * but never unlock what the editor locked. Its `presets` *replace* the
 * editor-wide grid rather than intersecting it, so a locked field may offer
 * colors outside `colors.presets`:
 *
 * - `presets` — entries are validated exactly like editor-level presets
 *   (`#rgb` / `#rrggbb` hex; invalid ones are skipped with a console warning
 *   naming the block and field). A non-empty valid list replaces the editor's
 *   palette for this field; leaving it unset, passing `[]`, or passing only
 *   invalid entries all inherit the editor's palette.
 * - `allowCustom` — `false` locks this field to its palette even while the rest
 *   of the editor allows free-form entry. `true` cannot unlock a field when the
 *   editor-wide `colors.allowCustom` is `false`; it is ignored with a warning.
 *
 * @see https://docs.templatical.com/guide/custom-blocks
 */
interface CustomBlockColorField extends CustomBlockFieldBase, Pick<ColorsConfig, "presets" | "allowCustom"> {
  type: "color";
  default?: string;
}
interface CustomBlockNumberField extends CustomBlockFieldBase {
  type: "number";
  default?: number;
  min?: number;
  max?: number;
  step?: number;
}
interface SelectOption {
  label: string;
  value: string;
}
interface CustomBlockSelectField extends CustomBlockFieldBase {
  type: "select";
  options: SelectOption[];
  default?: string;
}
interface CustomBlockBooleanField extends CustomBlockFieldBase {
  type: "boolean";
  default?: boolean;
}
interface CustomBlockRepeatableField extends CustomBlockFieldBase {
  type: "repeatable";
  fields: Exclude<CustomBlockField, CustomBlockRepeatableField>[];
  default?: Record<string, unknown>[];
  minItems?: number;
  maxItems?: number;
}
type CustomBlockField = CustomBlockTextField | CustomBlockTextareaField | CustomBlockImageField | CustomBlockColorField | CustomBlockNumberField | CustomBlockSelectField | CustomBlockBooleanField | CustomBlockRepeatableField;
interface CustomBlockDefinition {
  type: string;
  name: string;
  icon?: string;
  description?: string;
  fields: CustomBlockField[];
  template: string;
  dataSource?: DataSourceConfig;
  /**
   * Default block styles applied when a new instance of this custom block is
   * created. Deep-merged over the built-in defaults — only specify the fields
   * you want to override. Controls both the editor canvas wrapper and the
   * rendered MJML/email output.
   *
   * @example
   * defaultStyles: {
   *   padding: { top: 0, right: 0, bottom: 0, left: 0 },
   * }
   */
  defaultStyles?: Partial<BlockStyles>;
  /**
   * Optional CSS rules attached to this custom block definition. Emitted once
   * (deduped across instances) into `<mj-head><mj-style>…</mj-style></mj-head>`
   * in the rendered MJML, and adopted into the editor canvas (shadow root or
   * light-DOM mount) so authored responsive/hover/font behavior previews
   * inside the editor.
   *
   * Use this for media queries, hover states, or any CSS that should apply
   * once per definition rather than per block instance. Class names are not
   * scoped by the SDK — namespace them yourself (e.g. `.tplc-<type>-<el>`) to
   * avoid collisions with other definitions or built-in editor styles.
   *
   * @example
   * stylesheet: `
   *   @media (max-width: 480px) {
   *     .tplc-image-text-cell { display: block !important; width: 100% !important; }
   *   }
   * `
   */
  stylesheet?: string;
}
interface DataSourceFetchContext {
  fieldValues: Record<string, unknown>;
  blockId: string;
}
interface DataSourceConfig {
  label: string;
  onFetch: (context: DataSourceFetchContext) => Promise<Record<string, unknown> | null>;
}
//#endregion
//#region src/factory.d.ts
export declare function generateId(): string;
export declare function createTitleBlock(partial?: Partial<TitleBlock>): TitleBlock;
export declare function createParagraphBlock(partial?: Partial<ParagraphBlock>): ParagraphBlock;
export declare function createImageBlock(partial?: Partial<ImageBlock>): ImageBlock;
export declare function createButtonBlock(partial?: Partial<ButtonBlock>): ButtonBlock;
export declare function createDividerBlock(partial?: Partial<DividerBlock>): DividerBlock;
export declare function createSectionBlock(partial?: Partial<SectionBlock>): SectionBlock;
export declare function createVideoBlock(partial?: Partial<VideoBlock>): VideoBlock;
export declare function createSocialIconsBlock(partial?: Partial<SocialIconsBlock>): SocialIconsBlock;
export declare function createSpacerBlock(partial?: Partial<SpacerBlock>): SpacerBlock;
export declare function createHtmlBlock(partial?: Partial<HtmlBlock>): HtmlBlock;
export declare function createMenuBlock(partial?: Partial<MenuBlock>): MenuBlock;
export declare function createTableBlock(partial?: Partial<TableBlock>): TableBlock;
export declare function createCountdownBlock(partial?: Partial<CountdownBlock>): CountdownBlock;
export declare function createCustomBlock(definition: CustomBlockDefinition): CustomBlock;
/** Layout-only. Use this to build a layout; createBlock("slot") throws. */
export declare function createSlotBlock(): SlotBlock;
/** Layout-only. Use this to build a layout; createBlock("wrapper") throws. */
export declare function createWrapperBlock(partial?: Partial<WrapperBlock>): WrapperBlock;
export declare function createBlock(type: BlockType, blockDefaults?: BlockDefaults): Block;
export declare function cloneBlock(block: Block): Block;
//#endregion
//#region src/layout.d.ts
/** Throw if `layout` does not contain exactly one legal slot. */
export declare function validateLayout(layout: TemplateContent): void;
export declare function assertNoSlotInContent(content: TemplateContent): void;
export declare function assertNoWrapperInContent(content: TemplateContent): void;
/** True iff the one slot is a direct child of a wrapper (the card). */
export declare function layoutWrapsSlot(layout: TemplateContent): boolean;
/**
 * Overlay `layout` around `content`. Clones both; remints layout ids.
 * Layout wins only `settings.backgroundColor`.
 */
export declare function applyLayout(layout: TemplateContent, content: TemplateContent): TemplateContent;
//#endregion
//#region src/events.d.ts
export declare class EventEmitter<TEvents extends Record<string, unknown> = Record<string, unknown>> {
  private handlers;
  on<K extends keyof TEvents>(event: K, handler: (data: TEvents[K]) => void): () => void;
  off<K extends keyof TEvents>(event: K, handler: (data: TEvents[K]) => void): void;
  emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void;
  removeAllListeners(event?: keyof TEvents): void;
  listenerCount(event: keyof TEvents): number;
}
//#endregion
//#region src/clone.d.ts
/**
 * Cycle-safe deep clone via a JSON round-trip.
 *
 * A naked `JSON.stringify` throws `Converting circular structure to JSON`
 * if the tree is self-referencing — e.g. a DOM element carrying a Sortable
 * expando back-ref (`HTMLDivElement.SortableXXX -> instance -> el -> div`)
 * leaks into block data through a drag handler inside a section. Both the
 * editor's public `getContent()` export path and the history snapshot path
 * must tolerate that: we drop the offending back-ref from the clone rather
 * than throw. Losing a transient DOM expando is harmless; the block data is
 * intact.
 *
 * The replacer tracks the ancestors of the value it is serializing and omits
 * only a reference back to one of them, which is what every cycle is. An
 * object reached by two paths is not a cycle and is copied into each place:
 * content can legitimately share one, e.g. content built by hand that puts one
 * array into two blocks, and dropping the second visit would lose that block's
 * data from `getContent()` and undo.
 */
export declare function safeClone<T>(value: T): T;
//#endregion
//#region src/html-scan.d.ts
/**
 * Minimal, allocation-free primitives for reading an HTML open tag out of a
 * markup string. They exist because merge-tag markup is rewritten from a raw
 * string in two packages — `@templatical/types` (label / sample resolution for
 * the previews) and `@templatical/renderer` (converting spans back to tokens on
 * export) — and both need the same two answers: where does this open tag end,
 * and what is the value of one of its attributes.
 *
 * Both are hand-written character scans rather than regexes. A regex over an
 * attribute string with no closing quote backtracks across the whole input,
 * which is the ReDoS class the span scanners were rewritten to avoid; a scan
 * that only moves forward cannot.
 */
/**
 * Index of the `>` that closes the open tag whose name ends at `from`, or `-1`
 * when the tag never closes.
 *
 * Quote-aware: a `>` inside a quoted attribute value does not end the tag.
 * That matters because a consumer may configure a merge-tag syntax whose tag
 * values contain `<` / `>` — Smarty-style `<% $email %>` — and HTML attribute
 * serialization escapes only `&`, `"` and U+00A0, so those characters reach the
 * markup literally. A plain `indexOf(">")` stops mid-attribute there and every
 * caller downstream sees a truncated attribute string.
 *
 * An unterminated quote yields `-1` rather than a guessed tag end: callers
 * treat that as "not markup I can rewrite" and emit the input untouched, which
 * is the safe answer for malformed HTML.
 */
export declare function findOpenTagEnd(html: string, from: number): number;
/**
 * The value of the `name` attribute within an open tag's attribute string (the
 * text between the tag name and its closing `>`), or `null` when the attribute
 * is absent or its quoted value is never closed.
 *
 * Handles double-quoted, single-quoted and unquoted values, and matches the
 * attribute name case-insensitively, as HTML does. The value is
 * entity-decoded, because that is what the attribute means: the editor
 * serializes a tag value of `<% $email %>` as
 * `data-merge-tag="&lt;% $email %&gt;"`, and every caller compares the result
 * against a configured merge-tag token written in raw characters.
 */
export declare function getTagAttrValue(attrs: string, name: string): string | null;
//#endregion
//#region src/fonts.d.ts
/**
 * Font-stack primitives shared by the renderer, the editor's font selects and
 * every importer, so all of them read a CSS `font-family` value the same way.
 *
 * A value is a comma-separated list of families, each either quoted
 * (`'Times New Roman'`, `"Helvetica Neue"`) or a run of identifiers
 * (`Helvetica Neue`, `sans-serif`). The split is a forward character scan, not
 * a regex: a quoted family may contain a comma (`"Foo, Bar"`), and an
 * unterminated quote must fail fast rather than backtrack.
 */
interface FontFamily {
  /** The family name, quotes removed and backslash escapes resolved. */
  name: string;
  /**
   * Whether the source quoted it. Quoting matters for generic keywords:
   * unquoted `serif` is the generic family, quoted `'serif'` names a font.
   */
  quoted: boolean;
}
/**
 * The built-in web-safe families, keyed by lowercased name, and the stack the
 * renderer emits for each.
 */
export declare const BUILT_IN_FONT_STACKS: Readonly<Record<string, string>>;
/**
 * The families in a `font-family` value, or `[]` when it sets no font. That
 * covers blank, a CSS-wide keyword, and any list a browser would reject (an
 * empty entry, a CSS-wide keyword among other families, an unterminated
 * quote), because a browser drops an invalid declaration and renders no font
 * from it. A trailing `!important` is ignored.
 */
export declare function parseFontFamilies(value: unknown): FontFamily[];
/** `name` as a single-quoted CSS string. */
export declare function quoteFontFamily(name: string): string;
/** Families back into a `font-family` value, quoted ones in single quotes. */
export declare function formatFontFamilies(families: readonly FontFamily[]): string;
/** An unquoted generic family keyword such as `sans-serif` or `system-ui`. */
export declare function isGenericFontFamily(family: FontFamily): boolean;
/**
 * `value` re-serialised: single-quoted names, `", "` separators, no
 * `!important`. `""` when it sets no font. Never contains `"`, so it can sit
 * inside a double-quoted `style` attribute.
 */
export declare function normalizeFontStack(value: unknown): string;
/** The first family's name, unquoted; `""` when `value` sets no font. */
export declare function firstFontFamily(value: unknown): string;
/**
 * How an importer stores a font: `value` normalised, except that a built-in
 * stated alone, or as exactly the stack the renderer emits for it
 * (`Arial, sans-serif`), becomes the built-in's bare name. That collapse is
 * lossless under any render config, because the renderer re-expands a
 * built-in from its fixed table. Every other stack is kept, so its fallbacks
 * survive. `""` when `value` sets no font.
 */
export declare function canonicalFontStack(value: unknown): string;
//#endregion
//#region src/preview-resolution.d.ts
/**
 * Context handed to `resolvePreview`.
 *
 * `recipient` is present only on surfaces that have one — the test-email
 * dialog — and absent in the editor's own preview mode. Treat its absence as
 * "no particular recipient", not as an error: a resolver should still return
 * something renderable, typically its own default or sample data.
 */
interface PreviewResolveContext {
  /**
   * The template as it currently stands. Already a copy — mutating it has no
   * effect on the editor, and returning it unchanged is a valid no-op.
   */
  content: TemplateContent;
  /** The address the preview is being shown for, when the surface has one. */
  recipient?: string;
}
/**
 * Resolves a template for display on preview surfaces — typically substituting
 * merge tags and **evaluating logic tags** against real data.
 *
 * Logic tags are the reason this hook exists. `MergeTag.sample` already covers
 * value tags client-side, but branching (`{% if %}` … `{% endif %}`) cannot be
 * evaluated in a browser for every supported syntax — mailchimp and ampscript
 * logic are server-side dialects — so only the consumer's own backend can do it.
 *
 * Display-only. The returned content reaches preview surfaces and nothing else:
 * it is never written to the editor's state, never returned from
 * `getContent()`, never sent, and never exported. Rejecting is safe — the
 * preview falls back to the unresolved template and says so.
 */
type ResolvePreview = (context: PreviewResolveContext) => Promise<TemplateContent>;
/**
 * Whether `value` is shaped enough like `TemplateContent` to render.
 *
 * A resolver is consumer code returning data that often came from an HTTP
 * response, so the declared return type guarantees nothing at runtime. A
 * mis-shaped result is treated as a resolution failure — the preview degrades
 * to the unresolved template — rather than throwing inside the render.
 */
export declare function isRenderableTemplateContent(value: unknown): value is TemplateContent;
//#endregion
//#region src/cloud.d.ts
/**
 * Cloud's HTTP row for one version — what the API returns, not the BYO
 * {@link TemplateVersion} contract. `createCloudVersionHistoryProvider`
 * copies the fields the contract uses (`id`, `createdAt`, `isAutomatic`,
 * `content`) and drops `templateId`.
 */
interface TemplateVersionResponse {
  id: string;
  templateId?: string;
  content: TemplateContent;
  isAutomatic: boolean;
  createdAt: string;
}
/**
 * Cloud's HTTP row for one comment — what the API returns, not the BYO
 * {@link Comment} contract. Same field names as `Comment`, plus optional
 * `templateId`. `createCloudCommentsProvider` omits `updatedAt` when it
 * equals `createdAt` (Cloud stamps both on insert) so the panel does not
 * mark every comment "(edited)".
 */
interface CommentResponse {
  id: string;
  templateId?: string;
  blockId: string | null;
  parentId: string | null;
  body: string;
  author: CommentAuthor;
  resolvedAt: string | null;
  resolvedBy: CommentAuthor | null;
  createdAt: string;
  updatedAt: string;
  replies: CommentResponse[];
}
type FindingSeverity = "high" | "medium" | "low";
type ScoringCategory = "spam" | "readability" | "accessibility" | "bestPractices";
interface ScoringFinding {
  id: string;
  severity: FindingSeverity;
  message: string;
  blockId: string | null;
  category: ScoringCategory;
  suggestion: string;
}
interface CategoryScore {
  score: number;
  findings: ScoringFinding[];
}
interface ScoringResult {
  score: number;
  categories: Record<ScoringCategory, CategoryScore>;
}
interface HealthCheckResult {
  api: {
    ok: boolean;
    latency: number;
  };
  websocket: {
    ok: boolean;
    error?: string;
  };
  auth: {
    ok: boolean;
    error?: string;
  };
  overall: boolean;
}
interface TokenData {
  token: string;
  expiresAt: number;
  projectId: string;
  tenant: string;
  testEmail?: {
    allowedEmails: string[];
    signature: string;
  };
  user?: {
    id: string;
    name: string;
    signature: string;
  };
}
interface AuthRequestOptions {
  method?: "GET" | "POST";
  headers?: Record<string, string>;
  body?: Record<string, unknown>;
  credentials?: RequestCredentials;
}
interface AuthConfig {
  url: string;
  baseUrl?: string;
  requestOptions?: AuthRequestOptions;
  onError?: (error: Error) => void;
}
interface TestEmailConfig {
  allowedEmails: string[];
  signature: string;
}
interface UserConfig {
  id: string;
  name: string;
  signature: string;
}
interface DirectAuthConfig {
  mode: "direct";
  clientId: string;
  clientSecret: string;
  tenant: string;
  baseUrl?: string;
}
interface ProxyAuthConfig {
  mode: "proxy";
  url: string;
  baseUrl?: string;
  requestOptions?: AuthRequestOptions;
}
type SdkAuthConfig = DirectAuthConfig | ProxyAuthConfig;
interface Collaborator {
  id: string;
  name: string;
  color: string;
  selectedBlockId: string | null;
}
type TemplateOperation = "addBlock" | "updateBlock" | "deleteBlock" | "moveBlock" | "updateSettings" | "setContent" | "updateBlockStyle";
interface TemplateOperationPayload {
  operation: TemplateOperation;
  data: Record<string, unknown>;
  timestamp: number;
}
interface AiConfig {
  chat?: boolean;
  scoring?: boolean;
  designToTemplate?: boolean;
  rewrite?: boolean;
}
interface McpConfig {
  enabled: boolean;
  onOperation?: (payload: TemplateOperationPayload) => void;
}
interface CollaborationConfig {
  enabled: boolean;
  onCollaboratorJoined?: (collaborator: Collaborator) => void;
  onCollaboratorLeft?: (collaborator: Collaborator) => void;
  onBlockLocked?: (event: {
    blockId: string;
    collaborator: Collaborator;
  }) => void;
  onBlockUnlocked?: (event: {
    blockId: string;
    collaborator: Collaborator;
  }) => void;
}
interface WebSocketServerConfig {
  host: string;
  port: number;
  appKey: string;
}
interface ApiResponse<T> {
  data: T;
}
interface ApiError {
  message: string;
  errors?: Record<string, string[]>;
}
/**
 * Cloud's entitlement flags — the one thing in the SDK that is deliberately
 * **not** an interface a consumer could implement. Everything else is a
 * provider; this is Cloud's commercial layer sitting above the provider set,
 * which is exactly where the OSS/commercial line is drawn.
 *
 * **A flag is legitimate only when it meters a resource Cloud itself buys.**
 * Four kinds of gate do not belong here, however tempting:
 *
 * - Editor *capability* the OSS build grants free — fonts, theming, custom
 *   blocks, autosave. Gating it leaves a paying customer worse off than a free
 *   one.
 * - Declining to use a Cloud service — a consumer's own media storage, for
 *   instance. Charging for the *absence* of a Cloud cost is backwards, which is
 *   why the media tier is limits-only.
 * - Anything a browser flag cannot enforce: HTML output belongs to the server
 *   render, MJML export is unenforceable because `@templatical/renderer` is MIT
 *   (whoever holds the JSON holds the MJML), and headless access is a
 *   server-side auth question.
 * - Anything config already decides — `branding: false` hides the footer on any
 *   plan without an entitlement's help.
 *
 * Quantity limits are the honest lever — see {@link PlanLimits}.
 */
interface PlanFeatures {
  /** Inference spend, per call. */
  aiGeneration: boolean;
  /** Realtime connection capacity. */
  collaboration: boolean;
  /** Storage plus realtime fan-out. */
  commenting: boolean;
  /** Storage for saved blocks. */
  savedModules: boolean;
  /** Sending cost and deliverability reputation. */
  testEmail: boolean;
}
interface PlanLimits {
  maxFileSizeMb: number;
  maxTemplates: number | null;
  mediaCategories: string[];
  storageLimitBytes: number;
}
/**
 * Cloud JWT/plan wire shape for one media category — what the plan payload
 * carries, not a BYO contract field.
 */
interface MediaCategoryData {
  mimeTypes: string[];
  extensions: string[];
}
/**
 * Cloud JWT/plan wire shape for media entitlements — what the plan payload
 * carries, not the BYO {@link MediaProvider} contract.
 */
interface MediaConfig {
  useMediaLibrary: boolean;
  categories: Record<string, MediaCategoryData>;
  maxFileSize: number;
}
/**
 * Cloud JWT/plan wire shape for storage quota — what the plan payload
 * carries. Same fields as {@link MediaStorageInfo}.
 */
interface StorageInfo {
  usedBytes: number;
  limitBytes: number;
}
interface PlanConfig {
  features: PlanFeatures;
  limits: PlanLimits;
  templateCount: number;
  plan: string;
  media: MediaConfig;
  storage: StorageInfo;
  websocket: WebSocketServerConfig;
  accessibility?: {
    blockOnError?: boolean;
  };
}
interface AiChatMessage {
  id: string;
  role: "user" | "assistant";
  content: string;
  timestamp: number;
}
interface CreateCommentData {
  body: string;
  blockId?: string;
  parentId?: string;
  authorIdentifier: string;
  authorName: string;
}
interface UpdateCommentData {
  body: string;
}
interface AiGenerateOptions {
  conversationId?: string;
}
interface AiStreamEvent {
  type: "text" | "done" | "error";
  text?: string;
  content?: TemplateContent;
  conversationId?: string;
  error?: string;
}
interface RewriteData {
  text: string;
  instruction: string;
  blockId: string;
}
interface AiScoreOptions {
  fixFindingId?: string;
}
//#endregion
export type { AiChatMessage, AiConfig, AiGenerateOptions, AiScoreOptions, AiStreamEvent, ApiError, ApiResponse, AuthConfig, AuthRequestOptions, BaseBlock, Block, BlockDefaults, BlockStyles, BlockType, BlockVisibility, BorderCorner, BorderRadiusValue, BorderSide, BorderSideValue, BorderStyle, BorderValue, ButtonBlock, CategoryScore, CollaborationConfig, Collaborator, ColorsConfig, ColumnLayout, Comment, CommentAuthor, CommentChange, CommentEventMeta, CommentInput, CommentPatch, CommentResponse, CommentsListParams, CommentsOptions, CommentsProvider, ContentDirection, CornerRadius, CountdownBlock, CreateCommentData, CustomBlock, CustomBlockBooleanField, CustomBlockColorField, CustomBlockDefinition, CustomBlockField, CustomBlockFieldBase, CustomBlockFieldType, CustomBlockImageField, CustomBlockNumberField, CustomBlockRepeatableField, CustomBlockSelectField, CustomBlockTextField, CustomBlockTextareaField, CustomFont, DataSourceConfig, DataSourceFetchContext, DirectAuthConfig, DisplayCondition, DisplayConditionsConfig, DividerBlock, DividerPercentWidth, EditorUser, ExportResult, FindingSeverity, FontFamily, FontsConfig, HeadingLevel, HealthCheckResult, HtmlBlock, ImageBlock, LogicPair, LogicTag, LogicTagsConfig, McpConfig, MediaAsset, MediaAssetPatch, MediaCategory, MediaCategoryData, MediaConfig, MediaCreateInput, MediaFolder, MediaFolderInput, MediaFoldersProvider, MediaListPage, MediaListParams, MediaOptions, MediaProvider, MediaRequestContext, MediaResult, MediaStorageInfo, MediaUsageInfo, MenuBlock, MenuItemData, MergeTag, MergeTagRequestContext, MergeTagsConfig, ParagraphBlock, PlanConfig, PlanFeatures, PlanLimits, PreviewResolveContext, ProxyAuthConfig, RenderPayload, RenderProvider, ResolvePreview, RewriteData, SavedBlock, SavedBlockInput, SavedBlockPatch, SavedBlocksListParams, SavedBlocksOptions, SavedBlocksProvider, ScoringCategory, ScoringFinding, ScoringResult, SdkAuthConfig, SectionBlock, SectionWrapper, SelectOption, SlotBlock, SocialIcon, SocialIconGlyph, SocialIconSize, SocialIconStyle, SocialIconTone, SocialIconsBlock, SocialPlatform, SpacerBlock, SpacingValue, StorageInfo, SyntaxPreset, SyntaxPresetName, TableBlock, TableCellData, TableRowData, Template, TemplateContent, TemplateDefaults, TemplateOperation, TemplateOperationPayload, TemplatePatch, TemplateSaveTrigger, TemplateSettings, TemplateSettingsConfig, TemplateVersion, TemplateVersionResponse, TemplatesOptions, TemplatesProvider, TestEmailConfig, TestEmailOptions, TestEmailPayload, TestEmailProvider, ThemeOverrides, TitleBlock, TokenData, UiTheme, UpdateCommentData, UserConfig, VersionHistoryListParams, VersionHistoryListResult, VersionHistoryOptions, VersionHistoryProvider, VideoBlock, ViewportSize, WebSocketServerConfig, WrapperBlock };
//# sourceMappingURL=index.d.ts.map