CMS
Headless CMS on the data layer — content types declared in code, derived draft/published tables, the ctx.cms read surface, and the saveDraft → publish write pipeline with save-time validation + derivation.
@voltro/cms is a headless CMS built on the framework's own data layer. You
declare a content type once, in code; the package compiles it to two real
database tables (<type>_drafts + <type>_published) that auto-migrate picks
up, gives you a typed read surface, and a write pipeline that enforces the
schema's validation/derivation rules on every save.
The kernel runs on every SQL dialect the framework supports — sqlite, postgres, mysql, mariadb and mssql: all of its tables apply, and drafts, locale variants, immutable revisions, approvals, scheduled publishing, releases and the typed published reads behave the same on each. Its identity and scope columns (content type, document, site, environment, locale) hold at most 64 characters, so their composite keys fit every engine's index limit.
Two entry points keep the browser/server boundary clean:
@voltro/cms— the server entry: table derivation (@voltro/database), the write pipeline, signed preview tokens (node:crypto), the REST mount.@voltro/cms/web— browser-safe: the field DSL, the validation/derivation engine + its typed errors (effect-only), and the<ContentForm>renderer (react-only). An editor page pre-validates with the SAME rules the server applies; a mutation descriptor can declareerror: ContentValidationFailedwithout dragging the server graph into the bundle.
Declaring a content type
By convention each content type lives in a *.contentType.ts file. The field
DSL is a plain-data descriptor language — validation rules travel as data and
are applied at save time.
import { defineContentType, Schema, derivedFrom, slugify } from '@voltro/cms'
export const blogPost = defineContentType({
name: 'blogPost',
displayName: 'Blog Post',
pluralName: 'Blog Posts',
fields: {
title: Schema.String.pipe(Schema.maxLength(200)),
slug: Schema.String.pipe(Schema.pattern(/^[a-z0-9-]+$/), Schema.unique(), derivedFrom('title', slugify)),
body: Schema.RichText({ images: 'asset', links: 'blogPost' }),
tags: Schema.Array(Schema.String),
publishedAt: Schema.DateTime.optional(),
coverImage: Schema.Media().optional(),
author: Schema.Reference('author'),
visibility: Schema.Literal('public', 'unlisted', 'private'),
},
list: { columns: ['title', 'updatedAt'], defaultSort: { field: 'updatedAt', dir: 'desc' } },
})maxLength/patternare enforced by the save-time validator (andmaxLengthalso caps the shipped text widget).derivedFrom(source, transform)marks a field computed-on-save: the pipeline computes it from its source and overwrites a caller-provided value —slugifyis the canonical transform: lowercase, accents folded to their letter, umlauts spelled out (Über uns→ueber-uns), everything else that is not a letter or digit becomes a hyphen.unique()marks a string field unique per tenant and scope — the derived tables get a real composite(tenantId, site, environment, locale, field)DB UNIQUE constraint (the database rejects a duplicate slug within one tenant and scope, not the app). Pair it withderivedFrom('title', slugify)for a unique slug.Schema.RichText(options?)stores a rich document: paragraph, heading, list, table and image blocks with inline marks and links (see Rich text).images/linksname the content types an image block and a link reference; leave one out to refuse that node.Schema.Media()stores a storage object key as text (e.g. one issued by@voltro/plugin-storage); resolve it to a URL after a read withresolveMedia(below).Schema.Numberis a whole number (an integer column). A fractional value is refused at save time with the ruleinteger.Schema.Fractiontakes a fractional part (arealcolumn, and a number input withstep="any"), for example a focal point's0.25..requiredToPublish()lets a draft be saved without the field and refuses to publish until it is set (absent,nulland a blank string count as empty). The column is nullable, as with.optional(). Every publish path checks it: a single publish, a release (the whole release is refused) and a bulk run (the item is planned asincomplete). The error isContentValidationFailedwith the rulerequiredToPublish;publishViolations(type, values)lists the empty fields without writing, so an editor can say so first. Use it for what arrives before someone describes it, such as an image's alt text after a bulk upload.listdescribes the consuming editor's list view; every referenced name is validated at definition time.- Reserved field names (
defineContentTypethrows):id,status,publishAt,revisionId,revision,documentId,site,environment,locale,tenantId,createdAt,updatedAt,createdBy,updatedBy.
contentTypeToEntities(blogPost) returns the { draft, published } tables —
register them in your database/index.ts so auto-migrate creates them, together
with the shared cmsRevisionsTable and cmsReferencesTable:
import { cmsReferencesTable, cmsRevisionsTable, contentTypeToEntities } from '@voltro/cms'
const blog = contentTypeToEntities(blogPost)
export const database = databaseHandle({
tenants,
blogPostDrafts: blog.draft,
blogPostPublished: blog.published,
cmsRevisions: cmsRevisionsTable,
cmsReferences: cmsReferencesTable,
})Both content tables carry the lifecycle status column (draft / published
/ archived), the revision they show (revisionId, revision), the tenant()
mixin (tenant-scoped reads/writes through the request store), and are reactive
(the default) so a publish wakes live subscriptions.
Rich text
A Schema.RichText() value is a RichDocument, the CMS's own document model.
It is never HTML and never an editor's internal format:
const body: RichDocument = {
type: 'doc',
blocks: [
{ id: 'rb_1', type: 'heading', level: 2, content: [{ type: 'text', text: 'Raised beds' }] },
{ id: 'rb_2', type: 'paragraph', content: [
{ type: 'text', text: 'Plant ' },
{ type: 'text', text: 'early', marks: ['bold'] },
{ type: 'link', target: 'cdoc_plan', text: 'see the plan' },
] },
{ id: 'rb_3', type: 'list', ordered: false, items: [[{ type: 'text', text: 'Tomatoes' }]] },
{ id: 'rb_4', type: 'table', header: true, rows: [[[{ type: 'text', text: 'Bed' }]], [[{ type: 'text', text: '1' }]]] },
{ id: 'rb_5', type: 'image', asset: 'cdoc_photo', caption: 'Tomatoes' },
],
}- Every block has a stable
id. A save gives a new block one and keeps the existing ones. - A plain string is saved as paragraphs, one per blank-line-separated run. JSON in another shape (a TipTap document, HTML) is refused.
- A
linkpoints at a document by itsdocumentId, and animageblock points at an asset document. Both are references, so they are recorded as edges on publish,cms.usedByfinds them, and the site resolves their current address or file when it renders. - A list nests:
levelsgives each item its depth (0 at the top, at mostMAX_LIST_LEVEL= 3, and at most one deeper than the item before); absent, every item is at the top. The editor nests an item by two spaces of indent;RichDocumentViewrenders a deeper item as a list inside the item before it; an HTML import turns a list inside a list item into levels. - Each depth has its kind:
sublistsholds it for the lists one, two and three levels in ('ordered'/'unordered'; absent or shorter: numbered like the list itself), so numbered steps can sit under bullets.listNumberedAt(block, depth)answers it; the editor has a "Numbered at level n" box per depth the list reaches; HTML and Contentful imports keep the kind of the first list met at a depth, and a Contentful list inside a list item nests as it does in HTML. richDocumentProblems,normalizeRichDocument,richDocumentReferencesandplainTextOfare the pure helpers behind this.
The editor types inline text in a small markup that is parsed into the document
on every change: **bold**, _italic_, ++underline++ and [text](doc:<documentId>). A
backslash escapes a marker (inlineMarkupOf escapes every +). parseInlineMarkup and inlineMarkupOf convert
between the two. The markup is only input, and the stored value is always the
document.
Render a document with RichDocumentView from /web. It produces React
elements only, so stored text never becomes markup. A link without an address
renders as its text, and images appear only through your renderer:
import { RichDocumentView } from '@voltro/cms/web'
<RichDocumentView
document={page.body}
hrefOf={(documentId) => links[documentId]}
renderImage={({ asset, caption }) => <Figure image={images[asset]} caption={caption} />}
/>Importing HTML
Content from another system arrives as HTML. richDocumentFromHtml translates what the rich document can hold — paragraphs (also WordPress-style blank-line paragraphs), headings (h1/h2 → level 2, h3–h6 → level 3), lists, tables, bold, italic, underline (<u>) and links to your own documents — and reports everything else instead of carrying it:
import { richDocumentFromHtml } from '@voltro/cms'
const { document, findings } = richDocumentFromHtml(post.contentHtml, {
// An address on the old site that is now one of your documents → a link node.
resolveLink: (href) => importedByUrl.get(href) ?? null,
})
// document: { type: 'doc', blocks: [...] } — store it in a RichText field
// findings: [{ kind: 'externalLink' | 'image' | 'unsupportedTag', detail }] — show them for review- A link that
resolveLinkdoes not map keeps its text and is reported asexternalLink(the rich document links documents, not URLs). - An image is reported as
imagewith its source — unlessresolveImage(src)returns the asset document the import brought it in as: then it becomes an image block, its alt text the caption. script,style,iframe, forms and the like are dropped with their content and reported; any other unknown tag keeps its text and is reported. Character references are decoded. Nothing is executed, loaded or kept as markup.
A Contentful rich-text document goes the same way through richDocumentFromContentful: paragraphs, headings, lists, tables, bold and italic, entry links and embedded assets the import resolved become nodes; a URL hyperlink keeps its text (externalLink), and an embedded entry, a quote or anything else keeps its text and is reported.
import { richDocumentFromContentful } from '@voltro/cms'
const { document, findings } = richDocumentFromContentful(entry.fields.body['en-US'], {
resolveEntry: (id) => documentOfEntry.get(id) ?? null, // entry-hyperlink → link node
resolveAsset: (id) => documentOfAsset.get(id) ?? null, // embedded-asset-block → image block
})Components
A page is often a list of blocks rather than one body. defineComponent
declares a block — a stable camelCase id, a displayName for the editor and
typed props built from the same field DSL — and Schema.Components([...])
declares a field that holds an ordered list of them:
import { defineComponent, defineContentType, Schema } from '@voltro/cms'
export const hero = defineComponent({
id: 'hero',
displayName: 'Hero',
props: {
heading: Schema.String.pipe(Schema.maxLength(120)),
intro: Schema.String.optional(),
},
})
export const textBlock = defineComponent({ id: 'textBlock', displayName: 'Text block', props: { text: Schema.String } })
export const page = defineContentType({
name: 'page', displayName: 'Page', pluralName: 'Pages',
fields: {
title: Schema.String,
sections: Schema.Components([hero, textBlock]).optional(),
},
})- The field is stored as JSON: each placed component is
{ instanceId, componentId, fingerprint, props }. - On save, a placement without an
instanceIdgets a stable one (cins_…); an existing id is kept, so moving a block keeps its identity. Every placement is stamped with the definition's currentfingerprint. - The
fingerprintis derived from the prop contract (names, kinds, rules), not from the display name — renaming a component in the editor does not change it, adding or changing a prop does. - Validation runs per placement: an unknown
componentId, a duplicateinstanceId, an undeclared prop and every prop rule are reported with a path such assections[1].props.heading. - A component may be listed once per field;
defineComponentrejects an id that is not camelCase.
Rendering is the site's job: map each componentId to a renderer and skip one
you have no renderer for.
Components that need consent
A component that loads a third party, such as a video or a map, declares the
consent purpose a reader must grant first. gateConsent is the delivery gate
for it. A banner alone is not.
import { gateConsent, grantedPurposes, type ConsentPurpose } from '@voltro/cms'
const video = defineComponent({
id: 'video',
displayName: 'Video',
props: { title: Schema.String, url: Schema.String },
consent: 'externalMedia',
})
const purposes: ReadonlyArray<ConsentPurpose> = [
{ id: 'externalMedia', version: 1, displayName: 'External media', description: 'Videos from other services.' },
]
// choices: what the reader stored, purpose id → the version they allowed
const granted = grantedPurposes(purposes, choices)
const safe = gateConsent(page, row, granted)- Until the purpose is granted,
gateConsentreplaces each such component with{ instanceId, componentId, consentRequired, props: {} }. None of its props reach the reader, so the page has no URL to load. Render a placeholder that names the purpose. - Purposes are versioned.
grantedPurposes(purposes, choices)counts a choice only for the purpose's current version, so raising the version asks every reader again. - Apply it wherever content leaves for a reader, on the server. The reader's
choices are theirs to send; the gate protects them, it is not an access
control.
purposesUsedBy(type)lists the purposes a type's components need, for a banner to ask about. gateConsent,grantedPurposesandpurposesUsedByare also exported from@voltro/cms/web.
Page templates
A content type can offer templates: a starting layout of components plus rules that a document built from one keeps. The document stores the template's id, and every save checks that template's rules. The editor, the API, an import and a bulk action therefore meet the same guarantees.
import { templateValues } from '@voltro/cms'
const landing = {
id: 'landing',
displayName: 'Landing page',
values: { layout: 'landing' },
sections: [{ component: hero, props: { heading: 'Welcome' } }, { component: textBlock }, { component: callToAction }],
required: [hero, callToAction],
first: hero,
max: [{ component: callToAction, count: 1 }],
}
const page = defineContentType({
name: 'page', displayName: 'Page', pluralName: 'Pages',
fields: {
title: Schema.String,
layout: Schema.Literal('default', 'landing'),
template: Schema.String.optional(),
sections: Schema.Components([hero, textBlock, callToAction]).optional(),
},
templates: { field: 'template', components: 'sections', list: [landing] },
})
const start = templateValues(page, 'landing') // { template, layout, sections }templateValues(type, id)returns the values a new document starts with: the template id,valuesand thesectionsas components. The save stamps each component's instance id. It returnsnullfor an unknown template.- Rules:
requiredcomponents must appear at least once,firstmust come first, andmaxlimits how many of one component there may be. A broken rule failssaveDraftwithContentValidationFailedon the components field. The rule isrequired,positionormax, and the message names the template and the component. An unknown template id fails withunknownon the template field. - A document without a template id has none of these rules.
templateViolations(type, row)returns the violations without saving, andtemplateOf(type, row)returns the template a row names. defineContentTypethrows whenfieldis not an optional string field,componentsis not aSchema.Componentsfield, an id repeats, or a template uses a component the field does not allow.templateValues,templateOfandtemplateViolationsare also exported from@voltro/cms/web.
Page tree and routes
Declare tree on a content type to arrange its documents under each other.
parent names an optional Schema.Reference to the same type, order an
optional number field that orders siblings, and segment the string field
that forms the path:
import { defineContentType, Schema, derivedFrom, slugify } from '@voltro/cms'
export const page = defineContentType({
name: 'page', displayName: 'Page', pluralName: 'Pages',
fields: {
title: Schema.String,
slug: Schema.String.pipe(Schema.unique(), derivedFrom('title', slugify)),
parent: Schema.Reference('page').optional(),
position: Schema.Number.optional(),
},
tree: { parent: 'parent', order: 'position', segment: 'slug' },
})- A reference holds the target's
documentId, so it points at the document, not at one locale variant. - The parent is an ordinary field: it is versioned and goes live with the page's publish, including inside a release. Moving a page changes its public path when the move is published.
saveDraftrefuses a parent that is the page itself or one of its descendants (rulecycle) and one that does not exist (ruleunknown).defineContentTypethrows when the parent is not an optional reference to the same type, the segment is not a string field or the order is not a number field.
Read the tree through ctx.cms:
const cms = cmsContext(ctx.store, contentTypes, { scope })
const tree = await cms.tree('page', { fallback: ['en-GB'] })
const match = await cms.route('page', 'garden/beds', { fallback: ['en-GB'] })tree(type, { fallback, filter })returns{ nodes, orphans }.nodesholds one node per published document, depth-first with siblings in order. Each node carriesdocumentId,parent,depth,segments,path, the publishedrow, itslocaleandfallback. The variant comes from the surface's locale, else from the firstfallbacklocale that has one.orphanslists documents whose chain never reaches the root, because a parent is not published in any accepted locale or the parents form a cycle. Orphans are not routable and are never hung under the root.route(type, path, options)returns{ node, tree }ornull. A path that exists only in a fallback locale's tree answers with the requested locale's node of the same document. Comparenode.pathwith the requested path and redirect to the canonical address.- Both read every published row of the type in the accepted locales. Resolve a
typed link by finding the target's
documentIdin the same tree. When the target is missing from the tree, it is not live in this locale, so render its text without a link. buildTree(entries, config)is the pure builder behind both. It is also exported from@voltro/cms/web, together with the node types.
Inherited fields
A header, a footer or another binding can be set once on a branch of the tree
and apply to every page below it. tree.inherit names optional fields that
a page takes from the nearest ancestor that sets them.
import { inheritedValue } from '@voltro/cms'
const page = defineContentType({
name: 'page', displayName: 'Page', pluralName: 'Pages',
fields: {
title: Schema.String,
slug: Schema.String.pipe(Schema.unique(), derivedFrom('title', slugify)),
parent: Schema.Reference('page').optional(),
header: Schema.Reference('header').optional(),
footer: Schema.Reference('footer').optional(),
},
tree: { parent: 'parent', segment: 'slug', inherit: { header: {}, footer: { locked: true } } },
})
const match = await cms.route('page', 'campaign/offer')
if (match !== null) {
const header = inheritedValue(match.tree, match.node, 'header') // { value, from }
const reset = inheritedValue(match.tree, match.node, 'header', { ancestorsOnly: true })
}inheritedValue(tree, node, field)returns{ value, from }.fromis the document that set the value: the page itself, an ancestor, ornullwhen none does. Fall back to a site-wide default fornull.{ ancestorsOnly: true }skips the page's own value. It shows what the page inherits once its own value is cleared ("reset to inherited"). Clearing the field on the page is the reset.locked: truemeans no page may set the field.saveDraftrefuses a value with the rulelocked, so only the app's site-wide default applies. Use it for content that must not be replaced page by page, like a legal footer.- Inherited fields must be declared optional. It reads the same tree, so it
follows the locale and fallback that tree was built with. Also exported from
@voltro/cms/web.
Agent tools along the page tree
Which WebMCP tools an agent in a reader's browser may use on a page can follow the page tree: the app declares every tool it has (the ceiling) and which are on by default; each page may turn tools on or off for itself and every page below it, or lock them off so nothing below can turn them on again. effectiveExposure (pure, also in /web) resolves one page from the chain root → page:
import { effectiveExposure } from '@voltro/cms/web'
const { tools, explained } = effectiveExposure({
ceiling: ['searchSite', 'openPage', 'fillContactForm'], // what the app has; content cannot add to it
defaults: ['searchSite', 'openPage', 'fillContactForm'], // on unless the tree says otherwise
// Root → page: the legal branch turns openPage off and locks the contact form off.
chain: [{ off: ['openPage'], locked: ['fillContactForm'] }, { on: ['openPage', 'fillContactForm'] }],
})
// tools: ['searchSite', 'openPage'] — the lock holds below the branch
// explained: [{ tool: 'fillContactForm', state: 'locked', decidedAt: 0 }, …]- A tool outside the ceiling is never on, whatever the content says. A step's
on/off/lockedis a list of tool names; anything else counts as unset, so rows can be passed as they are. - Within a step,
lockedapplies first, thenoff, thenon. A locked tool stays locked for every page below. explainednames, per tool, the step that decided it (null: the default) — for an editor showing where a setting comes from.
Sitemap and language alternates
A CMS translates the slug, not just a prefix: /p/garden is /de/p/garten.
A page's alternates therefore come from each language's tree, matched by
document.
import { alternatesOf, sitemapUrls, sitemapXml } from '@voltro/cms'
const trees = await Promise.all(['en-GB', 'de-DE'].map(async (locale) => ({
locale,
tree: await cmsContext(ctx.store, contentTypes, { scope: { ...scope, locale } })
.tree('page', { fallback: fallbackChain[locale] }),
})))
const alternates = alternatesOf(trees, documentId) // [{ locale, path }, …]
const urls = sitemapUrls(trees, (node) => node.row['audience'] !== 'members')
const xml = sitemapXml(urls, (locale, path) => `${siteUrl}${prefixOf(locale)}/p/${path}`, 'en-GB')- Build each language's tree the way the site routes, with the reader's fallback. A page counts in a language only where it has its own variant, never through a fallback, and at the address the site serves it under.
alternatesOf(trees, documentId)returns{ locale, path }for every language the document has its own variant in. Turn them intohreflanglinks and a canonical URL in the page's meta.sitemapUrls(trees, include)lists every such page with itslastmod(the variant'supdatedAt) and alternates.includeleaves pages out, for example members-only ones, in every language.sitemapXml(urls, href, xDefault)renders the document with absolute URLs fromhref(locale, path), reciprocalxhtml:linkalternates and anx-defaultfor the named language. Serve it from a REST route withbytes(...). All three are pure and also exported from@voltro/cms/web.
Redirects when a page moves
A published page keeps answering at its old address after it moves. That
covers a changed slug, a new parent, and an ancestor that moved. Every
publish of a tree type records each document's current path per site,
environment and locale in cms_paths. When a path changed, the old one is
stored in cms_redirects, pointing at the document.
const match = await cms.route('page', 'garden/beds', { filter: { tenantId } })
if (match?.via === 'redirect') {
// A former address: redirect permanently (308) to match.node.path.
}viasays how the path was found:path(the page's own address),fallback(another locale's address of it) orredirect(an address it had before it moved).routechecks live pages first, in the requested locale and then alongfallback. Only a path no live page has falls back tocms_redirects. A live page at a former address always wins.- A redirect names the document, not a path. A page that moves twice sends both old addresses straight to its current one, and moving back does not create a loop.
- Paths change only when a change is published. Saving a draft moves nothing.
- Pass the tenant in
filter, as for every other public read. The redirect lookup applies itstenantId. listRedirects(store, type, scope)lists a scope's redirects.redirectTarget(store, type, path, scope, tenantId?)resolves a single one. RegistercmsPathsTableandcmsRedirectsTablein the app's schema next tocmsRevisionsTable.
An address that never was a path here — a page's address on the site it was imported from, a vanity path — is added with addRedirect. It points at the document, replaces an earlier redirect from the same path, and yields to a live page at that path:
import { runProvidedEffect } from '@voltro/runtime'
import { addRedirect } from '@voltro/cms'
// In a mutation: the page's address on the old site answers with the page.
await runProvidedEffect(addRedirect(ctx.store, page, scope, '/about/volunteer/', documentId, tenantId))A type outside a tree can have an address of its own — a blog post's slug. Declare it with address: '<string field>': every publish records each document's address in cms_paths, and a changed one leaves a redirect to the document, as moving a page does. cms.route is for trees; read a post's former address with redirectTarget, and hadAddress tells a post that was taken down (answer 410) from one that never was:
import { runProvidedEffect } from '@voltro/runtime'
import { Schema, defineContentType, derivedFrom, redirectTarget, slugify } from '@voltro/cms'
export const blogPost = defineContentType({
name: 'blogPost', displayName: 'Blog post', pluralName: 'Blog posts',
fields: { title: Schema.String, slug: Schema.String.pipe(Schema.unique(), derivedFrom('title', slugify)) },
address: 'slug',
})
// The site's post route: an old slug answers with the post at its address now.
const documentId = await runProvidedEffect(redirectTarget(ctx.store, 'blogPost', slug, scope, tenantId))Gone addresses. A page that is taken down or archived keeps its last address in cms_paths, and a redirect still names it. cms.gone(type, path, options) is true when no live page answers path (route finds nothing) but a published page had it — its own address or a former one — in the requested locale or along fallback. A site answers such a path with 410 Gone instead of 404 (gone() in a loader, ContentGone from an action), so search engines drop it. Published again, the page answers again.
import { runProvidedEffect } from '@voltro/runtime'
import { ContentGone, removeRedirect } from '@voltro/cms'
// No live page at the path: was it one that is no longer live?
if (match === null && (await cms.gone('page', path, { filter: { tenantId } }))) {
throw new ContentGone({ contentType: 'page', path }) // answer 410, not 404
}
// In a mutation: the address leads nowhere again (true when there was a redirect).
await runProvidedEffect(removeRedirect(ctx.store, page, scope, '/about/volunteer/'))removeRedirect(tx, type, scope, fromPath) deletes the redirect from that address. A page that had the address and is no longer live still makes it gone; any other address answers 404 again. hadAddress(store, type, path, scope, tenantId?) is the lookup gone runs per locale.
Reference edges and "used by"
Publishing records what the published variant references, in the shared
cms_references table. Every declared Schema.Reference counts, including
references inside Schema.Array, Schema.Struct and component props. Each edge
carries the source (type, document, variant, site, environment, locale), the
path where the reference sits (for example sections[2].props.image) and the
target document.
- Edges change in the same transaction as the content. A publish replaces the variant's edges, and an unpublish or archive removes them. A release publishes through the same path, so its entries update the edges too.
- A draft that references a document is not a use. Only live content counts.
cms.usedBy(type, documentId)lists the live uses of a document in the surface's site and environment, across locales.usedBy(store, target, scope)is the same read without a surface.referencesOf(type, values)returns the references a set of values makes, derived from the declared fields and never from a JSON scan.
const uses = await cms.usedBy('asset', photo.documentId)
// [{ sourceType: 'page', sourceDocumentId, sourceVariantId, locale: 'en-GB', path: 'sections[0].props.image' }]Content published before an app registered cmsReferencesTable has no edges
until it is published again.
Scope — site, environment, locale
Besides its tenant, every content row lives in a CmsScope: the site it
belongs to, the content environment (production, staging, …) and its
locale. The three axes are stored on every draft, published row and revision,
and every write and read takes the scope explicitly — never from a filter the
caller happens to pass:
import type { CmsScope } from '@voltro/cms'
// apps/api/content/scope.ts — server-side, one place.
export const cmsScope = (locale = 'en-GB'): CmsScope => ({
site: 'main',
environment: 'production',
locale,
})A row in another site, environment or locale reads as absent, exactly like
another tenant's row, and a caller-pinned id is never moved across scopes
(ContentIdConflict). A Schema.unique() field is unique per tenant and
scope, so the same slug can exist once per site, environment and locale. A
multi-site app derives the site from the request (its host, say) and the
environment from its deployment; the examples below assume a scope value
built this way.
Revisions
Every successful saveDraft appends one immutable row to cms_revisions: the
validated values, the content type, the document, the variant's scope and a
number per variant, starting at 1. The draft row points at the newest revision; a
published row points at exactly the revision that went live, so a later edit
never changes what readers see until the next publish. A save that fails
validation writes nothing.
import { runProvidedEffect } from '@voltro/runtime'
import { listRevisions, publish } from '@voltro/cms'
const history = await runProvidedEffect(listRevisions(ctx.store, blogPost, draft.documentId as string, scope)) // newest first
// Publish only the revision the editor reviewed; a newer save in between
// throws RevisionMismatch and nothing goes live.
await runProvidedEffect(publish(ctx.store, blogPost, draft.id as string, scope, { revisionId: reviewed.revisionId }))Revisions are never updated or deleted. Rows saved before revisions existed
show revision 0 and get revision 1 on their next save.
Two editors on one draft do not overwrite each other silently. Pass the
revision the editor saw, and a save that lands after someone else's throws
RevisionMismatch without writing anything:
import { runProvidedEffect } from '@voltro/runtime'
import { changedFields, restoreRevision, saveDraft } from '@voltro/cms'
await runProvidedEffect(saveDraft(ctx.store, blogPost, values, scope, { expectedRevision: seen.revisionId }))
// Bring an earlier revision back. It becomes the newest revision, so the
// history only grows. A field the old revision did not have is cleared.
await runProvidedEffect(restoreRevision(ctx.store, blogPost, draft.id as string, scope, earlier.id as string))
// Which fields differ between two revisions (browser-safe, also in /web).
changedFields(blogPost.fields, older.values, newer.values) // ['title', 'body']restoreRevision validates the old values against today's rules. It throws
ContentValidationFailed when they no longer pass, and ContentNotFound
(stage revision) for a revision of another document or scope.
restoreRevision is an Effect: yield* it in Effect.gen, or run it with runProvidedEffect.
Typing together
Two editors can also write in the same field at the same time, each keystroke
kept. openDraftTexts(store, type, draftId) gives each plain text field of a
draft a shared CRDT text in cms_draft_texts, started from the draft's value.
Register cmsDraftTextsTable beside the content tables. A field counts as plain
text when it is a text or textarea string the editor writes: not derived,
not unique, not a choice, not the template field and not rich text
(collaborativeFields(type) lists them). typeDraftText(store, textId, update)
merges one editor's edit, an encoded CRDT update, into the stored text. The
merge does not depend on order, so two edits made from the same text both
survive. Stream the table to the other editors and bind each field with
useCrdtText from @voltro/local-first/react.
import { runProvidedEffect } from '@voltro/runtime'
import { openDraftTexts, saveDraft, typeDraftText } from '@voltro/cms'
// When an editor opens the draft: one shared text per plain text field.
const texts = await runProvidedEffect(openDraftTexts(ctx.store, blogPost, draft.id as string))
// Each keystroke: an encoded CRDT update (useCrdtText pushes one).
await runProvidedEffect(typeDraftText(ctx.store, textId, update))
// The save takes those fields as the server merged them.
await runProvidedEffect(saveDraft(ctx.store, blogPost, values, scope, { expectedRevision: seen.revisionId, collaborative: true }))The shared text is never the content itself; a save materializes it. With
collaborative: true, saveDraft takes those fields from the merged texts
and ignores what the form sent for them. A draft that moved on since
expectedRevision only in those fields, or in a field derived from one of them
(a slug from its title), is no conflict, because both editors wrote those
changes together. movedTogether(type, fields) names that set. Pass the
editor's own states of the texts as texts ({ id, update }, each an encoded
CRDT update) and they are merged in before the save reads them, so an edit still
on its way to the server is part of the save rather than left behind. A change to any other field still throws
RevisionMismatch. Each text records the revision it belongs to, and a save
moves it to the new one. A draft that changed without the texts (a restore, an
import, a save without collaborative) leaves them behind: the next save does
not use them, and the next openDraftTexts starts them again from the draft as
new rows. A client still holding the old history then cannot merge into the
new text.
fieldDiffs(fields, before, after) says how each changed field changed: its
text before and after as a word diff, { field, segments } with segments of
same, removed and added text. A rich document compares by its text (one
line per block), a component list one line per component with its text props;
other structured values compare as compact JSON. diffWords(before, after) is
the diff alone, and valueText(value) the text a value is compared as. Two
texts too long to compare word by word come back as one removed and one added
run. All three are pure and also exported from @voltro/cms/web.
import { fieldDiffs } from '@voltro/cms'
fieldDiffs(blogPost.fields, older.values, newer.values)
// [{ field: 'title', segments: [{ op: 'same', text: 'Raised beds from ' },
// { op: 'removed', text: 'oak' }, { op: 'added', text: 'larch' }] }]fieldVersions(revisions, field) lists the values one field held across a
document's revisions, newest first. It adds an entry wherever the value
changed. For an image asset's file that is the file history: a revision that
only fixed the alt text adds no version. Each entry names the revision that
introduced the value. Bringing an older value back is a new save, so it
becomes a new revision rather than an overwrite. It is pure and also exported
from @voltro/cms/web.
import { runProvidedEffect } from '@voltro/runtime'
import { fieldVersions, listRevisions } from '@voltro/cms'
const revisions = await runProvidedEffect(listRevisions(ctx.store, asset, documentId, scope))
const files = fieldVersions(revisions, 'file')
// [{ value: 'file_b', revisionId, number: 4, createdAt, createdBy }, { value: 'file_a', … }]Locale variants and fallback
A document is the stable content identity (documentId); each locale of it
is a variant — its own row with its own id, revisions and publish state.
A document has at most one variant per site, environment and locale.
import { runProvidedEffect } from '@voltro/runtime'
import { cmsContext, saveDraft } from '@voltro/cms'
// A new document: its first variant, in the scope's locale.
const en = await runProvidedEffect(saveDraft(ctx.store, blogPost, input, scope))
// Its German variant: same documentId, no id, the German scope.
const de = await runProvidedEffect(saveDraft(ctx.store, blogPost, { documentId: en.documentId, title: 'Hallo' }, { ...scope, locale: 'de-DE' }))
// Reading in German, falling back to English at read time:
const cms = cmsContext(ctx.store, [blogPost], { scope: { ...scope, locale: 'de-DE' } })
const entry = await cms.resolve('blogPost', { key: { field: 'slug', value: slug }, fallback: ['en-GB'] })
// entry: { row, locale, requestedLocale, fallback } — or nullsaveDraft with a documentId and no id creates the variant; a second
variant in the same locale is ContentIdConflict, and a document the caller
does not have is ContentNotFound. resolve looks the key up in the requested
locale first, then along fallback. A key found in a fallback locale whose
document has a variant in the requested locale answers with that variant (its
own slug — redirect to it); otherwise the fallback variant answers with
fallback: true. Nothing is copied into the requested locale: the fallback is
resolved on every read and reported, never stored. Rows that predate variants
become their own documents on migration (documentId = id).
Translation status
A translation can record the source-language revision it was written from, and
translationStatus compares that basis with the source's current draft:
import { runProvidedEffect } from '@voltro/runtime'
import { saveDraft, translationStatus } from '@voltro/cms'
// Write the German variant from the English revision the translator saw.
await runProvidedEffect(saveDraft(ctx.store, page, { documentId, title: 'Garten' }, deScope, { basedOn: english.revisionId }))
const status = await runProvidedEffect(translationStatus(ctx.store, page, documentId, scope, 'en-GB', ['de-DE', 'fr-FR']))
// status.targets → [{ locale: 'de-DE', state: 'outdated', changed: ['title'] }, { locale: 'fr-FR', state: 'missing' }]stateismissingwhen no variant exists andupToDatewhen the variant is based on the source's current revision. It isoutdatedwhen the variant is based on an older revision, withchangednaming the source fields edited since. It isunknownwhen the variant never said what it was based on.- The basis is stored on the revision (
cms_revisions.basedOn). An update that omitsbasedOnkeeps the previous revision's basis, so fixing a typo in a translation does not claim it caught up with its source. - For a list,
translationStatuses(store, type, documentIds, scope, source, targets)returns aMapfrom document id to status and reads them together — three reads per 500 documents instead of three per document.contentHealthuses it.
Translation exchange — XLIFF 2.1
A document's translatable text goes to a translator or a translation service as XLIFF 2.1, and comes back into a translation draft:
import { applyTranslation, parseXliff, toXliff, translationUnits, unitsHash } from '@voltro/cms'
const units = translationUnits(page.fields, source) // [{ id: 'title', source: 'Raised beds' }, …]
const xml = toXliff({ srcLang: 'en-GB', trgLang: 'de-DE', fileId: `page:${documentId}`,
notes: { 'voltro:source-hash': unitsHash(units) }, units })
// …translated elsewhere, then:
const back = parseXliff(returnedXml)
const values = applyTranslation(page.fields, source, back.units) // the German draft's valuesWhat is translated: plain text fields — not one with a pattern (a slug, an
address), not a derived or a choice field — every rich-text block's text in
the editor's inline markup (**bold**, _italic_, [text](doc:<id>), so a
link keeps its target), list items and table cells one unit each, image
captions, and the same inside placed components. Structure, references and
numbers come from the source unchanged; a unit without a target keeps the
source text. unitsHash fingerprints the source units, so an import can refuse
a file made from a source that has changed since; matchUnits counts what came
back translated, untranslated, unknown and missing.
parseXliff reads XLIFF 2.x with one <file> — namespace prefixes, CDATA,
character references, several segments per unit — and throws XliffInvalid
for a DOCTYPE or entity declaration, input over 5 MB, inline elements it does
not write (<ph>, <pc>), or a file that is not XLIFF 2. All of it is pure and
also exported from @voltro/cms/web.
Reading — ctx.cms
cmsContext(store, types, { scope }) builds the read surface over a
request-scoped store, confined to one scope; attach it to your AppContext and
read it with useCms(ctx). Reads target <type>_published and exclude
archived rows.
import { cmsContext, useCms } from '@voltro/cms'
const posts = await useCms(ctx)
.contentType('blogPost')
.where('publishedAt', '<=', new Date())
.orderBy('publishedAt', 'desc')
.limit(20)
.all()To walk every entry, page by id instead of by offset:
const first = await useCms(ctx).contentType('blogPost').page(20)
const next = first.next === null ? null : await useCms(ctx).contentType('blogPost').page(20, first.next)page(limit, after?) returns { items, next }: up to limit rows in id
order after the row whose id is after, and the id to pass for the following
page (null on the last). A row published or taken down between two requests
neither repeats nor skips another, which an offset cannot promise. It keeps
the query's where filters and replaces its orderBy, limit and offset.
createCmsClient({ store, types, scope }) is the same surface without a request
handle (build-time / static-site generation). Signed preview tokens
(previewToken / verifyPreviewToken / cms.preview) let an app read the
draft row instead — see the package README for the token contract and the
API-key-gated REST mount (handleCmsRest).
Writing — the pipeline
The lifecycle ops take the caller's store first. Hand them ctx.store and
every write rides the runtime's auto-scope spine: tenant + audit columns are
stamped, reads are tenant-scoped, ids come from the table's id scheme. Each op
is an Effect whose error channel is its typed failures — the one form of the
write API; yield* it in an Effect.gen handler. The same holds for every
other async function the package exports — review, releases, scheduling,
redirects, search, shares and the rest — so the samples below that await
one run it with runProvidedEffect. Only handleCmsRest, the HTTP edge,
returns a Promise.
import { Effect } from 'effect'
import { saveDraft, publish, unpublish, archive } from '@voltro/cms'
const program = Effect.gen(function* () {
// derive → validate → write into blogPost_drafts (status: 'draft')
const draft = yield* saveDraft(ctx.store, blogPost, input, scope)
// copy the draft into blogPost_published (same id), in the mutation's transaction
const row = yield* publish(ctx.store, blogPost, draft.id as string, scope)
yield* unpublish(ctx.store, blogPost, draft.id as string, scope) // remove the published copy, keep the draft
yield* archive(ctx.store, blogPost, draft.id as string, scope) // status 'archived' — reads exclude it
return row
}).pipe(
Effect.catchTag('ContentValidationFailed', (e) => Effect.succeed({ invalid: e.violations })),
)saveDraft applies the derivedFrom derivations first, then validates the
derived row — a rule on a derived field checks the value actually written.
Violations fail with ContentValidationFailed carrying every per-field
violation ({ field, rule, message }), so an editor can annotate the whole
form in one pass. Re-saving with row.id updates the caller's own draft;
publish copies into the published table (insert on first publish, update
after) and marks the draft in-sync.
The ops never open a transaction of their own — they run in the one they are
handed. A mutation's ctx.store already is one transaction, so the published
copy and the draft flip commit together with everything else the mutation
writes, or not at all. Stores refuse a nested transactional(), which is why a
pipeline that opened its own could not run inside a mutation. Outside a
mutation, wrap the call:
import { runProvidedEffect } from '@voltro/runtime'
await app.store.transactional((tx) => runProvidedEffect(publish(tx, blogPost, id, scope)))Tenant isolation is structural: a foreign id reads as absent through the
scoped store (ContentNotFound), a caller-pinned id that exists only in
another tenant is refused (ContentIdConflict), and a caller-provided
tenantId never reaches a write — the pipeline owns the lifecycle columns.
An async handler runs an op with runProvidedEffect (@voltro/runtime),
which rejects with the typed failure itself — not Effect's FiberFailure
wrapper — so instanceof works:
import { runProvidedEffect } from '@voltro/runtime'
import { ContentValidationFailed, saveDraft } from '@voltro/cms'
try {
await runProvidedEffect(saveDraft(ctx.store, blogPost, input, scope))
} catch (e) {
if (e instanceof ContentValidationFailed) return { invalid: e.violations }
throw e
}ISR revalidation on publish
A content type can declare which ISR routes fall when its content is
published or unpublished. revalidateContent(type) fires
revalidatePath / revalidateTag
for each entry, reaching every voltro start replica:
import { defineContentType, Schema } from '@voltro/cms'
const blogPost = defineContentType({
name: 'blogPost',
displayName: 'Blog post',
pluralName: 'Blog posts',
fields: {
title: Schema.String.pipe(Schema.maxLength(200)),
body: Schema.RichText({ images: 'asset', links: 'blogPost' }),
},
revalidate: {
paths: ['/blog/[slug]', '/blog'],
tags: ['blog'],
},
})A purge must follow the commit — a replica that re-renders on it has to read
the published row — and the write ops run inside a transaction they do not
commit, so they never fire it themselves. publishDue fires it after its own
commits. For a publish from a mutation, fire it from a post-commit subscriber on
the published table:
// apps/api/subscribers/blogPostPublished.subscribe.ts
import { defineSubscriber } from '@voltro/runtime'
import { revalidateContent } from '@voltro/cms'
import { blogPost } from '../content/blogPost.contentType'
export default defineSubscriber({
table: 'blogPost_published',
on: ['insert', 'update', 'delete'],
once: true, // one purge per change, not one per replica
handler: async () => { revalidateContent(blogPost) },
})You don't need this on postgres for the plain publish case: a route declaring
cacheInvalidatesOn: ['blogPost_published'] is already dropped by CDC when
the published table changes. Declare revalidate for what CDC can't see —
non-postgres dialects, routes whose loaders read the content indirectly, or
tag fanout across several routes.
The engine, standalone
The validation/derivation engine is pure and exported on its own (also on
/web) for custom write paths and client-side form validation:
import { validateContent, contentViolations, applyDerivations } from '@voltro/cms/web'
const derived = applyDerivations(blogPost, formValue) // derivedFrom fields computed
const violations = contentViolations(blogPost, derived) // pure — never throws
validateContent(blogPost, derived) // throws ContentValidationFailed on any violationPreview links
A preview link lets someone without an editor account see one draft until it
expires or you revoke it. Unlike a signed previewToken, a share is stored:
you can list it per document and revoke it at any time.
import { runProvidedEffect } from '@voltro/runtime'
import { createPreviewShare, listPreviewShares, resolvePreviewShare, revokePreviewShare } from '@voltro/cms'
// An editor shares a draft: the revision it has now, for a week.
const { share, token } = await runProvidedEffect(createPreviewShare(ctx.store, page, draft.id as string, scope, {
revision: 'pinned', // or 'latest': follows every save
expiresAt: new Date(Date.now() + 7 * 86_400_000),
label: 'For the print shop',
}))
const url = `https://example.com/share/${token}`
// A visitor opens the link. The token is the authorization.
const seen = await runProvidedEffect(resolvePreviewShare(ctx.store, token))
// { ok: true, revision, values, locale, contentType } | { ok: false, reason: 'unknown' | 'expired' | 'revoked' }
await runProvidedEffect(revokePreviewShare(ctx.store, share.id as string))- The token is 256 random bits. Only its SHA-256 hash is stored, so the table
never holds a usable link.
createPreviewShareis the only time the token exists in the clear. - The expiry is required, must lie in the future and at most
MAX_PREVIEW_SHARE_DAYS(30) ahead. Otherwise the call throwsPreviewShareRejected. - Creating, listing and revoking are tenant-scoped editor operations.
resolvePreviewShareis the one cross-tenant read, because a visitor has no tenant. Everything it reads is confined to the share's tenant and variant. unknownalso answers a token that never existed, so the result gives no hint for guessing.- Register
cmsPreviewSharesTablein yourdatabaseHandleto use shares. Serve the pagenoindex.
Review before publish
A content type can require that another editor approves a revision before it goes live:
import { runProvidedEffect } from '@voltro/runtime'
import { approveReview, defineContentType, requestChanges, requestReview, reviewStatus, Schema } from '@voltro/cms'
export const blogPost = defineContentType({
name: 'blogPost', displayName: 'Blog Post', pluralName: 'Blog Posts',
fields: { title: Schema.String },
review: { required: true },
})
await runProvidedEffect(requestReview(ctx.store, blogPost, draft.id as string, scope, { actorId: me }))
await runProvidedEffect(approveReview(ctx.store, blogPost, draft.id as string, scope, { revisionId: seen.revisionId, actorId: reviewer }))
// or: await runProvidedEffect(requestChanges(ctx.store, blogPost, draft.id as string, scope, { revisionId, actorId: reviewer, note: 'Add a date' }))
const status = await runProvidedEffect(reviewStatus(ctx.store, blogPost, draft.id as string, scope))
// { state: 'none' | 'inReview' | 'approved' | 'changesRequested', revisionId, stale, lastStep }An approval covers exactly one revision. A save after it shows a new revision nobody approved: the status turns
nonewithstale: true, and the reviewer'srevisionIdno longer matches (RevisionMismatch).The person who asked for review cannot approve it (
ReviewStepRefused, reasonselfApproval).allowSelfApproval: truelifts this for one call. Approving or requesting changes without an open request is refused with the reasonnotInReview.The gate sits in
publishRevision, so every path that publishes passes it:publish, releases, rollbacks and scheduled publishing. An unapproved revision throwsReviewRequired.publishDueskips such a row and keeps it scheduled until it is approved, without holding up the others.Review writes run inside the caller's transaction: use the mutation's
ctx.storeor a top-levelstore.transactionalcallback. A draft-row lock serializes decisions for the same variant. The persistedsequenceorders steps even when timestamps tie or replica clocks disagree; only one concurrent decision can consume an open request.Before starting updated writers, stop review writes on every replica and apply the declared schema with
voltro db apply. Existing review rows receivesequence = 0and retain their history. If the newest existing timestamps tie,reviewStatus,approveReviewandrequestChangesrefuse to guess their order (ReviewStepRefused, reasonambiguousOrder). IncludeReviewStepRefusedin explicitreviewStatusEffect error annotations and handleambiguousOrderin exhaustive reason checks. Start a new review withrequestReview; it begins a numbered round without rewriting previous steps. Resume writes only after every writer uses the updated schema and code.The review log in
cms_reviewsis append-only. An earlier approval still counts when a rollback brings its revision back.Register
cmsReviewsTablein yourdatabaseHandlewhen a type setsreview. Types without it are not affected.review: { required: 'workspace' }leaves it to each workspace: the type publishes freely until the workspace requires review for it —setReviewRequired(tx, tenantId, typeName, true), or a blueprint'steam.reviewRequired(applied before its entries).workspaceReviewTypeslists what a workspace requires andreviewRequiredFor(store, type, variantId)answers it for one variant; the gate uses the same answer. RegistercmsTeamTablefor such a type.
Quality rules and exceptions
A content type names what it checks: each rule the field that causes the finding, the words an editor reads, and whether publishing waits for it (blocking, the default). A blocking finding is repaired at its field — or an editor asks for an exception: one rule, one variant, a reason, and an end date at most MAX_EXCEPTION_DAYS (90) days out. Someone else approves or rejects it. Register cmsQualityExceptionsTable when a type declares rules.
import { runProvidedEffect } from '@voltro/runtime'
import { decideQualityException, defineContentType, qualityFindings, requestQualityException, Schema } from '@voltro/cms'
export const page = defineContentType({
name: 'page', displayName: 'Page', pluralName: 'Pages',
fields: { title: Schema.String, seoTitle: Schema.String.optional(), seoDescription: Schema.String.optional() },
quality: [
{ id: 'seo.titleLength', field: 'seoTitle', message: 'Longer than 60 characters: results cut it off.',
check: (values) => typeof values['seoTitle'] === 'string' && values['seoTitle'].length > 60 },
{ id: 'seo.description', field: 'seoDescription', message: 'No description for search engines.', blocking: false,
check: (values) => typeof values['seoDescription'] !== 'string' || values['seoDescription'] === '' },
],
})
const findings = qualityFindings(page, draftValues) // [{ ruleId, field, message, blocking }] — pure
const asked = await runProvidedEffect(requestQualityException(ctx.store, page, draftId, scope, {
ruleId: 'seo.titleLength', reason: 'Campaign title, agreed with marketing.', expiresAt, actorId,
}))
// { ok: true, id } | { ok: false, reason: 'unknownRule' | 'notBlocking' | 'noReason' | 'badExpiry' | 'alreadyOpen' }
if (asked.ok) await runProvidedEffect(decideQualityException(ctx.store, asked.id, { decision: 'approve', actorId: publisherId }))
// { ok: true, state } | { ok: false, reason: 'notFound' | 'notOpen' | 'selfApproval' | 'notRequester' }- Publishing checks the revision being published: a blocking finding without an approved, unexpired exception refuses it as
ContentValidationFailed, with a violation{ field, rule: 'quality.<id>', message }— so single publishes, releases, schedules and bulk runs all carry the same refusal. Advice (blocking: false) never blocks. - An exception holds for its rule on its variant only, until
expiresAt; after that its state readsexpiredand the finding blocks again. The requester cannot approve it (selfApproval);withdrawends an approved exception at once — or, by its requester, an open request. qualityExceptions(store, type, variantId, scope)lists the history with each state today (requested,approved,rejected,withdrawn,expired).- A rule id is letters, digits,
.or-, unique in the type; a rule naming an undeclared field fails at definition.
Vocabularies
A content type can hold one list-of-text field to a controlled vocabulary: every save folds case, spacing and width, maps each synonym to its term and drops repeats; a term the vocabulary does not know fails the save (ContentValidationFailed, rule taxonomy) — or is kept as typed with unknown: 'keep'. normalizeTerms is pure and also exported from @voltro/cms/web, so an editor can show the terms a save will store.
import { defineContentType, normalizeTerms, Schema } from '@voltro/cms'
export const asset = defineContentType({
name: 'asset', displayName: 'Image', pluralName: 'Images',
fields: { title: Schema.String, tags: Schema.Array(Schema.String).optional() },
taxonomy: {
field: 'tags',
terms: [{ term: 'raised beds', synonyms: ['raised bed', 'Hochbeet'] }, { term: 'vegetables', synonyms: ['veg'] }],
},
})
normalizeTerms(asset.taxonomy!, ['Hochbeet', ' Raised Bed ', 'VEG', 'Tomatoes'])
// { terms: ['raised beds', 'vegetables'], unknown: ['Tomatoes'] }- The field must be a declared
Schema.Array(Schema.String); a vocabulary without terms, or a spelling that means two terms, fails at definition.
Duplicate files
duplicateGroups groups the drafts of a type whose media field holds the same file — the same bytes uploaded twice, whatever their names. The fingerprint comes from the caller (for @voltro/plugin-storage: the stored object's SHA-256, StorageService.head(key).checksum), so the CMS stays decoupled from storage. retireDuplicate archives a copy no published content references (usedBy) and otherwise refuses with those references, so an editor points them at the kept document first.
import { runProvidedEffect } from '@voltro/runtime'
import { duplicateGroups, retireDuplicate } from '@voltro/cms'
const fingerprint = async (key: string) => (await lookUpChecksum(key)) ?? null
const groups = await runProvidedEffect(duplicateGroups(ctx.store, asset, scope, { field: 'file', fingerprint }))
// [{ fingerprint, documents: [{ id, documentId, title, status }, …] }] — oldest first
const retired = await runProvidedEffect(retireDuplicate(ctx.store, asset, scope, { copyId, keepId, field: 'file', fingerprint }))
// { ok: true } | { ok: false, reason: 'notDuplicate' } | { ok: false, reason: 'inUse', usedBy: [{ sourceType, sourceDocumentId, … }] }- Archived drafts are left out of the groups; a file whose fingerprint cannot be read is never a duplicate.
Availability of assets
A content type can declare when its documents may be used. This usually applies to image assets whose usage rights run out or are withdrawn:
import { runProvidedEffect } from '@voltro/runtime'
import { defineContentType, Schema, unavailableAmong } from '@voltro/cms'
export const asset = defineContentType({
name: 'asset', displayName: 'Image', pluralName: 'Images',
fields: {
title: Schema.String,
rightsUntil: Schema.DateTime.optional(),
blocked: Schema.Boolean.optional(),
},
availability: { until: 'rightsUntil', blocked: 'blocked' },
})
// Leave unavailable assets out when rendering an already-published page.
const unavailable = await runProvidedEffect(unavailableAmong(ctx.store, assetIds, scope))- Publishing a document of such a type records its availability in
cms_availability. - Publishing a revision that references a blocked or expired document throws
ReferenceUnavailable. The error names each target with itspathand the reasonblockedorexpired. The gate sits inpublishRevision, so single publishes, releases and rollbacks refuse it.publishDuekeeps such a row scheduled until the asset is available again. - Unblocking and republishing the asset, or picking another one, lifts the refusal.
unavailableAmong(store, documentIds, scope, now?)answers which documents may not be used right now. A right that runs out takes the asset off pages that are already live, without republishing them.defineContentTypethrows unlessuntilnames a date or datetime field andblockeda boolean field. RegistercmsAvailabilityTablewhen a type setsavailability.
Owners and reviews
A document can have an owner: the account responsible for its content in every language. That is separate from its author, its reviewer and whoever publishes it. A type can also declare a review cycle, so that published content is checked again after a number of days.
import { runProvidedEffect } from '@voltro/runtime'
import { contentHealth, recertify, setOwner, stewardshipOf } from '@voltro/cms'
const page = defineContentType({
name: 'page', displayName: 'Page', pluralName: 'Pages',
fields: { title: Schema.String },
lifecycle: { reviewEveryDays: 180 },
})
const place = { site: 'main', environment: 'production' }
await runProvidedEffect(setOwner(ctx.store, page, documentId, place, 'usr_owner'))
const { owner, review, reviewDue } = await runProvidedEffect(stewardshipOf(ctx.store, page, documentId, place))
await runProvidedEffect(recertify(ctx.store, page, documentId, place, { revisionId, by: 'usr_owner' }))
const findings = await runProvidedEffect(contentHealth(ctx.store, [page], place, {
sourceLocale: 'en-GB', locales: ['en-GB', 'de-DE'],
}))lifecycle: { reviewEveryDays }(a positive whole number) starts a review date on the document's first publish in a site and environment. Later publishes leave the date alone.recertifyrecords who checked which revision, and when. It moves the next reviewreviewEveryDaysahead.stewardshipOfreturnsowner,reviewDue,reviewedAt,reviewedBy,reviewedRevisionandreview.reviewisnotRequired(no cycle, or never published),scheduledordue.setOwner(…, null)clears the owner. The stewardship record is per document, site and environment, not per locale.contentHealthlists what needs attention among published documents:noOwner,reviewDue,linksToUnpublished(a live variant references a document that is not live in its language;detailnames the fields),translationMissingandtranslationOutdated(detailnames the source fields changed). A translation whose basis isunknownis not reported. It reads every published row of the types, so treat it as a report.- Register
cmsStewardshipTableto use owners or a review cycle. A type withoutlifecyclewrites nothing on publish.contentHealthalso readscms_references.
Bulk operations
One action over many drafts, in two steps: a dry run that changes nothing, then a run of exactly that plan.
import { runProvidedEffect } from '@voltro/runtime'
import { planBulk, runBulk } from '@voltro/cms'
const place = { site: 'main', environment: 'production' }
const items = [
{ type: 'page', id: 'page_01', locale: 'en-GB' },
{ type: 'page', id: 'page_02', locale: 'de-DE' },
]
const plan = await runProvidedEffect(planBulk(ctx.store, contentTypes, place, { kind: 'publish' }, items))
// plan[i].disposition: 'ready' | 'unchanged' | 'blocked', plus reason and detail
const results = await runProvidedEffect(runBulk(app.store, contentTypes, place, { kind: 'publish' }, plan))
// results[i].outcome: 'done' | 'unchanged' | 'failed', plus reason and detail- Actions:
{ kind: 'publish' },{ kind: 'unpublish' }and{ kind: 'setOwner', owner }(owner is an account id ornull). planBulkreturns one entry per item withdisposition,reason(notFound,reviewRequired,incomplete,referenceUnavailable,notPublished,unknownType),detail(for an unusable reference, the field and why; forincomplete, the empty fields),title,documentIdand, for a publish, therevisionIdthe draft showed.runBulkruns eachreadyitem in its own transaction through the same path as a single edit, including the review and availability gates. A publish uses the revision the plan pinned, so a save after the dry run is not published. One failing item does not undo the others. Blocked items are not tried and come back asfailedwith their reason.- To retry, plan the failed items again. Hand
runBulka store that is not already inside a transaction. After the commits it fires the revalidations of the types it changed.
{ kind: 'setField', field, value } sets one field to one value on every item. The dry run validates the value per item as a save would — a derived field, rich text or components are invalid with the reason in detail — and pins the revision each draft shows. The run saves a new draft revision of each against that revision: a draft edited after the dry run fails as revisionMoved instead of being overwritten. Nothing is published.
// Set one field on many drafts: each gets a new draft revision with the value (null clears it).
const plan = await runProvidedEffect(planBulk(ctx.store, contentTypes, place, { kind: 'setField', field: 'layout', value: 'wide' }, items))Change feed
A consumer that mirrors content (a search index, a static build, another
system) needs every change in order and has to resume after a break. A type
that declares changeFeed: true appends each publish and take-down to
cms_changes, in the same transaction as the change.
import { runProvidedEffect } from '@voltro/runtime'
import { cmsChangesTable, readChanges } from '@voltro/cms'
const page = defineContentType({ name: 'page', /* … */ changeFeed: true })
// A consumer: everything after the cursor it kept last time.
const { items, next } = await runProvidedEffect(readChanges(ctx.store, { site: 'main', environment: 'production' }, { after: cursor, limit: 100 }))
// items: [{ id, at, locale, contentType, documentId, variantId, action, revision, releaseId }, …]- The feed can never show a publish that rolled back, and never misses one
that committed. A release's entries carry its
releaseId, so they can be applied together. readChanges(store, place, { after, limit, settleMs, filter })returns the changes afterafter, oldest first, andnext. Keepnext; it stays put when nothing new has settled, so polling with it never skips.- Rows are ordered by their time-ordered id. Two transactions can commit in
the other order than their ids, so the read leaves out the last
settleMs(default 2 s). A row still being written is picked up on the next read instead of being skipped. - Pass the tenant in
filterfor a reader that carries none. RegistercmsChangesTablewhen a type sets the flag.
Search
A type that declares search: { title } is findable: every save writes the
draft's text to cms_search, every publish the published copy's, and a
take-down or archive removes it — each in the same transaction as the change.
searchContent asks the database's own full-text index, so a page is findable
the moment its publish commits. No external service is involved.
import { runProvidedEffect } from '@voltro/runtime'
import { cmsSearchTable, rebuildSearch, searchContent } from '@voltro/cms'
const page = defineContentType({ name: 'page', /* … */ search: { title: 'title' } })
// The public site: published pages in the reader's language, best first.
const hits = await runProvidedEffect(searchContent(ctx.store, { site: 'main', environment: 'production' }, 'compost heap', {
stage: 'published', locale: 'en-GB', types: ['page'], limit: 20,
}))
// hits: [{ contentType, documentId, variantId, locale, title, snippet: { text, marks }, rank }, …]
// Content saved before the type declared `search`: index it once.
await runProvidedEffect(rebuildSearch(ctx.store, page))- The title ranks before the body. The body is the text of every other field
that is not derived: strings, rich text, and the text inside lists, groups
and placed components. References, media keys and closed values
(
Schema.Literal) are not searched. - Every word of the query must occur, as a word beginning —
tomatofindstomatoes,comp heafinds "compost heap" — on postgres, mysql, sqlite and the in-memory store (a prefix search); mssql looks for the whole query as a substring. The index is language-neutral (simple, no stemming), because one table holds every locale. stage: 'draft'searches every document in its newest state, for an editor.stage: 'published'searches what is live, for readers.snippetis the passage of the body around the first hit.marksholds[start, end)offsets of the matched words, so the reader's UI can highlight them as text rather than HTML.- Leave out what a reader may not see yourself, for example members pages: ask for more hits than you show and drop those.
- Pass the tenant in
filterfor a reader that carries none. RegistercmsSearchTablewhen a type setssearch.
Environments
A site's content lives in an environment (CmsScope.environment) — production beside staging, say — with its own variants, revisions and published copies; the tenant, the site, the content types and the document ids are shared. Use one to try a change, review a large release or rehearse a migration without touching what is live.
import { runProvidedEffect } from '@voltro/runtime'
import { compareEnvironments, copyEnvironment } from '@voltro/cms'
// In a mutation: fill an EMPTY staging from production.
const result = await runProvidedEffect(copyEnvironment(ctx.store, contentTypes, { site: 'main', from: 'production', to: 'staging' }))
// { ok: true, variants, published } | { ok: false, reason: 'targetNotEmpty' | 'sameEnvironment', variants }
// How staging differs, per type.
const diff = await runProvidedEffect(compareEnvironments(ctx.store, contentTypes, { site: 'main', from: 'production', to: 'staging' }))
// [{ contentType, onlyInFrom, onlyInTo, differing: [{ documentId, locale, title }] }]copyEnvironmentfills an environment that holds no variant of these types yet — it never merges into or overwrites one (targetNotEmpty). Every draft is copied with its own revision history (the live copy as revision 1, the draft on top when it moved on), and the derived state is written as a publish would: references, availability, page paths, the search index. Only the caller's tenant is read and written.compareEnvironmentsnames, per type, the documents only on one side and the live documents whose published values differ.- Readers pick the environment through the scope they read with — a delivery key or a route for
stagingreads staging.
Promoting between environments
import { runProvidedEffect } from '@voltro/runtime'
import { planPromotion, promote } from '@voltro/cms'
const pair = { site: 'main', from: 'staging', to: 'production' }
// What promoting would change: [{ contentType, documentId, locale, title, change: 'new' | 'changed' | 'blocked' }]
const plan = await runProvidedEffect(planPromotion(ctx.store, contentTypes, pair))
// In a mutation: the chosen documents go live in production as ONE release.
const result = await runProvidedEffect(promote(ctx.store, contentTypes, pair, [{ contentType: 'page', documentId, locale: 'en-GB' }], { name: 'Spring' }))
// { ok: true, releaseId, promoted } | { ok: false, reason: 'nothingSelected' | 'blocked' | 'notInPlan', items }planPromotionlists the documents live infromthat arenewinto(not live there) orchanged(other values). A document whosetovariant has unpublished draft edits isblocked— promoting it would bury them unseen. Unchanged documents are left out.promotesaves each chosen document'sfromvalues as thetovariant's newest revision (a new variant under the same document whentohas none) and publishes them together as one release into— review, availability and required-field checks included, all or nothing. It refuses, writing nothing, when an item is blocked or not in the plan. Run it in a transaction.
Project blueprints
A blueprint declares the content a new workspace starts with — its pages, header, footer, site document — in code, and provisions it into any workspace and environment. Provisioning is idempotent and leaves nothing tying the content to the blueprint.
import { runProvidedEffect } from '@voltro/runtime'
import { applyBlueprint, blueprintRef, defineBlueprint, planBlueprint } from '@voltro/cms'
const starter = defineBlueprint({
id: 'starter-site',
displayName: 'Starter site',
locale: 'en-GB',
entries: [
{ key: 'about', type: 'page', match: 'slug', values: { title: 'About us', layout: 'default' },
translations: { 'de-DE': { title: 'Über uns' } } },
{ key: 'imprint', type: 'page', match: 'slug', values: { title: 'Imprint', layout: 'default' } },
{ key: 'footer', type: 'footer', values: { title: 'Footer', imprint: blueprintRef('imprint') } },
],
})
const target = { site: 'main', environment: 'production' }
// [{ key, type, locale, label, action: 'create' | 'present', documentId, variantId, outcome: 'live' | 'draft' | 'review' | null }]
const plan = await runProvidedEffect(planBlueprint(ctx.store, contentTypes, starter, target))
// In a mutation: creates what the plan calls `create`, all or nothing.
const done = await runProvidedEffect(applyBlueprint(ctx.store, contentTypes, starter, target))defineBlueprintrefuses a key used twice, ablueprintRefto no entry and entries that reference each other in a circle (BlueprintInvalid), and orders the entries so a referenced one comes first.blueprintRef(key)stands for that entry's document id anywhere invalues— a reference field, a component's props.- An entry is present when the workspace has a document whose
matchfield has the entry's value (after derivations, soslugis compared as it would be saved); withoutmatch, any document of the type counts. A present document is never changed and gets no new language; it only lends its id to the entries that reference it. For a document the blueprint creates, each language intranslationsis its own step. templatebuilds the document from one of the type's page templates, withvaluesover it.planBlueprintrefuses an unknown type,matchfield or template before anything is written.applyBlueprintsaves each created variant and publishes it, unless the entry sayspublish: false(draft) or the type needs a review (review— it stays a draft). A second run finds everything and writes nothing. It runs in the caller's transaction; a validation failure or a referenced document that is not live aborts it whole.plan.documentsis the number of new documents, for a quota check before applying. Nothing records that a document came from a blueprint: once provisioned, the content is the workspace's own, and a later change to the blueprint reaches only workspaces set up after it.
The team a blueprint brings
A blueprint's team names the role a new editor of the workspace gets
(defaultRole) and people invited with a role before they have an account
(members: e-mail and role). Roles are the app's own names; defineBlueprint
refuses a malformed role or address and an address listed twice
(teamProblems). Register cmsTeamTable and cmsTeamInvitationsTable.
import { runProvidedEffect } from '@voltro/runtime'
import { applyBlueprintTeam, defineBlueprint, invitedRole, inviteToTeam, planBlueprintTeam, teamDefaultRole, withdrawInvitation } from '@voltro/cms'
const blog = defineBlueprint({ id: 'blog', displayName: 'Blog', locale: 'en-GB', entries: [/* … */],
team: { defaultRole: 'author', members: [{ email: 'managing-editor@example.com', role: 'publisher' }] } })
await runProvidedEffect(planBlueprintTeam(ctx.store, tenantId, blog.team!)) // { defaultRole: { role, action: 'set' | 'kept' }, members: [{ email, role, action: 'invite' | 'present' }] }
await runProvidedEffect(applyBlueprintTeam(ctx.store, tenantId, blog.team!)) // in the caller's transaction
// In the app's role resolver, for someone without an assignment:
const role = (await runProvidedEffect(invitedRole(store, tenantId, email))) ?? (await runProvidedEffect(teamDefaultRole(store, tenantId))) ?? 'author'
// By hand, in the caller's transaction:
await runProvidedEffect(inviteToTeam(ctx.store, tenantId, 'riley@example.com', 'author')) // 'invited' | 'changed' | 'present'
await runProvidedEffect(withdrawInvitation(ctx.store, tenantId, 'riley@example.com')) // false when there was noneApplying it sets the default role only where the workspace has none and invites only addresses not invited yet — a second run, or another blueprint, never undoes an admin's choice. Every read takes the tenant it filters by, so a role resolver running outside a request can use it.
Audiences
A variant of a page for part of its readers is named by an audience: a versioned rule over signals the server was handed about the request — the preferred language, a country a trusted proxy determined, whether the reader allowed being recognised and was here before. The rule is evaluated on the server; the browser never decides what it is shown.
import { defineAudience, languagesOf, pickVariant } from '@voltro/cms'
export const germanSpeakers = defineAudience({ id: 'germanSpeakers', version: 1, displayName: 'German speakers', rule: { languages: ['de'] } })
export const austria = defineAudience({ id: 'austria', version: 1, displayName: 'Austria', rule: { countries: ['AT'] } })
// On the server, from signals the request declared (never evaluated in the browser):
const signals = { languages: languagesOf(acceptLanguage), country: edgeCountry }
const variant = pickVariant(page.heroVariants ?? [], [germanSpeakers, austria], signals)
// variant: the first whose audience matches, or null → the published original- Every condition a rule gives must hold; a rule with none would match everyone and is refused by
defineAudience. languagescompares the reader's FIRST preference (dematchesde-AT);languagesOforders anAccept-Languageheader by its quality factors.pickVariantreturns the first variant whose audience matches; a variant naming an audience that no longer exists never matches.- A variant is content of the page, so it goes live with the page's publish. A response that depends on these signals must say so to caches (
Vary), or be private.
Experiments
Two versions of a live page, and readers split between them. Version B overrides chosen text fields of the published values (the type's own string fields, not derived ones); share is the percent of readers shown B.
An experiment starts with its hypothesis — what B should change, and why (required, at most 500 characters) — and may carry a guardrail: B's conversion rate may fall at most guardrailMaxDrop percentage points (1–50) below A's. From MIN_READERS readers per version on, experimentResults reports guardrail.breached when it falls further; stopping stays a person's decision.
import { runProvidedEffect } from '@voltro/runtime'
import {
applyVariant, assignVariant, experimentResults, recordExperimentEvent, runningExperiment, startExperiment,
} from '@voltro/cms'
// A publisher, in a mutation: version B of a live page shows another title to 50 % of readers.
const started = await runProvidedEffect(startExperiment(ctx.store, page, scope, {
documentId, name: 'Friendlier title', share: 50, overrides: { title: 'Grow with us' }, goal: 'cta',
hypothesis: 'A friendlier title makes more readers follow the call to action.', guardrailMaxDrop: 5,
}))
// { ok: true, id } | { ok: false, reason: 'notLive' | 'alreadyRunning' | 'noOverrides' | 'badShare' | 'unknownField' | 'noHypothesis' | 'badGuardrail' }
// Reading the page for a reader who allowed it (readerId: a pseudonymous id the app keeps in a cookie):
const experiment = await runProvidedEffect(runningExperiment(ctx.store, page, scope, documentId))
if (experiment !== null) {
const variant = assignVariant(experiment.id, readerId, experiment.share) // 'A' | 'B', the same every visit
values = applyVariant(values, experiment, variant)
await runProvidedEffect(recordExperimentEvent(ctx.store, experiment, readerId, 'exposure'))
}
// When the reader reaches the goal:
await runProvidedEffect(recordExperimentEvent(ctx.store, experiment, readerId, 'conversion'))
const results = await runProvidedEffect(experimentResults(ctx.store, experimentId))
// { A: { readers, conversions, rate }, B: { … }, lift, pValue, conclusive, guardrail: { maxDrop, breached } }- One experiment runs per page, language and environment, and only on a live page.
stopExperimentends it; its counts stay. - The reader id is the app's: a pseudonymous id, set only with the reader's consent. The version comes from a hash of experiment and reader, so it holds across visits and processes with nothing stored until the reader is counted.
recordExperimentEventcounts a reader once per kind (a unique index, safe when asked twice at once), a conversion only after an exposure, and only while the experiment runs. The reader is stored hashed with the experiment id, so two experiments cannot be joined on it.experimentResultsisconclusiveonly with at leastMIN_READERS(100) readers per version and a two-sided p-value below 0.05 — before that, say the difference may be noise.
Adopting the winner
Version B goes live the way every change does — through a release. adoptWinner stops the experiment if it still runs, saves B's text over the page's draft as a new revision, and pins that revision in a new draft release named after the experiment. Nothing is published there: the release is, by whoever may, through its review gate, a schedule or by hand, and it rolls back like any other.
import { runProvidedEffect } from '@voltro/runtime'
import { adoptWinner, experimentLineage } from '@voltro/cms'
// A publisher, in a mutation:
const adopted = await runProvidedEffect(adoptWinner(ctx.store, page, experimentId))
// { ok: true, releaseId, revisionId } | { ok: false, reason: 'notFound' | 'alreadyAdopted' | 'noDraft' }
const lineage = await runProvidedEffect(experimentLineage(ctx.store, experimentId))
// { startedOn, overrides, delivered: [{ revisionId, variant, readers }], adopted: { releaseId, revisionId, releaseStatus } | null }- Every counted reader is traced to what they were delivered:
startedOnis version A (the published revision the experiment started on), version B is it plusoverrides, and each exposure records the revision live at that moment — a publish during the experiment adds a row todelivered. The assignment isassignVariant(experimentId, readerId, share), deterministic, so it can be recomputed for any reader id. - A slug that follows its title follows B's title too, as with any edit; the old address redirects.
- An experiment is adopted once (
alreadyAdopted);releaseStatusfollows the release (draft,scheduled,published,failed).
Usage and quotas
contentUsage counts what a tenant holds right now, from the drafts tables — for a usage page, or to check a limit before a create. Nothing is estimated and there is no monthly window: it is the current stock.
import { runProvidedEffect } from '@voltro/runtime'
import { QuotaExceeded, contentUsage } from '@voltro/cms'
const usage = await runProvidedEffect(contentUsage(ctx.store, contentTypes, 'main'))
// { documents, documentsByType: { page: 12, … }, environments: ['production', 'staging'] }
// In the create's mutation, before the write:
if (usage.documents + 1 > LIMIT) {
return yield* Effect.fail(new QuotaExceeded({ quota: 'documents', limit: LIMIT, used: usage.documents }))
}- A document counts once, however many languages and environments it has (a copy into another environment keeps its id). Archived documents are not counted. A request store counts only the caller's tenant.
environmentslists the environments of the site that hold any content.QuotaExceeded({ quota, limit, used }, also exported from@voltro/cms/webfor descriptors) is the typed refusal: declare it as the mutation'serror, and give it a status inpublicApi.errorStatus.- Two creates at the same moment can both pass a count-then-write check. To make the last free slot go to one of them, lock a row both creates read first, e.g. the tenant's row with
lock: 'update', inside the create's transaction. - Files are not counted here:
storagePlugin({ quota: { maxCount, maxBytes } })counts and refuses uploads itself, andStorageService.usage(tenantId)reports them.
Releases
A release pins exact revisions of several variants — any content type, any locale — for one site and environment, and takes them live together.
import { runProvidedEffect } from '@voltro/runtime'
import {
addToRelease, createRelease, publishRelease, rollbackRelease, scheduleRelease,
} from '@voltro/cms'
// Pin the current revision of several variants — any type, any locale.
const release = await runProvidedEffect(createRelease(ctx.store, { name: 'Spring', site: 'main', environment: 'production' }))
await runProvidedEffect(addToRelease(ctx.store, release.id as string, { type: page, id: homeId, locale: 'en-GB' }))
await runProvidedEffect(addToRelease(ctx.store, release.id as string, { type: page, id: homeDeId, locale: 'de-DE' }))
// In a mutation: every entry goes live, or none does.
await runProvidedEffect(publishRelease(ctx.store, [page], release.id as string))
// …or plan it; a schedule running publishDueReleases takes it live.
await runProvidedEffect(scheduleRelease(ctx.store, release.id as string, new Date('2026-04-01T08:00:00Z')))
// Undo: a NEW release restores what was live before.
await runProvidedEffect(rollbackRelease(ctx.store, [page], release.id as string))publishRelease runs in the caller's transaction: when one entry fails, the
entries before it roll back with it and the release stays a draft, so a release
is never half-live. In a mutation, fail with a typed error rather than returning
an { ok: false } answer — an answer commits the entries already written. A
release publishes the revision it pinned, even when the draft has been
edited since; publish of a single variant copies its current revision the same
way (publishRevision), so a draft still at revision 0 needs one save first.
publishDueReleases(store, types, now) takes due scheduled releases live, each
in its own transaction. It claims a release with a conditional update and a
fencing token, so a second replica or a retry never publishes it twice; a
release that fails is marked failed with the reason. Drive it from a
*.cron.tsx every minute. rollbackRelease publishes a new release that puts
back each variant's previous revision (unpublishing what was not live); the
rolled-back release keeps its history. Register cmsReleasesTable and
cmsReleaseItemsTable in your databaseHandle to use releases.
The reason on a failed release names what to fix, for example
ReferenceUnavailable: page page_… uses asset cdoc_… (blocked) or
ReviewRequired: … (describeFailure builds it). Once the cause is fixed,
retryRelease(store, releaseId) (or retryReleaseEffect) takes the release
back to draft with its entries unchanged and the failure cleared, ready to be
published or scheduled again. A release that did not fail throws
ReleaseNotEditable.
Scheduled publishing
A draft can be marked to go live at a future time, then flipped live by a
periodic sweep. schedulePublish stamps the draft's publishAt (a draft-only
nullable column) without publishing now; publishDue publishes every draft
whose time has passed.
import { runProvidedEffect } from '@voltro/runtime'
import { schedulePublish, publishDue } from '@voltro/cms'
// Mark a draft to publish later (does NOT publish now):
await runProvidedEffect(schedulePublish(ctx.store, blogPost, draftId, new Date('2026-01-01T09:00:00Z'), scope))
// Flip every due draft live (idempotent; returns the published ids):
const publishedIds = await runProvidedEffect(publishDue(ctx.store, blogPost, new Date()))schedulePublish keys off a tenant-scoped read (a foreign/missing id throws
ContentNotFound) and leaves status: 'draft' until the row goes live.
Passing null as the time cancels the schedule.
publishDue selects publishAt <= now AND status = 'draft' and gives each row
its own transaction: the ordinary publish plus clearing publishAt commit
together, and a failing row cannot take back the rows already live. It is
idempotent, so a row is never double-published, and it fires the type's
declared revalidations after the commits. Hand it a store that is not already
inside a transaction — a schedule's app.store, not a mutation's ctx.store.
A request store covers one tenant; a background/root store covers every tenant.
@voltro/cms does not ship the scheduler — you drive publishDue from a
*.cron.tsx schedule:
// apps/api/schedules/content-scheduler.cron.tsx
import { defineSchedule, runProvidedEffect } from '@voltro/runtime'
import { publishDue } from '@voltro/cms'
import { blogPost } from '../blogPost.contentType'
export default defineSchedule({
name: 'contentScheduler',
cron: '* * * * *',
timezone: 'UTC',
// app.store has no request subject, so the sweep flips due drafts live
// across ALL tenants.
handler: async ({ app }) => {
await runProvidedEffect(publishDue(app.store, blogPost, new Date()))
},
})Scheduled take-down
The other end of a campaign: scheduleUnpublish stamps the draft's
unpublishAt (a second draft-only nullable column), and unpublishDue takes
every live entry whose time has passed down — the published copy, its
references and its search entry go, as unpublish does, and unpublishAt is
cleared in the same transaction. It may be set before the entry is live (live
at nine, down at five); an entry that is not live when its time comes only has
the marker cleared. null cancels it. Drive it from the same schedule:
import { runProvidedEffect } from '@voltro/runtime'
import { scheduleUnpublish, unpublishDue } from '@voltro/cms'
await runProvidedEffect(scheduleUnpublish(ctx.store, blogPost, draftId, new Date('2026-01-31T17:00:00Z'), scope))
const takenDown = await runProvidedEffect(unpublishDue(ctx.app.store, blogPost, new Date()))unpublishAt is reserved like publishAt: a content type cannot declare a
field of that name.
Repeating live windows
A live window that repeats ("live every Friday at 08:00 for 72 hours, four
times") is a bounded series, written as a wall time of an IANA zone.
occurrencesOf(rule) turns it into its windows, each a plain startsAt and
endsAt. The steps are calendar steps in the zone, so a weekly 08:00 stays
08:00 across a daylight-saving change. A wall time the zone skips moves to the
first moment after the gap (adjusted: 'gap'), one it repeats takes the
earlier instant ('fold'), and a monthly day the month lacks moves to its last
day ('clamped'). A series has at most MAX_OCCURRENCES (100) positions, each
window ends before the next starts, and except leaves local dates out.
recurrenceProblems(rule) says in words what is wrong, and zonedInstant is
the wall-time resolution on its own; all three are browser-safe.
scheduleSeries keeps the rule in cms_publish_series (register
cmsPublishSeriesTable). The draft only ever holds one armed window as its
ordinary publishAt / unpublishAt, and publishDue / unpublishDue carry it
out as for any schedule, including review and blocked images. advanceSeries
arms the next window once nothing is pending, and ends the series after its
last. A schedule set by hand makes the series wait; scheduling again replaces
the series. A rule with problems, or one whose windows are all over, throws
ContentValidationFailed on the field repeat.
import { runProvidedEffect } from '@voltro/runtime'
import { advanceSeries, cancelSeries, occurrencesOf, scheduleSeries } from '@voltro/cms'
const rule = { start: '2026-10-02T08:00', zone: 'Europe/Berlin', every: 'week', count: 4, durationMinutes: 72 * 60 } as const
occurrencesOf(rule) // four { startsAt, endsAt } windows, 08:00 Berlin time each, across the DST change
await runProvidedEffect(scheduleSeries(ctx.store, offer, draftId, scope, rule)) // arms the first window as publishAt / unpublishAt
// In the schedule, after publishDue and unpublishDue:
await runProvidedEffect(advanceSeries(ctx.app.store, offer, new Date())) // arms the next window once one is over
await runProvidedEffect(cancelSeries(ctx.store, offer, draftId)) // stops, clears what it armedMedia resolution
A Schema.Media() field stores a storage object key. Turning it into a
served URL needs the storage service (its getUrl / mintUrl are
Effect-returning and mintUrl needs the request Subject), so that context
lives in your app — not the core package. Rather than couple @voltro/cms to a
storage plugin, resolution is a typed hook: you supply a MediaResolver, and
resolveMedia swaps every media key on a row (including media nested in
Array / Struct fields) for the resolved URL.
import { runProvidedEffect } from '@voltro/runtime'
import { resolveMedia, resolveMediaAll, type MediaResolver } from '@voltro/cms'
import { Effect } from 'effect'
const resolver: MediaResolver = (key) =>
Effect.runPromise(storage.mintUrl(key, ctx.subject)).catch(() => null)
const post = await useCms(ctx).contentType('blogPost').where('slug', '=', 'hello').one()
const withUrls = post ? await runProvidedEffect(resolveMedia(blogPost, post, resolver)) : nullresolveMedia returns a new row (the input is not mutated); a key the resolver
returns null for is left as its stored key. resolveMediaAll maps a whole
list; mediaFields(type) lists the top-level media field names.
Versioning content
@voltro/cms ships no parallel revision system — the derived tables are
ordinary database tables, so @voltro/plugin-row-history gives full row history
plus time-travel with no new machinery. The plugin records every table by default —
narrow it with include: (pass the derived table handles) or exclude: if you
only want content history — then read a timeline or restore a snapshot:
import { rowHistoryPlugin, rowHistory, restoreAsOf } from '@voltro/plugin-row-history'
// Register in your app's plugin list:
rowHistoryPlugin({})
const timeline = await rowHistory(ctx.store, 'blogPost_published', postId, tenantId)
await restoreAsOf(ctx.store, 'blogPost_published', postId, tenantId, someEarlierDate)The editor form
<ContentForm> (from /web) renders one labelled widget per field, driven by
each field's editor hint — stateless and unstyled. Each label is bound to its
control, so assistive technology announces the field name. Override any widget
(e.g. an upload widget for media) via the widgets prop; a widget receives the
id its label points at and must put it on the control it renders. A widget
is rendered as a component, so it may use hooks (an upload, a live list to pick
from). Its onChange applies to the form as it is when the change lands, so an
upload that finishes after the editor typed elsewhere keeps the typing:
import { ContentForm } from '@voltro/cms/web'
<ContentForm contentType={blogPost} value={row} onChange={setRow}
widgets={{ media: MyUploadWidget }} />A components field renders as a named group: one fieldset per placed
component (legend Hero 1, Text block 2, …) with that component's props as a
nested form, Move up / Move down / Remove buttons whose accessible
names include the component, and an Add component picker below the list.
A richText field renders as a named group holding the block editor: one
fieldset per block (legend Paragraph 1, List 2, …), Move up / Move
down / Remove buttons named after the block, and an Add block
picker. Pass renderPicker to <ContentForm> so the editor can offer image
blocks and links. It renders a control that picks one document of a given
type:
<ContentForm contentType={page} value={row} onChange={setRow}
renderPicker={({ id, type, value, onChange }) => <DocumentSelect id={id} type={type} value={value} onChange={onChange} />} />By default a paragraph or heading is typed in small inline markup in a text
area. richTextSurface="visual" edits them as they look instead: a text box
(role="textbox", named after the block) showing bold as bold and a link as a
link, with Bold, Italic and Underline buttons (and Ctrl/Cmd+B, +I,
+U) that toggle the mark on the selection. What the text box holds is read back into the document's
inline nodes on every input, so the stored value only holds what the document
model allows: a paste arrives as plain text, Shift+Enter is a line break, and
Enter adds nothing (a new paragraph is a new block). Lists and tables keep
their text areas. Name the buttons with strings.bold, strings.italic and
strings.underline:
<ContentForm contentType={page} value={row} onChange={setRow} richTextSurface="visual"
strings={{ bold: 'Fett', italic: 'Kursiv' }} /><RichTextSurface> is the text box on its own, for an editor of your own. The
helpers it is built on work on a run of inline nodes by character offset:
toggleMark, hasMark, replaceText, mergeInline, inlineText, and
inlineHtml / inlineFromDom for the HTML the box shows and the run read back
from it.
renderFieldAside(name) renders something beside each field, inside the
field's own container and after its control — its comment threads, a hint, who
else is editing it. Return null to render nothing for a field:
<ContentForm contentType={page} value={row} onChange={setRow}
renderFieldAside={(name) => <FieldComments anchor={`cms:page:${row.documentId}#${name}`} />} />renderBlockAside(field, blockId, label) does the same inside each block of a
rich-text field (the built-in editor), after the block's actions. blockId is
the block's stable id — it survives moving the block and new revisions — so a
thread anchored to it stays with that paragraph; label is the block's legend
(Paragraph 2).
fieldLabel(path) gives each field the label a person reads instead of its
name in code. path is the field's name (title), or for a component's prop
the component id and the prop (hero.heading); undefined keeps the name.
Answer from the app's message catalog and the labels follow the editor's
language:
<ContentForm contentType={page} value={row} onChange={setRow}
fieldLabel={(path) => catalog[`field.page.${path}`]} />strings gives the form's own controls their words — block names and
legends, Move up / Move down / Remove and their accessible names,
Add block, Add component, the block editor's labels and the link
inserter. Pass any of them; the rest stays English (CONTENT_FORM_STRINGS,
browser-safe, also in /web). The accessible names are functions of the
thing acted on:
<ContentForm contentType={page} value={row} onChange={setRow}
strings={{ blockNames: { paragraph: 'Absatz' }, moveUp: 'Nach oben', removeLabel: (label) => `${label} entfernen` }} />A Schema.Array(...) of single values — strings, numbers, references — renders a named group with one control per entry, through the element's widget (a reference entry uses your reference widget): each entry in a fieldset whose legend is the field's label and position (Categories 2, strings.item), with Move up / Move down / Remove, and Add entry (strings.addItem) below. An array of structs keeps the placeholder.
fieldWidgets replaces one field's widget by its name, whatever its hint — a select for a string field only some values make sense in, like the template a page is built from. It wins over widgets:
<ContentForm contentType={post} value={row} onChange={setRow}
widgets={{ reference: DocumentSelect }}
fieldWidgets={{ template: TemplateSelect }} />Undo and redo in the editor
describeEdit(fields, before, after, words) names one change of the form: a
component or rich-text block added, removed, moved up or down, or edited, found
by its instanceId or block id; two neighbours that changed places are a
swap (which of them was moved cannot be told from the result, so both are
named); any other field is edited. Several fields at
once are one edit. words supplies the editor's language (field, component and
block names, and the verbs), so a toolbar can say "Undo: move Hero up"
instead of showing only an arrow. The key it returns tells whether the next
change continues this one.
recordEdit(history, before, edit, at) keeps the form as it was before each
step. A change with the same key within mergeMs (1.5 s) continues the last
step, so typing is one step, and at most limit (100) steps are kept. A new
step drops what could have been redone. undoEdit and redoEdit return the
form to show and the history after the step, or null when there is nothing to
undo or redo. All of it is pure and lives in @voltro/cms/web; the history is
the editor's own and is not stored. A step undone after a save is an ordinary
change and is saved as a new revision.
import { EMPTY_EDIT_HISTORY, describeEdit, recordEdit, redoEdit, undoEdit } from '@voltro/cms/web'
let history = EMPTY_EDIT_HISTORY
// On every change of the form:
const edit = describeEdit(page.fields, values, next, words) // { label: 'Move Hero up', key }
if (edit !== null) history = recordEdit(history, values, edit, Date.now())
// Undo, and redo:
const undone = undoEdit(history, current) // { values, history, label } or null
const redone = redoEdit(history, current)Leave fields typed in together out of the history: undoing them would rewind the other editors' typing as well.
Visual editing
The editor can show the page it edits beside the form, in a frame of its own
origin, and the two talk over postMessage. @voltro/cms/web holds the
protocol; the frame, the rendering and the layout stay the app's.
values(editor to preview): the form as it is now, unsaved. The preview renders it without a reload.ready(preview to editor): the preview listens; send the values.select(preview to editor): a click on a part of the page.pathis a field (title) or one placed component (sections.2);formPartOf(form, path)finds that part of aContentForm.move(preview to editor): a component moved in the preview to indexto;moveEntry(list, from, to)moves it in the value.
Every message carries the protocol name and a nonce for the session
(newVisualNonce(), 128 bits). readPreviewMessage and readEditorMessage
return null for a message from another origin, with another nonce or in an
unknown shape, so a stale frame or a foreign page cannot drive the editor.
Also check event.source against the frame (or window.parent). The preview
marks what it renders with sourceAttributes(path), and sourcePathOf(target)
finds the path behind a click. Mark only in the preview; public pages carry no
markers.
import { formPartOf, moveEntry, newVisualNonce, parseSourcePath, readPreviewMessage, visualMessage } from '@voltro/cms/web'
// Editor side: one nonce per session, one frame.
const session = { origin: window.location.origin, nonce: newVisualNonce() }
window.addEventListener('message', (e) => {
if (e.source !== frame.contentWindow) return
const m = readPreviewMessage(e, session)
if (m?.kind === 'ready') frame.contentWindow?.postMessage(visualMessage(session, { kind: 'values', values }), session.origin)
if (m?.kind === 'select') formPartOf(form, m.path)?.querySelector<HTMLElement>('input, textarea, select')?.focus()
if (m?.kind === 'move') {
const { field, index } = parseSourcePath(m.path)
if (index !== undefined) setValues({ ...values, [field]: moveEntry(values[field] as unknown[], index, m.to) })
}
})import { readEditorMessage, sourceAttributes, sourcePathOf, visualMessage } from '@voltro/cms/web'
// Preview side: render the values it is sent, mark what it renders, report clicks.
window.addEventListener('message', (e) => {
const m = readEditorMessage(e, session)
if (m !== null) setValues(m.values)
})
window.parent.postMessage(visualMessage(session, { kind: 'ready' }), session.origin)
<h1 {...sourceAttributes('title')}>{values.title}</h1>
<article onClick={(e) => {
const path = sourcePathOf(e.target)
if (path !== null) window.parent.postMessage(visualMessage(session, { kind: 'select', path }), session.origin)
}} />The frame is the app's own origin, and the default policy forbids every
frame. Allow it for the preview route only — a middleware.ts matched to it,
so the editor itself stays unframeable:
// middleware.ts (web app root)
import { defineMiddleware } from '@voltro/web/middleware'
export const previewFraming = defineMiddleware({
match: { under: '/preview' },
run: () => ({
responseHeaders: {
'content-security-policy': "frame-ancestors 'self'; base-uri 'none'; object-src 'none'",
'x-frame-options': 'SAMEORIGIN',
},
}),
})Setting frame-ancestors 'self' in security.headers.cspHtml instead lets
every page of the app be framed by its own origin.
AI operations
A model proposes; a person decides. recordAiOperation keeps every call —
operation and version, provider and model, the variant and revision it read,
the field, a SHA-256 promptHash of the prompt (never the prompt), tokens, and
suggested or failed with the error. settleAiOperation records what the
person did with a proposal, once: applied or discarded.
aiOperationsFor(store, type, variantId) lists a variant's history. Register
cmsAiOperationsTable.
Each workspace chooses how it reaches a model: setAiSettings(tx, tenantId, { provider, model, apiKey? }) — its own key is stored encrypted and
serverOnly, apiKey: null removes it, settings: null goes back to the
deployment's provider (AI_PROVIDER, @voltro/ai). aiSettings(store, tenantId) reads it for the server's call. Register cmsAiSettingsTable; it
needs the field cipher.
A workspace can cap its AI calls per calendar month (UTC): setAiBudget(tx, tenantId, monthlyTokens) (null: no limit). aiTokensUsed(store, tenantId)
sums the tokens this month's recorded calls used, aiBudgetLeft what is left —
check it before a call, and record a refused one as failed with the reason.
Going back to the deployment's provider (setAiSettings(…, null)) keeps a
budget.
import { generateText, providerFromEnv } from '@voltro/ai'
import { runProvidedEffect } from '@voltro/runtime'
import { aiSettings, recordAiOperation } from '@voltro/cms'
const own = await runProvidedEffect(aiSettings(ctx.store, tenantId))
const provider = own === null ? providerFromEnv() : { name: own.provider, model: own.model, ...(own.apiKey ? { apiKey: own.apiKey } : {}) }
const { text, usage } = await Effect.runPromise(generateText({ prompt, provider }))
await runProvidedEffect(recordAiOperation(ctx.store, { operation: 'suggest.seoDescription', version: '1', provider: provider.name, model: provider.model,
contentType: 'page', variantId, revisionId, field: 'seoDescription', prompt, usage, outcome: 'suggested' }))Glossary
A workspace's glossary says, per term of the source language, how it is written
in a target language (translation; null: it stays as it is, like a brand name)
and which translations must not be used (forbidden). One entry per term
(matched without regard to case) and language; setGlossaryTerm again replaces
it, glossaryInputProblems checks an entry first. termsIn(text, entries) picks
the entries a source text contains — the ones to tell a model that translates it;
glossaryProblems(text, entries) finds forbidden words in a translation. Both
match whole words. Register cmsGlossaryTable.
import { runProvidedEffect } from '@voltro/runtime'
import { glossary, glossaryProblems, setGlossaryTerm, termsIn } from '@voltro/cms'
await runProvidedEffect(setGlossaryTerm(ctx.store, tenantId, { term: 'raised bed', locale: 'de-DE', translation: 'Hochbeet', forbidden: ['erhöhtes Beet'] })) // 'added' | 'replaced'
const terms = termsIn(sourceText, await runProvidedEffect(glossary(ctx.store, tenantId, 'de-DE'))) // the entries the source names — tell the model
glossaryProblems(translatedText, terms) // [{ term, found: 'erhöhtes Beet', use: 'Hochbeet' }]Extensions
An extension is described by its manifest before anything of it runs: id,
name, major.minor.patch version, publisher, the capabilities it asks for and
the places in the editor it shows (sidebar, dashboard, fieldWidget,
entryTab, releaseCheck, assetAction, settings); a fieldWidget names
the fields it shows beside, and the settings slot lists its settings
(each a number with optional bounds, a boolean or a choice of options, with
a default). A capability is one of
content:read, content:write, egress:<host> (HTTPS to exactly that host)
or secret:<NAME>; manifestProblems names everything else in words. The
manifest, the capability check, compareVersions, newCapabilities,
ExtensionManifestSchema and the typed ExtensionAccessDenied are
browser-safe (@voltro/cms/web), so the editor shows the same capabilities the
server grants.
Installs are per tenant, in cms_extensions, and each extension's own data in
cms_extension_data (register cmsExtensionsTable and
cmsExtensionDataTable):
installExtension(tx, manifest, consent)installs only whenconsentcovers every capability the manifest asks for; the grant is exactly that.upgradeExtension(tx, manifest)applies a newer version at once when it asks for nothing new — and drops what it no longer asks for. A version that asks for more waits (pending); the installed version keeps running with its grant untilconsentToUpgrade(tx, id, consent)covers what it adds.rollbackExtension(tx, id)returns to the version that ran before the last move, with the grant it had then (installed.previousnames it). One step: a second rollback answersnothingToRollBack, and a waiting version is dropped. A rollback never grants more than was consented to for that version.revokeExtension(tx, id)takes every capability away and keeps the install and its data; every reach is refused untilregrantExtension(tx, id, consent)consents again to everything its version asks for.bindExtensionSecret(tx, id, name, value)sets a secret the running or waiting version asks for (secret:<NAME>;notAskedotherwise) andvalue: nullremoves it. The value is stored incms_extension_secrets(registercmsExtensionSecretsTable), encrypted andserverOnly: no read hands it to a client.extensionSecret(store, id, name)is for the host — lend it assecretand the sandbox passes it on only when granted. Uninstalling removes the secrets too. The column needs the field cipher (VOLTRO_FIELD_ENCRYPTION_KEY, minted byvoltro dev).setExtensionSettings(tx, id, values)sets settings after checking each value against the manifest (settingsProblems: kind, bounds, options, no unknown keys);extensionSettings(store, id)reads them with the defaults filled in, and the sandbox'ssettings()hands them to the extension's code, which cannot write them.uninstallExtension(tx, id)removes the install and the extension's data, and returns that data as the export. Content never depends on an extension.
import { runProvidedEffect } from '@voltro/runtime'
import { consentToUpgrade, extensionSandbox, installExtension, installedExtension, upgradeExtension } from '@voltro/cms'
await runProvidedEffect(installExtension(ctx.store, readingTime_1_0, ['content:read']))
const change = await runProvidedEffect(upgradeExtension(ctx.store, readingTime_1_1))
// change.installed.pending?.adds → ['secret:READING_SPEED']: 1.0.0 keeps running
await runProvidedEffect(consentToUpgrade(ctx.store, 'reading-time', ['secret:READING_SPEED']))
const installed = await runProvidedEffect(installedExtension(ctx.store, 'reading-time'))
const sandbox = extensionSandbox(ctx.store, installed!, host)
await sandbox.readContent('page', draftId) // needs content:read
await sandbox.secret('READING_SPEED') // needs secret:READING_SPEED
await sandbox.data.set('lastRun', { at: Date.now() }) // its own namespaceextensionSandbox(store, installed, host) is what the extension's code gets.
The host (ExtensionHost) lends content reads (one draft, readContent, or a
type's drafts, listContent, how many there are, countContent, and the values a revision holds, readRevision) and writes, fetch and secrets (secret answers a promise); the sandbox checks each reach against the grant and throws
ExtensionAccessDenied (with the capability) before the host is called. A
fetch must be HTTPS on the default port to a granted host. The check is on
the calls the sandbox offers — the extension's code runs in the api process,
so the sandbox is a contract for reviewed code, not an isolation boundary.