Skip to content

@plenary/core

@plenary/core is the framework-agnostic contract the rest of the SDK is built on. It defines the shape of a Page Builder document, how a component describes its props to the console, the responsive style model and its CSS compiler, the postMessage protocol between the console and a live preview, and the rules for which console origins may drive a preview. It has zero dependencies.

Most sites import only types from it, such as PlenaryDocument and PropDefinition; @plenary/react calls the runtime functions for you. Use the functions directly when you build a renderer for a framework other than React.

Terminal window
npm install @plenary/core

The package ships ESM and CommonJS builds with type declarations. Current version: 1.0.x.

Export Kind Purpose
PlenaryNode, PlenaryDocument types The stored page document
PropFieldType, PropDefinition, SlotDefinition, StylePanel, ComponentRegistration types How a component describes itself to the console
ThemeToken, ThemeRegistration types Design tokens and breakpoint cutoffs
Breakpoint, BreakpointCutoffs, NodeStyles types The responsive style model
BREAKPOINTS, STYLE_PROP_FOR_BREAKPOINT, DEFAULT_CUTOFFS constants The responsive style model
readNodeStyles, effectiveStyle, resolveCutoffs, compileNodeCss functions Read, cascade, and compile node styles
isAllowedEditorOrigin, hasWildcardPattern functions Editor-origin matching for the preview bridge
PROTOCOL_VERSION, DND_NEW constants Preview protocol
PlenaryMessage, ManifestComponent, CanvasDropTarget, every *Payload and *Message type, IframeToConsoleMessage, ConsoleToIframeMessage, PlenaryProtocolMessage, PlenaryMessagePayloads, PlenaryMessageType types Preview protocol

A blocks field on a content entry stores a PlenaryDocument: a tree of PlenaryNodes. You receive it as entry.data.<fieldKey> from the Content API.

interface PlenaryNode {
/** Stable id minted by the console; survives reorders. The SDK never generates ids. */
id: string;
/** Registered component key: "box", "section", "hero", ... */
component: string;
/** Builder-only display name from the block tree. The renderer ignores it. */
label?: string;
/** Prop values as plain JSON. */
props: Record<string, unknown>;
/** Named child regions. The default slot is "children"; Section keys its columns "0", "1", ... */
slots?: Record<string, PlenaryNode[]>;
}
interface PlenaryDocument {
version: 1;
/** Top-level nodes. */
root: PlenaryNode[];
}

Three prop keys are reserved for editor styles on every node: style, styleTablet, and styleMobile. See Responsive styles.

An example document, as the Content API returns it:

{
"version": 1,
"root": [
{
"id": "3f0c2b9e-6a51-4d0e-9a57-1f4f0f3a2c11",
"component": "hero",
"props": {
"heading": "Ship pages faster",
"style": { "paddingTop": "64px" },
"styleMobile": { "paddingTop": "32px" }
}
},
{
"id": "8d2e4c1a-0b7f-4e44-8f61-2b9f3c5d7e80",
"component": "section",
"props": { "columns": 2, "gap": 16 },
"slots": {
"0": [{ "id": "c0", "component": "box", "props": {}, "slots": { "children": [] } }],
"1": [{ "id": "c1", "component": "box", "props": {}, "slots": { "children": [] } }]
}
}
]
}

These types describe a component to the console: its palette entry, its editable props, its slots, and which Style-tab panels it supports. You pass a ComponentRegistration to register in @plenary/react.

