Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/locator-routes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-ui-react': minor
---

Collections served at their locators. A collection's `publicPrefix` (`'/docs'`, or `'/'` for the site root) serves each document at `{publicPrefix}/{locator}`: `createRoutes()` mounts a catch-all `{publicPrefix}/$` per such collection (the new `collections` spec key drops, limits or replaces them), and the prefix gives the collection a default `path`, so the sitemap, "View" links and page navigation use the same URL. `definition.collections()` carries `publicPrefix`. New exports: `documentPath`, `publicPrefixOf` and `normalizePublicPrefix` from `@tanstack/cms-core`, and `normalizePublicPrefix`, `SHADOWED_LOCATORS_KEY` and the `ShadowedLocators` type from `@tanstack/cms-core/definition`. `tanstackCms()` passes the route segments that shadow each collection's locators to the build as a `define`.

**Breaking:**

- When a commit, approval or scheduled publish changes the URL of a published document (from `path` or `publicPrefix`), the engine adds a permanent redirect from the old URL to the new one in the redirects collection, in the same transaction, and retargets redirects that pointed at the old URL. This applies to existing `path` functions built from the slug too, and only when the CMS has a redirects collection.
- Writes to a `publicPrefix` collection fail with `VALIDATION_FAILED` when the locator's first segment is another route under the prefix (`api` or the admin base path at the site root, an app or plugin route, another collection's prefix). A generated slug steps past it.
- A collection with `publicPrefix: '/'` mounts its catch-all at `/$` in place of `notFound`. `createRoutes()` throws when `notFound` is replaced by your own file, when a catch-all path is another route's, or when a prefix starts inside the admin or API routes. `defineCmsDefinition()` and `defineCms()` throw when two collections share a prefix.
- When the `page` collection has a `publicPrefix`, the home page, site nav and docs sidebar link to its locator URLs instead of `/p/<id>`.
33 changes: 21 additions & 12 deletions .claude/skills/astro-starlight-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,10 @@ rules that need server code attach there by collection name
(`defineCms({ collections, … })`).

One Starlight `docs` collection → one core collection. **Name it `page`** with
a `blocks` field: the public renderer (`/p/$id`), the docs layout, and the
on-page editor are wired to the `page`-with-`blocks` convention. Set
a `blocks` field: the docs layout and the on-page editor are wired to the
`page`-with-`blocks` convention. Give it `publicPrefix: '/docs'` (or `'/'` to
serve the docs at the site root, where Starlight had them): `createRoutes`
mounts a catch-all `/docs/$` that serves each page at its slug. Set
`theme: { variant: 'docs' }`: the docs layout builds the sidebar from the
`page` collection — grouped by the first slug segment, ordered by
`sidebarOrder`, labelled by `sidebarLabel` (falling back to the title) — so a
Expand All @@ -106,21 +108,27 @@ Starlight `autogenerate` sidebar survives without extra code.
| --------------------- | -------------- | ------------------------------------------------- | ------------------------------------------------------ |
| `title` | `title` | `text`, `required: true` | `titleField: 'title'` |
| `description` | `description` | `textarea` | `summaryField: 'description'` (the meta description) |
| (file path) / `slug` | `slug` | `text`, `unique: true` | derived path, e.g. `/start/installation` |
| (file path) / `slug` | `slug` | `slug`, `nested: true`, `required: true` | derived path, e.g. `/start/installation`; `/` = root |
| `sidebar.label` | `sidebarLabel` | `text` | used by the docs sidebar |
| `sidebar.order` | `sidebarOrder` | `number` | used by the docs sidebar |
| `sidebar.badge` | `sidebarBadge` | `text` or `select` | stored; the built-in sidebar doesn't render badges |
| `draft: true` | `published` | `boolean` | inverted: `published = draft !== true` |
| `lastUpdated` | `lastUpdated` | `date` | optional |
| custom `extend` keys | by type | `select`, `multiselect`, `date`, `url`, `json`, … | Zod `enum` → `select`, arrays of enums → `multiselect` |
| body (Markdown) | `blocks` | `blocks` | one `richText` block, `markdown` = the body |
| (old URL) | `redirect` doc | `redirectsCollection()` | `/start/installation/` → `/p/start-installation` |
| (old URL) | `redirect` doc | `redirectsCollection()` | `/start/installation/` → `/docs/start/installation` |

