Headless CMS core: typed collections and singletons with drafts, revisions, scheduling, locales and preview
Install
genpm add @core/contentWhat you get
- Source in src/lib/content/, 11 files. (46.4 kB)
- AI rules in src/lib/content/AGENTS.md, plus IDE rule files.
- Env vars added to .env.example: CONTENT_PREVIEW_SECRET, CONTENT_DEFAULT_LOCALE.
- Resolves @core/contracts, @core/db, @core/jobs for you.
README
This package has no README.
This is exactly what your AI reads when it works in src/lib/content. Nothing else is added to its context.
@core/content — rules for AI agents
Purpose
Content model of the CMS: collections (pages, posts, FAQs) and singletons (home, footer, settings) defined with zod,
stored in Postgres with drafts separate from published data, revisions, scheduled publishing (@core/jobs), locales
with fallback and signed preview. Implements ContentSource, sitemap/search sources and AdminResource
(@core/contracts). No UI: @core/admin renders the editor from contentAdminResource().
Map
index.ts— public API.registry.ts—defineCollection,defineSingleton.entries.ts— create,saveDraft,publish,schedulePublish,unpublish,archive, revisions,seedEntry,migrateEntries.read.ts—getEntry,listEntries,getSingleton,reader(collection)(typed).preview.ts— preview tokens.listEntries/countEntriesalso take nestedwherekeys ({ 'series.slug': 'basics' }) and apublishedAtrange (publishedFrominclusive,publishedBeforeexclusive): filter in SQL instead of fetching and filtering in memory.sources.ts—contentSitemapSource,contentSearchSource.admin.ts—contentAdminResource.adapters/next.ts—previewRoute(draftMode, cookies),exitPreviewRoute(draftMode).
Integration
- Env:
CONTENT_PREVIEW_SECRET(≥ 32 chars), optionalCONTENT_DEFAULT_LOCALE(defaulten). Migrations as insrc/lib/db/AGENTS.md. - Define the site's content in one project file imported everywhere,
src/genpm/content.ts:export const pages = defineCollection('pages', { schema: z.object({ title: z.string(), body: z.string() }) }). - Read in pages:
const page = await reader(pages).get(slug, { locale, draft: isDraftMode })(404 if null). - Preview:
app/api/preview/route.tswithexport const GET = previewRoute(draftMode, cookies)(both fromnext/headers) andapp/api/exit-preview/route.tswithexport const GET = exitPreviewRoute(draftMode). Passingcookiesmakes Next's draft-mode cookie expire with the token (admin links: 600 s); without it, draft mode lasts the whole browser session. - Scheduled publishing needs the @core/jobs cron endpoint running.
- Register
contentAdminResource('pages')insrc/genpm/admin.ts, and the sources insrc/genpm/seo.ts/search.ts. - Verify: create, publish, and read an entry; drafts must not appear without draft mode.
Retrofit: make an existing site editable
Work page by page, one commit per page, without changing markup or styles:
- List every visible literal (texts, image URLs, links) of the page.
- Group them: one singleton per page (
home,about). Repeated items of one page (features, prices, FAQs) are alistfield inside that singleton (ordered, one edit screen); use a collection only when the items have their own pages or are shared by several pages. - Define the schema with the current values' shape and call
seedEntrywith the current values (idempotent; it only creates, so it never overwrites editor changes — and a field added later to the seed does not reach an already-seeded database: set it in the admin or withsaveDraft+publish), e.g. from a seed script. - Replace literals with typed reads; keep a fallback only where a value is optional.
- Render before/after and compare the HTML: it must be identical. Next 15 streams metadata into
<body>for browsers oncegenerateMetadataawaits data;htmlLimitedBots: /.*/innext.config(kit-cms Integration 1) keeps it in<head>. - Grant editors the new singletons:
defineRolewith<singleton>:*(e.g.home:*,site_settings:*) — the defaulteditorrole only covers the kit's collections.
Conventions
- Field names in admin resources are
data.<field>; slugs are lowercasea-z0-9-with up to 6/segments. - Changing a schema incompatibly requires
migrateEntries; never edit jsonb by hand. - Permissions:
<collection>:read|create|update|delete|publish,:ownfor authors (owner =authorId). - Public reads never pass
draft: trueunless draft mode came from a verified preview token. - A preview link is not bound to its entry: Next's draft mode is browser-wide, so while it lasts (until the token
expires, when
cookiesis passed) that browser sees the drafts of every entry of every collection. Only share preview links with people who may see unpublished content;/api/exit-previewends it early. - Admin
updaterenames and saves the draft in one transaction: invalid data never leaves the entry renamed.
Don't
- Don't write to
content_entriesdirectly; publishing must go throughpublish()(validation + revision). - Don't put secrets or personal data in content; it is public once published.
- Don't redirect previews to absolute URLs;
safePathrejects them.
# @core/content — rules for AI agents
## Purpose
Content model of the CMS: collections (pages, posts, FAQs) and singletons (home, footer, settings) defined with zod,
stored in Postgres with drafts separate from published data, revisions, scheduled publishing (@core/jobs), locales
with fallback and signed preview. Implements `ContentSource`, sitemap/search sources and `AdminResource`
(@core/contracts). No UI: @core/admin renders the editor from `contentAdminResource()`.
## Map
- `index.ts` — public API. `registry.ts` — `defineCollection`, `defineSingleton`. `entries.ts` — create, `saveDraft`,
`publish`, `schedulePublish`, `unpublish`, `archive`, revisions, `seedEntry`, `migrateEntries`.
- `read.ts` — `getEntry`, `listEntries`, `getSingleton`, `reader(collection)` (typed). `preview.ts` — preview tokens.
`listEntries`/`countEntries` also take nested `where` keys (`{ 'series.slug': 'basics' }`) and a `publishedAt` range
(`publishedFrom` inclusive, `publishedBefore` exclusive): filter in SQL instead of fetching and filtering in memory.
- `sources.ts` — `contentSitemapSource`, `contentSearchSource`. `admin.ts` — `contentAdminResource`.
- `adapters/next.ts` — `previewRoute(draftMode, cookies)`, `exitPreviewRoute(draftMode)`.
## Integration
1. Env: `CONTENT_PREVIEW_SECRET` (≥ 32 chars), optional `CONTENT_DEFAULT_LOCALE` (default `en`). Migrations as in `src/lib/db/AGENTS.md`.
2. Define the site's content in one project file imported everywhere, `src/genpm/content.ts`:
`export const pages = defineCollection('pages', { schema: z.object({ title: z.string(), body: z.string() }) })`.
3. Read in pages: `const page = await reader(pages).get(slug, { locale, draft: isDraftMode })` (404 if null).
4. Preview: `app/api/preview/route.ts` with `export const GET = previewRoute(draftMode, cookies)` (both from
`next/headers`) and `app/api/exit-preview/route.ts` with `export const GET = exitPreviewRoute(draftMode)`.
Passing `cookies` makes Next's draft-mode cookie expire with the token (admin links: 600 s); without it, draft mode
lasts the whole browser session.
5. Scheduled publishing needs the @core/jobs cron endpoint running.
6. Register `contentAdminResource('pages')` in `src/genpm/admin.ts`, and the sources in `src/genpm/seo.ts` / `search.ts`.
7. Verify: create, publish, and read an entry; drafts must not appear without draft mode.
### Retrofit: make an existing site editable
Work page by page, one commit per page, without changing markup or styles:
1. List every visible literal (texts, image URLs, links) of the page.
2. Group them: one singleton per page (`home`, `about`). Repeated items of one page (features, prices, FAQs) are a
`list` field inside that singleton (ordered, one edit screen); use a collection only when the items have their own
pages or are shared by several pages.
3. Define the schema with the current values' shape and call `seedEntry` with the current values (idempotent; it
only creates, so it never overwrites editor changes — and a field added later to the seed does not reach an
already-seeded database: set it in the admin or with `saveDraft` + `publish`), e.g. from a seed script.
4. Replace literals with typed reads; keep a fallback only where a value is optional.
5. Render before/after and compare the HTML: it must be identical. Next 15 streams metadata into `<body>` for browsers
once `generateMetadata` awaits data; `htmlLimitedBots: /.*/` in `next.config` (kit-cms Integration 1) keeps it in `<head>`.
6. Grant editors the new singletons: `defineRole` with `<singleton>:*` (e.g. `home:*`, `site_settings:*`) — the
default `editor` role only covers the kit's collections.
## Conventions
- Field names in admin resources are `data.<field>`; slugs are lowercase `a-z0-9-` with up to 6 `/` segments.
- Changing a schema incompatibly requires `migrateEntries`; never edit jsonb by hand.
- Permissions: `<collection>:read|create|update|delete|publish`, `:own` for authors (owner = `authorId`).
- Public reads never pass `draft: true` unless draft mode came from a verified preview token.
- A preview link is not bound to its entry: Next's draft mode is browser-wide, so while it lasts (until the token
expires, when `cookies` is passed) that browser sees the drafts of every entry of every collection. Only share
preview links with people who may see unpublished content; `/api/exit-preview` ends it early.
- Admin `update` renames and saves the draft in one transaction: invalid data never leaves the entry renamed.
## Don't
- Don't write to `content_entries` directly; publishing must go through `publish()` (validation + revision).
- Don't put secrets or personal data in content; it is public once published.
- Don't redirect previews to absolute URLs; `safePath` rejects them.
The exact tree that will be injected, after .genpmignore. Pinned to
// Adaptador Next.js para la vista previa de borradores, sin importar `next`:
// app/api/preview/route.ts:
// import { cookies, draftMode } from 'next/headers';
// import { previewRoute } from '@/lib/content/adapters/next';
// export const GET = previewRoute(draftMode, cookies);
// app/api/exit-preview/route.ts: `export const GET = exitPreviewRoute(draftMode);`
// En la página: `const { isEnabled } = await draftMode(); await getEntry('pages', slug, { draft: isEnabled })`.
// El modo borrador de Next es de todo el navegador: mientras dure, se ven los borradores de cualquier entrada. Por eso,
// con `cookies`, la cookie de Next se acorta para que caduque a la vez que el token (TTL del panel: 600 s).
import { ContentError, safePath, verifyPreviewToken } from '../index.ts';
type DraftMode = () => Promise<{ enable(): void; disable(): void }> | { enable(): void; disable(): void };
type CookieStore = {
get(name: string): { value: string } | undefined;
set(cookie: { name: string; value: string; httpOnly: boolean; sameSite: 'lax' | 'none'; secure: boolean; path: string; maxAge: number }): unknown;
};
type Cookies = () => Promise<CookieStore> | CookieStore;
/** Cookie con la que Next.js 15 activa el modo borrador (`COOKIE_NAME_PRERENDER_BYPASS`). */
export const DRAFT_MODE_COOKIE = '__prerender_bypass';
/**
* Vuelve a escribir la cookie del modo borrador con los mismos atributos que pone Next (`draft-mode-provider.js`) y
* `maxAge` hasta la caducidad del token; sin él sería una cookie de sesión sin fin.
*/
async function expireDraftModeWith(cookies: Cookies, exp: number): Promise<void> {
const store = await cookies();
const value = store.get(DRAFT_MODE_COOKIE)?.value;
if (!value) return;
const dev = process.env.NODE_ENV === 'development';
store.set({
name: DRAFT_MODE_COOKIE,
value,
httpOnly: true,
sameSite: dev ? 'lax' : 'none',
secure: !dev,
path: '/',
maxAge: Math.max(1, Math.floor((exp - Date.now()) / 1000)),
});
}
/**
* GET `/api/preview?token=…` → activa el modo borrador y redirige a la ruta firmada en el token. Con `cookies`
* (recomendado) el modo borrador caduca con el token.
*/
export function previewRoute(draftMode: DraftMode, cookies?: Cookies) {
return async (req: Request): Promise<Response> => {
try {
const claims = await verifyPreviewToken(new URL(req.url).searchParams.get('token'));
(await draftMode()).enable();
if (cookies) await expireDraftModeWith(cookies, claims.exp);
return new Response(null, { status: 307, headers: { location: claims.path, 'cache-control': 'no-store' } });
} catch (e) {
if (e instanceof ContentError) return Response.json({ error: 'invalid_token' }, { status: 401 });
throw e;
}
};
}
const safeOrRoot = (path: string) => {
try {
return safePath(path);
} catch {
return '/';
}
};
/** GET `/api/exit-preview?path=/x` → desactiva el modo borrador y vuelve a `path` (solo rutas del propio sitio). */
export function exitPreviewRoute(draftMode: DraftMode) {
return async (req: Request): Promise<Response> => {
(await draftMode()).disable();
const location = safeOrRoot(new URL(req.url).searchParams.get('path') ?? '/');
return new Response(null, { status: 307, headers: { location, 'cache-control': 'no-store' } });
};
}
This package declares no MCP servers.
| Version | Commit | Published | Scan |
|---|---|---|---|
| 1.1.0 | 23978fe | 2 hours ago | scan passed |
- npm
- zod ^4.0.0
- proposed
- GenPM proposes the npm command and runs it only if you say yes.
- Used by (2)
- @core/blog ^1.1.0@core/forms ^1.0.0
- scan
- scan passed · 0 findings
- commit
- v1.1.0 → 23978fee0b532853e3112d070817a3e274c4ed49 · verified after fetch
- scripts
- None. GenPM never runs package code.
- license
- MIT
- Quality
- 100/100
- Recognized licensepassed
- AGENTS.md explains its purposepassed
- AGENTS.md has integration stepspassed
- AGENTS.md lists conventions or don'tspassed
- Includes testspassed
- Security scan passedpassed
- Released in the last 6 monthspassed
- Verified publisherpassed
- Summary and keywordspassed
- report
- See something wrong?