interface ComponentRegistration {
key: string;
label: string;
icon?: string;
props?: PropDefinition[];
slots?: SlotDefinition[];
category?: string;
styles?: StylePanel[];
}
Field Required Description
key yes The component key stored in PlenaryNode.component ("hero"). Must be unique across the site. Changing it orphans existing nodes.
label yes Name shown in the palette and block tree ("Hero").
icon no Palette glyph: an image URL, a data URI, or inline SVG markup (<svg ...>...</svg>). Inline SVG is converted to a data URI. Rendered small and monochrome, so a single-color icon reads best.
props no The editable props. See PropDefinition.
slots no Fixed named child regions. See SlotDefinition.
category no Palette group. Custom components appear under Custom · {category}.
styles no Style-tab panels offered for this component. Omitted or empty means no style controls. See StylePanel.
interface PropDefinition {
key: string;
type: PropFieldType;
required?: boolean;
defaultValue?: unknown;
fields?: PropDefinition[];
settings?: Record<string, unknown>;
ui?: Record<string, unknown>;
visibleWhen?: { prop: string; equals: unknown };
}
Field Description
key The prop name. The value is stored at node.props[key] and passed to your component as a prop of the same name.
type One of PropFieldType. Picks the console input and the stored value shape.
required Marks the input as required in the console.
defaultValue Seeded into a new node’s props when an editor adds the block. The renderer never merges defaults into stored props, so give your component its own fallback too.
fields Declared in the type, but the console does not read it. Declare a list’s sub-fields under settings.item_settings.fields instead (see below).
settings The field type’s settings, in the same shape a content model field uses: select options, a list’s item_type and item_settings, a reference’s target model. See Field types.
ui The field type’s UI settings: label, help_text, placeholder, control, and type-specific keys such as media_type. Without ui.label, the console labels the input from the key (buttonUrl becomes “Button Url”).
visibleWhen Shows the input only while the sibling prop prop strictly equals equals. An untouched sibling is compared by its defaultValue. The prop still exists on the node and still reaches the component.

Prop settings worth knowing:

Prop type Settings shape Stored value
select settings: { options: [{ value: "left", label: "Left" }] } the option’s value string
multi_select same options shape array of value strings
list of objects settings: { item_type: "object", sortable: true, item_settings: { fields: [{ key, name, type }] } } array of objects
list of scalars settings: { item_type: "text" } array of scalars
reference settings: { model: "author" } (the model key; add multiple: true for many) { "reference_id": "..." } or { "reference_ids": ["..."] }, not hydrated
image / file ui: { media_type: "video", show_alt_caption: false } (both optional) { "media_id": "...", "alt": "...", "caption": "..." } (alt and caption optional)
type PropFieldType =
| "text" | "rich_text" | "number" | "boolean"
| "date" | "time" | "datetime" | "json"
| "image" | "file" | "reference"
| "email" | "url" | "select" | "multi_select"
| "list" | "tags";

Every content field type except object, computed, blocks, and phone. A rich_text prop stores an HTML string.

interface SlotDefinition {
/** "header", "body"; "children" for the single default slot. */
name: string;
label?: string;
}

A slot is a named region editors can drop other blocks into. Slots are fixed per component: you cannot add or remove slots per node (the built-in Section’s columns are the one exception). Any component may be dropped into any slot.

type StylePanel = "layout" | "size" | "background" | "typography" | "css";
Value Style-tab panels the console shows
layout Layout (display, direction, justify, align, gap, wrap)
size Sizing, Padding, Margin
background Appearance (background, opacity, overflow, radius) and Border
typography Typography
css CSS Properties (free-form properties for the active breakpoint)

You do not need component code for styles to apply. The renderer compiles editor styles into a stylesheet that targets the component’s root element. Declaring a panel is a promise that your component renders a single root element those styles can land on.

interface ThemeToken {
/** Custom property name without the leading "--" ("brand-primary"). */
name: string;
/** The resolved value, used only for the editor's swatch preview. */
value: string;
/** Picker label; defaults to the name. */
label?: string;
}
interface ThemeRegistration {
/** Offered by color, background, and border pickers. */
colors?: ThemeToken[];
/** Offered by the Typography panel's font picker. */
fonts?: ThemeToken[];
/** max-width cutoffs in px for the responsive layers. Defaults: tablet 1024, mobile 640. */
breakpoints?: { tablet?: number; mobile?: number };
}

When an editor picks a token, the console stores var(--<name>), not the value. Your stylesheet must define every token as a CSS custom property, or styled pages render without it. Register a theme with registerTheme from @plenary/react.