Declare `summaryField: 'description'` on the collection: `cmsHead` reads the
meta description from the summary role. Add a `path` that returns `/` for the root page and `/p/<id>` otherwise, so the
sitemap lists every published page, and add `redirectsCollection()` to `collections` so
the old Starlight URLs (and the cross-page links inside the Markdown) 301 to
the new ones — the catch-all route follows the redirects collection.
meta description from the summary role. The nested slug is the page's
locator (unique per locale; `/` is the collection root), so with
`publicPrefix` each page's URL — in the sidebar, the sitemap, and the admin's
public link — is its slug under the prefix, with no `path` to write. Add
`redirectsCollection()` to `collections` so the old Starlight URLs (and the
cross-page links inside the Markdown) 301 to the new ones — the catch-all
routes follow the redirects collection — and so moving a published page
later leaves a redirect behind. With `publicPrefix: '/'` the old URLs need no
redirects, but a slug can't start with a segment another route owns (`api`,
`content`, `edit`, `p`, …; the engine rejects it).

`template: splash`, `hero`, `banner`, `prev`/`next`, `tableOfContents`, and
i18n `locales` have no direct field mapping → gap report (a `hero` can become
Expand All @@ -138,8 +146,8 @@ renderers module (`defineRenderers({ blocks })`, named by
Copy `scripts/read-frontmatter.mjs`, `scripts/mdx-to-markdown.mjs`, and
`scripts/migrate-starlight.mjs` from this skill into the target app's
`scripts/`. Edit the `CONFIG` block in `migrate-starlight.mjs` if your
collection name, slug, or URL rules differ (`toSlug`, `toId`, `toUrl`,
`REDIRECTS`). Then, pointing at the Starlight source directory:
collection name, slug, or URL rules differ (`toSlug`, `toId`,
`PUBLIC_PREFIX`, `REDIRECTS`). Then, pointing at the Starlight source directory:

```bash
node scripts/migrate-starlight.mjs ../<name>-before --export cms-export.json
Expand Down Expand Up @@ -191,9 +199,10 @@ components themselves are the gap. Self-test: `node scripts/mdx-to-markdown.mjs`
works (`seedContent({ force: true })` or `parseCmsExport` +
`importContent`, then `listAs`/`getAs`); and
`resolveRedirect('/start/installation/')` from `@tanstack/cms-core/server`
returns the new URL. `closeStore()` after each test.
returns the new URL, and `get({ collection: 'page', locator })` finds each
redirect's target. `closeStore()` after each test.
- Live check: `pnpm --filter <app> dev`; the sidebar matches Starlight's,
`/p/home` and `/p/start-installation` render, `curl -I localhost:<port>/start/installation/`
`/docs` and `/docs/start/installation` render, `curl -I localhost:<port>/start/installation/`
answers 301, and `/sitemap.xml` lists the published pages.
- Report counts, not just "done".

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ const OUT = join(here, '..', 'src', 'seed-data.ts')
// ===========================================================================
// CONFIG — the target core collection and how Starlight frontmatter maps onto
// its fields. The body is always one `richText` block (markdown). Named `page`
// so the core's public renderer (/p/:id) and on-page agent — both wired to the
// `page` convention — work unchanged.
// so the docs layout and on-page agent — both wired to the `page` convention —
// work unchanged. The slug is a nested `slug` field, so `createRoutes` serves
// each page at its locator under the collection's publicPrefix.
// ===========================================================================
const TARGET = 'page'

Expand All @@ -58,9 +59,11 @@ const toSlug = (relPath) => {
// with "/" → "-".
const toId = (slug) =>
slug === '/' ? 'home' : slug.replace(/^\//, '').replace(/\//g, '-')
// The page's URL in the new app; the old Starlight URL (= its slug) redirects
// here. REDIRECTS is the redirectsCollection() name (null to skip).
const toUrl = (id) => `/p/${id}`
// The page's URL in the new app — its slug under the collection's
// publicPrefix — where the old Starlight URL (= its slug) redirects.
// REDIRECTS is the redirectsCollection() name (null to skip).
const PUBLIC_PREFIX = '/docs'
const toUrl = (slug) => (slug === '/' ? PUBLIC_PREFIX : PUBLIC_PREFIX + slug)
const REDIRECTS = 'redirect'
// ===========================================================================

Expand Down Expand Up @@ -112,7 +115,7 @@ function main() {
if (REDIRECTS && slug !== '/' && data.draft !== true) {
documents[REDIRECTS][toId(slug)] = {
from: slug,
to: toUrl(toId(slug)),
to: toUrl(slug),
permanent: true,
}
}
Expand Down
6 changes: 3 additions & 3 deletions docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,13 @@ The definition's accessors are derived from it, never written by hand, and retur
| Accessor | Returns |
| --- | --- |
| `adminBasePath()` | The normalized `admin.basePath`: `''` or `/segment` without a trailing slash. |
| `collections()` | `{ name }` for each app and plugin collection, in order. Public URL prefixes come later. |
| `collections()` | `{ name, publicPrefix? }` for each app and plugin collection, in order. `publicPrefix` is normalized (`'/docs'`, or `''` for the site root) and present only when the collection sets one; `createRoutes()` mounts a [catch-all](./routes-and-endpoints#collection-routes) for each. Two collections with the same prefix throw. |
| `pluginRoutes()` | `{ routes, adminRoutes }`, each entry `{ plugin, route }`: the plugins' route nodes, tagged with the plugin name. |
| `routeKeys()` | Every CMS route key (`index`, `content`, `edit`, `review`, `apiV1`, …). The list is `CMS_ROUTE_KEYS`, grouped by surface (`public`, `admin`, `api`); `CmsRouteKey` is its union. |

`definition.config` is the config as written. `isCmsDefinition(value)` tells a definition apart from a config.

`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineInterfaceCollection`, `defineBlock`, `defineFieldType`, `definePluginDefinition`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, and `isBuiltInFieldType`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, and `CmsPluginDefinition`. `definePlugin` stays root-only, because a plugin's runtime half carries ops and event handlers.
`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineInterfaceCollection`, `defineBlock`, `defineFieldType`, `definePluginDefinition`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, `isBuiltInFieldType`, and `normalizePublicPrefix`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, `CmsPluginDefinition`, `LocatorStrategy`, and `LocatorInput`. `definePlugin` stays root-only, because a plugin's runtime half carries ops and event handlers.

```ts validate=type
import { defineCms } from '@tanstack/cms-core'
Expand Down Expand Up @@ -779,7 +779,7 @@ function isFieldVisible(field: Field, siblings: Record<string, JsonValue | undef
| `FieldValidator` | `StandardSchemaV1Like \| FieldValidatorFn`. |
| `FieldValidatorFn` | `(value, { doc, id, collection }) => string \| true \| null \| undefined \| void` (or a Promise of it). A non-empty string is an error. |
| `StandardSchemaV1Like` | The subset of the Standard Schema v1 interface the engine calls (`'~standard'.validate`). |
| `Collection` | A collection definition (`name`, `label`, `titleField`, `fields`, `path?`, `isSingleton?`, `readOnly?`, `storage?`, `migrations?`, `access?`, `hooks?`, `admin?`, and field-role overrides). See [Collection options](../schema/collections-and-fields#collection-options). |
| `Collection` | A collection definition (`name`, `label`, `titleField`, `fields`, `path?`, `publicPrefix?`, `locatorStrategy?`, `isSingleton?`, `readOnly?`, `storage?`, `migrations?`, `access?`, `hooks?`, `admin?`, and field-role overrides). See [Collection options](../schema/collections-and-fields#collection-options). |
| `CollectionAdmin` | `{ columns?: Array<string>; defaultSort?: { field: string; dir?: 'asc' \| 'desc' } }`. |
| `CollectionHooks` | Pre-commit lifecycle hooks: `preValidate`, `postValidate`, `preDelete`, plus the `postRead` response transform. `afterChange` / `afterDelete` are deprecated in favour of `defineEventHandler`. See [Events & Hooks](../architecture/events-and-hooks). |
| `ChangeHookArgs` | `{ doc, id, operation, actor }` — what a pre-commit mutating hook receives. |
Expand Down
12 changes: 10 additions & 2 deletions docs/api/cms-ui-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,11 @@ interface CreateRoutesSpec {
public?: CmsRouteSurfaceSpec<'public'>
admin?: CmsRouteSurfaceSpec<'admin'>
api?: CmsRouteSurfaceSpec<'api'>
// catch-alls at {publicPrefix}/$; default true unless public is false
collections?:
| boolean
| ReadonlyArray<string>
| { [collection: string]: boolean | string }
custom?: ReadonlyArray<VirtualRouteNode>
rootFile?: string
renderers?: string // the app's renderers module, relative to the routes directory
Expand All @@ -492,7 +497,7 @@ type CmsRouteKey =
type CmsSurfaceRouteKey<S extends CmsRouteSurface> // the keys of one surface
```

The virtual route tree for the TanStack Router plugin: the public pages, the admin, and the API routes, plus your own `custom` routes. The admin base path and plugin routes come from the definition. A surface you leave out is mounted, so `createRoutes(definition)` mounts everything. `renderers` is the path of a module that exports `renderers = defineRenderers({ … })`; the CMS routes render blocks with it. It is a path rather than an import so `vite.config.ts` never loads React, and it must exist when the config loads. Route keys are stable public API: renaming or removing one is a breaking change. Keys, paths, and options are listed in the [route table](./routes-and-endpoints#route-table); overriding and adding routes is covered in [Building Pages](../schema/building-pages).
The virtual route tree for the TanStack Router plugin: the public pages, the admin, and the API routes, a catch-all per collection with a `publicPrefix`, plus your own `custom` routes. The admin base path and plugin routes come from the definition. A surface you leave out is mounted, so `createRoutes(definition)` mounts everything. `renderers` is the path of a module that exports `renderers = defineRenderers({ … })`; the CMS routes render blocks with it. It is a path rather than an import so `vite.config.ts` never loads React, and it must exist when the config loads. Route keys are stable public API: renaming or removing one is a breaking change. Keys, paths, and options are listed in the [route table](./routes-and-endpoints#route-table); overriding and adding routes is covered in [Building Pages](../schema/building-pages).

---

Expand All @@ -511,6 +516,9 @@ interface CmsVitePlugin {
config: () => {
ssr: { noExternal: Array<string | RegExp> }
optimizeDeps: { exclude: Array<string> }
// set once createRoutes() has run: the route segments under each
// collection's publicPrefix that its locators can't use
define?: { __TANSTACK_CMS_SHADOWED_LOCATORS__: string }
}
resolveId: (
id: string,
Expand All @@ -521,7 +529,7 @@ interface CmsVitePlugin {
}
```

The CMS packages ship TanStack Start server functions and route files that your app's Start compiler must transform. The plugin keeps `@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, and `@tanstack/cms-client` (plus any `packages` you add) out of Vite's SSR externals and dependency pre-bundling, and bundles `@tanstack/ai*` into SSR alongside them. In SSR, `resolveId` and `load` serve `use-sync-external-store` as ESM on React's own `useSyncExternalStore`, so a production server bundle under pnpm loads one React. `routesDirectory` and `generatedDirectory` are read by `createRoutes()`, which resolves route files when the config loads. When `createRoutes(definition, { renderers })` names a renderers module, the plugin's `load` hook serves the package's `app-renderers` module (which every CMS page route imports) as code that binds it. Add it before `tanstackStart()`.
The CMS packages ship TanStack Start server functions and route files that your app's Start compiler must transform. The plugin keeps `@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, and `@tanstack/cms-client` (plus any `packages` you add) out of Vite's SSR externals and dependency pre-bundling, and bundles `@tanstack/ai*` into SSR alongside them. In SSR, `resolveId` and `load` serve `use-sync-external-store` as ESM on React's own `useSyncExternalStore`, so a production server bundle under pnpm loads one React. `routesDirectory` and `generatedDirectory` are read by `createRoutes()`, which resolves route files when the config loads. In return, the plugin passes the build the route segments that [shadow a collection's locators](./routes-and-endpoints#collection-routes), so writes can reject them. When `createRoutes(definition, { renderers })` names a renderers module, the plugin's `load` hook serves the package's `app-renderers` module (which every CMS page route imports) as code that binds it. Add it before `tanstackStart()`.

```ts validate=type
import { defineConfig } from 'vite'
Expand Down
Loading
Loading