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
15 changes: 15 additions & 0 deletions .changeset/populate-sidecar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-client': minor
---

`get` and `list` populate relations by default. The related documents come back beside each document under `relations`, keyed by relation field path (`author`, `blocks.2.author`), while `doc` keeps the ids. Population is one level deep, so cycles and self-references can't recurse, and it is batched: a page costs one storage read per target collection. Read a relation with the new `related(result, path)` (from `@tanstack/cms-core` and `@tanstack/cms-client`), typed from `Register`. `get`/`list` results are typed with their collection name.

`populate` takes `false` (ids only), `true`, or a list of paths (`['author', 'blocks']`), on every verb that accepts it. The agent tools `list_documents` and `search_documents` return ids unless the agent passes `populate`; `get_document` populates like `get`. The older verbs still populate only when asked.

**Breaking:**

- `get`, `list`, `client.get/list`, the `get`/`list` operations and `get_document` return `relations` unless called with `populate: false`.
- Populated relations skip trashed documents: a relation to one is `null` (dropped from a `many` array), like a missing document.
- A relation into a collection the reader can't read is `null` (or `[]`) instead of being left out of `relations`, so hidden and missing targets look the same.
9 changes: 6 additions & 3 deletions docs/api/cms-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,22 @@ console.log(`${items.length} of ${total} posts`)
The canonical reads, the `get` and `list` operations. They take the same bags as [`getAs` and `listAs`](./cms-core-server#getasctx-options-and-listasctx-options) on the server, and their document types come from `Register`.

```ts validate=type
import { createCmsClient } from '@tanstack/cms-client'
import { createCmsClient, related } from '@tanstack/cms-client'

const cms = createCmsClient({ baseUrl: 'https://cms.example.com', mode: 'live' })

const about = await cms.get({ collection: 'page', locator: 'about' })
const author = about && related(about, 'author')
const first = await cms.list({ collection: 'post', sort: { field: 'title' }, limit: 20 })
const next = first.nextCursor
? await cms.list({ collection: 'post', sort: { field: 'title' }, limit: 20, cursor: first.nextCursor })
: undefined
console.log(about?.doc, first.items.length, next?.total)
console.log(about?.doc, author, first.items.length, next?.total)
```

`get` resolves to `{ id, collection, doc }`, or `null` when the document is missing or the caller can't see it. `list` resolves to `{ items: [{ id, collection, doc }], total, nextCursor? }`. Both are public: anonymous callers read published documents, and callers who may read drafts see the working copy unless the client's `mode` is `live`.
`get` resolves to `{ id, collection, doc, relations }`, or `null` when the document is missing or the caller can't see it. `list` resolves to `{ items: [{ id, collection, doc, relations }], total, nextCursor? }`. Both are public: anonymous callers read published documents, and callers who may read drafts see the working copy unless the client's `mode` is `live`.

Relations are populated by default, one level deep, under `relations` keyed by field path; `doc` keeps the ids. `related(result, path)` reads one back, typed from `Register` (the target's document type, an array for `many: true`, `null` when missing or hidden). Pass `populate: false` for ids only, or an array of paths (`populate: ['author']`) to populate just those.

### `save(options)` and `act(options)`

Expand Down
34 changes: 22 additions & 12 deletions docs/api/cms-core-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,11 @@ type GetOptions = {
collection: string
staged?: boolean // `false`: the committed document, without staged changes
locale?: string // with `locator`: match the document in this locale
populate?: boolean // default false
populate?: PopulateSelection // default true
} & ({ id: string } | { locator: string }) // exactly one

type PopulateSelection = boolean | ReadonlyArray<string> // every relation, none, or these paths

interface ListOptions {
collection?: string // omit to list every collection ctx may read
locale?: string // only documents in this locale
Expand All @@ -152,18 +154,18 @@ interface ListOptions {
limit?: number // 1–500, default 100
offset?: number
cursor?: string // `nextCursor` from the previous page
populate?: boolean // default false
populate?: PopulateSelection // default true
}

interface ReadResult<TDoc = Doc> {
interface ReadResult<TDoc = Doc, C extends string = string> {
id: string
collection: string
collection: C
doc: TDoc
relations?: Record<string, Doc | Array<Doc> | null> // with `populate`
relations?: Record<string, Doc | Array<Doc> | null> // unless `populate: false`
}

interface ListResult<TDoc = Doc> {
items: Array<ReadResult<TDoc>>
interface ListResult<TDoc = Doc, C extends string = string> {
items: Array<ReadResult<TDoc, C>>
total: number
nextCursor?: string
}
Expand Down Expand Up @@ -194,16 +196,24 @@ export async function addToCart(cartId: string, variantId: string) {

A `locator` is the document's slug or its id, with leading slashes ignored. A document that is missing, or that `ctx` can't see, is `null` from `get` and absent from `list`. Documents are redacted for `ctx`, and filtering or sorting on a field it can't read is `FORBIDDEN`. Both functions validate the bag (`getInput`, `listInput` from `@tanstack/cms-core`) and throw `BAD_REQUEST` for an invalid one.

Full-text search stays its own verb, `queryDocumentsAs` with `query`, and `search_documents` for agents. The older read verbs below keep their behaviour.
Both verbs populate relations by default. The related documents come back beside the document, under `relations`, keyed by relation field path (`author`, `seo.image`, `blocks.2.author`); `doc` keeps the ids. Population is one level deep: a related document's own relation fields stay ids, so cycles and self-references can't recurse. A related document is read and redacted as `ctx` reads it. A missing, trashed or hidden target is `null`, or dropped from a `many` array, whether the document or its whole collection is hidden, so a reader can't tell hidden from missing. `list` batches the reads: one storage read per target collection for the whole page, not one per row. Pass `populate: false` for ids only, or an array of paths to populate just those (and the relations under them). `related(result, path)` from `@tanstack/cms-core` reads one relation back, typed from `Register`: a registered relation field gives the target's document type, or an array for `many: true`.

Full-text search stays its own verb, `queryDocumentsAs` with `query`, and `search_documents` for agents. The older read verbs below keep their behaviour, populating only when asked.

```ts validate=type
import { listAs, publicContext } from '@tanstack/cms-core/server'
import { related } from '@tanstack/cms-core'
import { getAs, listAs, publicContext } from '@tanstack/cms-core/server'

export async function postWithAuthor(slug: string) {
const post = await getAs(publicContext(), { collection: 'post', locator: slug })
return post && { post: post.doc, author: related(post, 'author') }
}

export async function allPosts() {
const ids: Array<string> = []
let cursor: string | undefined
do {
const page = await listAs(publicContext(), { collection: 'post', limit: 500, cursor })
const page = await listAs(publicContext(), { collection: 'post', limit: 500, cursor, populate: false })
ids.push(...page.items.map((i) => i.id))
cursor = page.nextCursor
} while (cursor)
Expand All @@ -222,7 +232,7 @@ interface QueryDocumentsOptions {
collections?: Array<string> // restrict a cross-collection query
query?: string // full-text search over title and content
locale?: string
populate?: boolean // attach `relations` to each item
populate?: PopulateSelection // attach `relations` to each item (default false)
where?: Record<string, unknown> | ReadonlyArray<WhereClause> // see "Filters" below
sort?: { field: string; dir?: 'asc' | 'desc' } // a system column or a field path (`seo.score`)
limit?: number
Expand Down Expand Up @@ -399,7 +409,7 @@ function populateRelationsAs(ctx: AccessContext, collectionName: string, doc: Do
function populateRelations(collectionName: string, doc: Doc): Promise<Record<string, Doc | Array<Doc> | null>> // deprecated: reads as publicContext()
```

Resolves every `relation` field of `doc` to the target document(s) `ctx` can read, keyed by field name. A `publicRead` context sees published targets the way it sees published sources. Fields whose target collection `ctx` can't read are left out.
Resolves every `relation` field of `doc` to the target document(s) `ctx` can read, keyed by field name. A missing, trashed or hidden target is `null` (dropped from a `many` array), including one in a collection `ctx` can't read. A `publicRead` context sees published targets the way it sees published sources.

### `listDocumentsAs(ctx, collection?, options?)`

Expand Down
11 changes: 11 additions & 0 deletions docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,17 @@ The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP

These agent tools are separate from the HTTP API operations (`saveDoc`, `getPublicDocument`, …) in [`@tanstack/cms-api`](./cms-api).

### `related(result, path)`

```ts
function related<C extends string, P extends RelationPath<C>>(
result: { collection: C; relations?: Relations },
path: P,
): RelatedAt<C, P>
```

The related document(s) at `path` of a populated `get`/`list` result (see [`getAs` and `listAs`](./cms-core-server#getasctx-options-and-listasctx-options)). Paths are relation field paths as `relations` keys them (`author`, `seo.image`, `blocks.2.author`). For a top-level relation field of a registered collection, the result is typed as the target's document (an array for `many: true`). It is `null` when the path wasn't populated, or the target is missing or hidden. `@tanstack/cms-client` exports the same function.

---

## Events
Expand Down
4 changes: 2 additions & 2 deletions docs/api/routes-and-endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,8 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/
| Operation | Method | Access | Input | Result |
| --- | --- | --- | --- | --- |
| `getAuthSession` | GET | public | `{}` | The caller's `CmsSession` plus `ai: { text, image }` capabilities. |
| `get` | GET | public | `{ collection, id \| locator, staged?, locale?, populate? }` | `{ id, collection, doc, relations? }` or `null`. The canonical read ([`getAs`](./cms-core-server#getasctx-options-and-listasctx-options)): published only, except for callers who may read drafts of the collection and don't ask for `live`; drafts are read with staged changes overlaid, unless `staged` is `false`. |
| `list` | GET | public | `{ collection?, locale?, where?, sort?: { field, dir? }, limit? (1–500, default 100), offset?, cursor?, populate? }` | `{ items: [{ id, collection, doc, relations? }], total, nextCursor? }`. The canonical list, with the same visibility as `get`. |
| `get` | GET | public | `{ collection, id \| locator, staged?, locale?, populate? }` | `{ id, collection, doc, relations? }` or `null`. The canonical read ([`getAs`](./cms-core-server#getasctx-options-and-listasctx-options)): published only, except for callers who may read drafts of the collection and don't ask for `live`; drafts are read with staged changes overlaid, unless `staged` is `false`. Relations are populated one level deep unless `populate` is `false` (or a list of paths). |
| `list` | GET | public | `{ collection?, locale?, where?, sort?: { field, dir? }, limit? (1–500, default 100), offset?, cursor?, populate? }` | `{ items: [{ id, collection, doc, relations? }], total, nextCursor? }`. The canonical list, with the same visibility and populate default as `get`. |
| `save` | POST | `content.write` | `{ collection, id, doc, create?, publish?, expectedRevision?, expectedPendingVersion?, instruction? }` | `{ id, collection, doc, state: { label, published, revision, changeSet }, availableActions }`. The canonical write ([`saveAs`](./cms-core-server#saveasctx-options-and-actasctx-options)): `doc` is a patch merged onto the caller's working copy. It commits for publishers (a draft of a published document unless `publish` is set) and is submitted for review otherwise. `CONFLICT` for a stale `expectedRevision` / `expectedPendingVersion`, or `create` on an existing id. |
| `act` | POST | `content.read` | `{ collection, id, action, publishAt?: string \| null, reason?, expectedVersion? }` | As `save`, with `doc` `null` once the document is gone. Runs an action the document's strategy offers the caller (`FORBIDDEN` otherwise); `edit`, `submit`, `draft` and `import` are `save`'s (`BAD_REQUEST`). |
| `listDocumentSummaries` | GET | `content.read` | `{ collection, search?, status?: 'all' \| 'published' \| 'draft' \| 'scheduled', locale?, ids? (≤ 500), sort?: { field, dir? }, limit? (1–500, default 50), offset?, columns? (≤ 20) }` | `{ items: DocSummary[], total }` |
Expand Down
29 changes: 29 additions & 0 deletions docs/deployment/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,35 @@ copy. `get` takes `staged: false` for that, so
`readDocumentAs(ctx, collection, id)` in an `edit` or system context becomes
`(await getAs(ctx, { collection, id, staged: false, populate: false }))?.doc ?? null`.

### 28. `get` and `list` populate relations by default

`get` and `list` (on the server, over HTTP and Start, on the client, and the
`get_document` tool) return the related documents beside each document,
under `relations`, keyed by relation field path. `doc` keeps the ids.
Population is one level deep and batched per target collection. Read a
relation with `related(result, path)`, typed from `Register`:

```ts
import { related } from '@tanstack/cms-core'

const post = await cmsAs(cms, ctx).get({ collection: 'post', locator: 'hello' })
const author = post && related(post, 'author')
const ids = await cmsAs(cms, ctx).list({ collection: 'post', populate: false })
```

Pass `populate: false` for ids only, or a list of paths
(`populate: ['author']`). The agent tools `list_documents` and
`search_documents` stay ids-only unless the agent passes `populate`. The
older verbs still populate only when asked.

- **Populated relations skip trashed targets.** A relation to a trashed
document is `null` (dropped from a `many` array), like a missing one; it
used to come back with its `deletedAt` stamp.
- **A relation into a collection the reader can't read is `null`** (or
`[]`) instead of being left out of `relations`.
- **`populate` takes a list of paths** as well as a boolean, on every verb
that accepts it.

## Versioning policy

From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The
Expand Down
8 changes: 4 additions & 4 deletions docs/mcp/operations-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,10 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/
| Tool | Kind | Behavior |
| --- | --- | --- |
| `list_collections` | read | Collections and their fields |
| `list_documents` | read | The canonical `list`: documents of one collection (or every readable one) with `locale`, `where`, `sort`, paging (`limit`, `offset`, `cursor`) and `populate`. Returns `{ items: [{ id, collection, doc }], total, nextCursor? }` |
| `get_document` | read | The canonical `get`: one document by `id` or `locator`, including staged creates and updates in the agent's `edit` mode. Returns `{ id, collection, doc }` or `null` |
| `list_documents` | read | The canonical `list`: documents of one collection (or every readable one) with `locale`, `where`, `sort`, paging (`limit`, `offset`, `cursor`) and `populate` (default `false`: relation fields stay ids). Returns `{ items: [{ id, collection, doc, relations? }], total, nextCursor? }` |
| `get_document` | read | The canonical `get`: one document by `id` or `locator`, including staged creates and updates in the agent's `edit` mode, with its relations populated (`populate: false` for ids only). Returns `{ id, collection, doc, relations }` or `null` |
| `read_document` | read | Deprecated, use `get_document`. One document by id, including staged creates and updates; `NOT_FOUND` when missing |
| `search_documents` | read | Full-text search and structured `where` / `sort` queries with collection, locale, a read `mode` (`live` for published only; never wider than the caller's), and pagination (`limit`, `offset`, `cursor`) |
| `search_documents` | read | Full-text search and structured `where` / `sort` queries with collection, locale, a read `mode` (`live` for published only; never wider than the caller's), pagination (`limit`, `offset`, `cursor`), and `populate` (default `false`) |
| `list_revisions` | read | Revision history, newest first |
| `list_translations` | read | A document's locale variants |
| `save_document` | write | Stage a new document or a change: `doc` holds only the fields to change, `create: true` refuses an existing id. Returns `{ id, collection, doc, state, availableActions }` |
Expand All @@ -178,7 +178,7 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/
| `restore_revision` | write | Stage restoring a revision |
| `schedule_document` | write | Stage setting or clearing `publishAt` |

The read tools come from the canonical read vocabulary, `readVerbs`: each verb's agent tool name is derived as `<verb>_<noun>` (`get` → `get_document`, `list` → `list_documents`, see `agentToolName`), and its input schema is the verb's bag (`getInput`, `listInput`), the same one the `get` and `list` operations, `client.get/list` and `cmsAs(cms, ctx).get/list` take. Full-text search stays its own tool, `search_documents`.
The read tools come from the canonical read vocabulary, `readVerbs`: each verb's agent tool name is derived as `<verb>_<noun>` (`get` → `get_document`, `list` → `list_documents`, see `agentToolName`), and its input schema is the verb's bag (`getInput`, `listInput`), the same one the `get` and `list` operations, `client.get/list` and `cmsAs(cms, ctx).get/list` take. The one difference is the populate default: `get_document` populates like `get`, while `list_documents` and `search_documents` return ids unless the agent asks (`populate: true`, or the paths it needs), to keep tool results small. Full-text search stays its own tool, `search_documents`.

The write tool comes from the canonical write vocabulary, `writeVerbs`, the same way: `save` → `save_document`, with the `saveInput` bag the `save` operation, `client.save` and `cmsAs(cms, ctx).save` take. An agent's save is always the strategy's `submit`, so it is staged for review. `act` (approve, reject, discard, …) is not an agent tool: review decisions stay with people.

Expand Down
1 change: 1 addition & 0 deletions packages/api/src/ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,7 @@ const _ops = {
limit: input.limit,
offset: input.offset,
cursor: input.cursor,
populate: false,
})
return {
items: result.items.map((i) => ({
Expand Down
Loading
Loading