Editor styles live on each node as three flat, camelCase style records:

Breakpoint Node prop Applies at
base style all widths
tablet styleTablet max-width: 1024px by default
mobile styleMobile max-width: 640px by default

The model is desktop-first. Tablet overrides base per property, and mobile overrides both.

type Breakpoint = "base" | "tablet" | "mobile";
const BREAKPOINTS: readonly Breakpoint[]; // ["base", "tablet", "mobile"]
const STYLE_PROP_FOR_BREAKPOINT: Record<Breakpoint, string>;
// { base: "style", tablet: "styleTablet", mobile: "styleMobile" }
interface BreakpointCutoffs {
tablet: number;
mobile: number;
}
const DEFAULT_CUTOFFS: BreakpointCutoffs; // { tablet: 1024, mobile: 640 }
interface NodeStyles {
base?: Record<string, string>;
tablet?: Record<string, string>;
mobile?: Record<string, string>;
}
function readNodeStyles(props: Record<string, unknown>): NodeStyles;

Reads the three layers off a node’s props. A layer that is missing, an array, or not an object comes back undefined.

function effectiveStyle(styles: NodeStyles, breakpoint: Breakpoint): Record<string, string>;

Returns the cascaded style at a breakpoint: base, overlaid by tablet (at tablet and mobile), then by mobile (at mobile only).

function resolveCutoffs(theme: ThemeRegistration | undefined): BreakpointCutoffs;

Returns the theme’s cutoffs, falling back to DEFAULT_CUTOFFS for any value that is not a positive finite number. Fractional values are floored.

function compileNodeCss(id: string, styles: NodeStyles, cutoffs?: BreakpointCutoffs): string;

Compiles one node’s layers into CSS that targets the renderer’s wrapper element, [data-plenary-id="<id>"] > *. It emits a base rule, then one @media (max-width: <cutoff>px) block per override layer. Every declaration is !important, so editor styles outrank the component’s own inline styles and site CSS. It returns "" when nothing survives. cutoffs defaults to DEFAULT_CUTOFFS.

import { compileNodeCss, readNodeStyles } from "@plenary/core";
const css = compileNodeCss(
"n1",
readNodeStyles({ style: { paddingTop: "64px" }, styleMobile: { paddingTop: "32px" } }),
);
// [data-plenary-id="n1"] > * { padding-top: 64px !important; }
// @media (max-width: 640px) { [data-plenary-id="n1"] > * { padding-top: 32px !important; } }

The compiler sanitizes as it goes, which makes the output safe to inject into a <style> element:

  • Keys are converted from camelCase to kebab-case. --custom properties pass through. A key that is not a valid property name is dropped.
  • A value containing {, }, \, /*, </style, or a control character is dropped whole. Non-string values are dropped.
  • The node id is escaped for the attribute selector.

The preview bridge only obeys messages from console origins you list. These functions implement the matching rules.

function isAllowedEditorOrigin(patterns: readonly string[], origin: string): boolean;

Returns true when origin (for example a MessageEvent.origin) matches any pattern. Malformed patterns and origins match nothing.

Pattern form Example Matches
Exact origin https://cms.example.com that origin only
Subdomain wildcard https://*.example.com https://a.example.com and https://a.b.example.com; never the bare https://example.com
Port wildcard http://localhost:* http://localhost on any port, including none

Rules:

  • The scheme is always literal. An https:// pattern never matches an http:// origin.
  • *. is only valid as the leftmost host label. A bare * host is not supported.
  • A pattern without a port matches only the scheme’s default port. An explicit port must match exactly.
  • Matching is case-insensitive.
import { isAllowedEditorOrigin } from "@plenary/core";
isAllowedEditorOrigin(["https://*.plenarycms.io"], "https://acme.plenarycms.io"); // true
isAllowedEditorOrigin(["https://*.plenarycms.io"], "https://plenarycms.io"); // false
isAllowedEditorOrigin(["http://localhost:*"], "http://localhost:5173"); // true
isAllowedEditorOrigin(["https://cms.example.com"], "https://cms.example.com:8443"); // false
function hasWildcardPattern(patterns: readonly string[]): boolean;

Returns true when any pattern contains *. A wildcard pattern cannot be a postMessage target, so the bridge uses this to decide whether to also send its hello with target "*".

The console and a site’s preview bridge talk over window.postMessage. These types are that contract. You need them only to build a bridge for a framework other than React; PlenaryBridge in @plenary/react implements it for you. The Live Preview guide explains the flow.

const PROTOCOL_VERSION = 1;
const DND_NEW = "application/x-plenary-new";

PROTOCOL_VERSION is announced in the hello handshake. If the console and the site disagree, the console shows “The site is on a different preview protocol version; live editing is unavailable.” and falls back to reloading the frame after each save. DND_NEW is the drag data-transfer type for a palette drag. It matters only when the preview is served from the console’s own origin.

interface PlenaryMessage<TType extends string, TPayload> {
plenary: true;
v: number;
type: TType;
payload: TPayload;
}

Every message carries plenary: true so both sides can ignore unrelated postMessage traffic. v is the sender’s PROTOCOL_VERSION.

Union type: IframeToConsoleMessage.

type Payload type Payload Sent when
hello HelloPayload { protocolVersion: number; sdkVersion: string } The bridge mounts inside a frame
manifest ManifestPayload { components: ManifestComponent[]; theme?: ThemeRegistration } Right after init
select SelectPayload { nodeId: string } A block is clicked in the preview
hover HoverPayload { nodeId: string | null } The pointer enters or leaves a block
canvasDrop CanvasDropPayload { component: string; target: CanvasDropTarget } A palette drag is dropped on the canvas
size SizePayload { height: number } The page’s content height changes
wheel WheelPayload { deltaY: number; x: number; y: number } Ctrl/Cmd + wheel over the page (zoom)
pan PanPayload { dx: number; dy: number } Middle-button drag over the page
key KeyPayload { key: string; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean } An editor shortcut is pressed inside the frame
edit EditPayload { nodeId: string; props: Record<string, unknown> } An inline text edit is committed

Union type: ConsoleToIframeMessage.

type Payload type Payload Purpose
init InitPayload { entryId: string; modelKey: string; editorOrigin: string } Activates the bridge
render RenderPayload { data: Record<string, unknown>; locale: string } The full draft field data to render
patch PatchPayload { nodeId: string; props: Record<string, unknown> } Merges props into one node. Reserved: the bridge handles it, but the console does not send it today
highlight HighlightPayload { selectedId: string | null; hoverId: string | null } Outlines the selected and hovered blocks
canvasDragOver CanvasDragPayload { x: number; y: number } A palette drag is over the canvas, in page CSS pixels
canvasDragLeave Record<string, never> {} The drag left the canvas
canvasDragDrop CanvasDragDropPayload { x: number; y: number; component: string } The drag was released; answer with canvasDrop
interface ManifestComponent {
/** The registration key. */
name: string;
label: string;
icon?: string;
props: PropDefinition[];
slots: SlotDefinition[];
category?: string;
styles?: StylePanel[];
}
type CanvasDropTarget =
| { at: "root" }
| { at: "before" | "after"; nodeId: string }
| { at: "slot"; nodeId: string; slot: string };

Each message also has a named alias, such as HelloMessage = PlenaryMessage<"hello", HelloPayload>. PlenaryProtocolMessage is the union of both directions. PlenaryMessagePayloads maps each type string to its payload type, and PlenaryMessageType is keyof PlenaryMessagePayloads. Together they give you a typed sender:

import { PROTOCOL_VERSION, type PlenaryMessagePayloads, type PlenaryMessageType } from "@plenary/core";
export function send<T extends PlenaryMessageType>(
type: T,
payload: PlenaryMessagePayloads[T],
targetOrigin: string,
): void {
window.parent.postMessage({ plenary: true, v: PROTOCOL_VERSION, type, payload }, targetOrigin);
}