Skip to content

Commit 282f2a9

Browse files
jherrcursoragent
andauthored
feat!: get/list populate relations by default — depth 1, batched, cycle-safe, with typed related() (3b) (#35) (#35)
Chain step 18 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: Cursor Agent <cursoragent@cursor.com>
1 parent 1bd8f7e commit 282f2a9

24 files changed

Lines changed: 677 additions & 166 deletions

‎.changeset/populate-sidecar.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@tanstack/cms-core': minor
3+
'@tanstack/cms-api': minor
4+
'@tanstack/cms-client': minor
5+
---
6+
7+
`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.
8+
9+
`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.
10+
11+
**Breaking:**
12+
13+
- `get`, `list`, `client.get/list`, the `get`/`list` operations and `get_document` return `relations` unless called with `populate: false`.
14+
- Populated relations skip trashed documents: a relation to one is `null` (dropped from a `many` array), like a missing document.
15+
- 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.

‎docs/api/cms-client.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,19 +70,22 @@ console.log(`${items.length} of ${total} posts`)
7070
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`.
7171

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

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

7777
const about = await cms.get({ collection: 'page', locator: 'about' })
78+
const author = about && related(about, 'author')
7879
const first = await cms.list({ collection: 'post', sort: { field: 'title' }, limit: 20 })
7980
const next = first.nextCursor
8081
? await cms.list({ collection: 'post', sort: { field: 'title' }, limit: 20, cursor: first.nextCursor })
8182
: undefined
82-
console.log(about?.doc, first.items.length, next?.total)
83+
console.log(about?.doc, author, first.items.length, next?.total)
8384
```
8485

85-
`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`.
86+
`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`.
87+
88+
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.
8689

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

‎docs/api/cms-core-server.md‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,11 @@ type GetOptions = {
141141
collection: string
142142
staged?: boolean // `false`: the committed document, without staged changes
143143
locale?: string // with `locator`: match the document in this locale
144-
populate?: boolean // default false
144+
populate?: PopulateSelection // default true
145145
} & ({ id: string } | { locator: string }) // exactly one
146146
147+
type PopulateSelection = boolean | ReadonlyArray<string> // every relation, none, or these paths
148+
147149
interface ListOptions {
148150
collection?: string // omit to list every collection ctx may read
149151
locale?: string // only documents in this locale
@@ -152,18 +154,18 @@ interface ListOptions {
152154
limit?: number // 1–500, default 100
153155
offset?: number
154156
cursor?: string // `nextCursor` from the previous page
155-
populate?: boolean // default false
157+
populate?: PopulateSelection // default true
156158
}
157159
158-
interface ReadResult<TDoc = Doc> {
160+
interface ReadResult<TDoc = Doc, C extends string = string> {
159161
id: string
160-
collection: string
162+
collection: C
161163
doc: TDoc
162-
relations?: Record<string, Doc | Array<Doc> | null> // with `populate`
164+
relations?: Record<string, Doc | Array<Doc> | null> // unless `populate: false`
163165
}
164166
165-
interface ListResult<TDoc = Doc> {
166-
items: Array<ReadResult<TDoc>>
167+
interface ListResult<TDoc = Doc, C extends string = string> {
168+
items: Array<ReadResult<TDoc, C>>
167169
total: number
168170
nextCursor?: string
169171
}
@@ -194,16 +196,24 @@ export async function addToCart(cartId: string, variantId: string) {
194196

195197
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.
196198

197-
Full-text search stays its own verb, `queryDocumentsAs` with `query`, and `search_documents` for agents. The older read verbs below keep their behaviour.
199+
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`.
200+
201+
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.
198202

199203
```ts validate=type
200-
import { listAs, publicContext } from '@tanstack/cms-core/server'
204+
import { related } from '@tanstack/cms-core'
205+
import { getAs, listAs, publicContext } from '@tanstack/cms-core/server'
206+
207+
export async function postWithAuthor(slug: string) {
208+
const post = await getAs(publicContext(), { collection: 'post', locator: slug })
209+
return post && { post: post.doc, author: related(post, 'author') }
210+
}
201211
202212
export async function allPosts() {
203213
const ids: Array<string> = []
204214
let cursor: string | undefined
205215
do {
206-
const page = await listAs(publicContext(), { collection: 'post', limit: 500, cursor })
216+
const page = await listAs(publicContext(), { collection: 'post', limit: 500, cursor, populate: false })
207217
ids.push(...page.items.map((i) => i.id))
208218
cursor = page.nextCursor
209219
} while (cursor)
@@ -222,7 +232,7 @@ interface QueryDocumentsOptions {
222232
collections?: Array<string> // restrict a cross-collection query
223233
query?: string // full-text search over title and content
224234
locale?: string
225-
populate?: boolean // attach `relations` to each item
235+
populate?: PopulateSelection // attach `relations` to each item (default false)
226236
where?: Record<string, unknown> | ReadonlyArray<WhereClause> // see "Filters" below
227237
sort?: { field: string; dir?: 'asc' | 'desc' } // a system column or a field path (`seo.score`)
228238
limit?: number
@@ -399,7 +409,7 @@ function populateRelationsAs(ctx: AccessContext, collectionName: string, doc: Do
399409
function populateRelations(collectionName: string, doc: Doc): Promise<Record<string, Doc | Array<Doc> | null>> // deprecated: reads as publicContext()
400410
```
401411

402-
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.
412+
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.
403413

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

‎docs/api/cms-core.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,17 @@ The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP
813813
814814
These agent tools are separate from the HTTP API operations (`saveDoc`, `getPublicDocument`, …) in [`@tanstack/cms-api`](./cms-api).
815815
816+
### `related(result, path)`
817+
818+
```ts
819+
function related<C extends string, P extends RelationPath<C>>(
820+
result: { collection: C; relations?: Relations },
821+
path: P,
822+
): RelatedAt<C, P>
823+
```
824+
825+
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.
826+
816827
---
817828

818829
## Events

‎docs/api/routes-and-endpoints.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/
237237
| Operation | Method | Access | Input | Result |
238238
| --- | --- | --- | --- | --- |
239239
| `getAuthSession` | GET | public | `{}` | The caller's `CmsSession` plus `ai: { text, image }` capabilities. |
240-
| `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`. |
241-
| `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`. |
240+
| `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). |
241+
| `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`. |
242242
| `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. |
243243
| `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`). |
244244
| `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 }` |

‎docs/deployment/upgrading.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,35 @@ copy. `get` takes `staged: false` for that, so
487487
`readDocumentAs(ctx, collection, id)` in an `edit` or system context becomes
488488
`(await getAs(ctx, { collection, id, staged: false, populate: false }))?.doc ?? null`.
489489

490+
### 28. `get` and `list` populate relations by default
491+
492+
`get` and `list` (on the server, over HTTP and Start, on the client, and the
493+
`get_document` tool) return the related documents beside each document,
494+
under `relations`, keyed by relation field path. `doc` keeps the ids.
495+
Population is one level deep and batched per target collection. Read a
496+
relation with `related(result, path)`, typed from `Register`:
497+
498+
```ts
499+
import { related } from '@tanstack/cms-core'
500+
501+
const post = await cmsAs(cms, ctx).get({ collection: 'post', locator: 'hello' })
502+
const author = post && related(post, 'author')
503+
const ids = await cmsAs(cms, ctx).list({ collection: 'post', populate: false })
504+
```
505+
506+
Pass `populate: false` for ids only, or a list of paths
507+
(`populate: ['author']`). The agent tools `list_documents` and
508+
`search_documents` stay ids-only unless the agent passes `populate`. The
509+
older verbs still populate only when asked.
510+
511+
- **Populated relations skip trashed targets.** A relation to a trashed
512+
document is `null` (dropped from a `many` array), like a missing one; it
513+
used to come back with its `deletedAt` stamp.
514+
- **A relation into a collection the reader can't read is `null`** (or
515+
`[]`) instead of being left out of `relations`.
516+
- **`populate` takes a list of paths** as well as a boolean, on every verb
517+
that accepts it.
518+
490519
## Versioning policy
491520

492521
From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The

‎docs/mcp/operations-registry.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,10 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/
164164
| Tool | Kind | Behavior |
165165
| --- | --- | --- |
166166
| `list_collections` | read | Collections and their fields |
167-
| `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? }` |
168-
| `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` |
167+
| `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? }` |
168+
| `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` |
169169
| `read_document` | read | Deprecated, use `get_document`. One document by id, including staged creates and updates; `NOT_FOUND` when missing |
170-
| `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`) |
170+
| `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`) |
171171
| `list_revisions` | read | Revision history, newest first |
172172
| `list_translations` | read | A document's locale variants |
173173
| `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 }` |
@@ -178,7 +178,7 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/
178178
| `restore_revision` | write | Stage restoring a revision |
179179
| `schedule_document` | write | Stage setting or clearing `publishAt` |
180180

181-
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`.
181+
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`.
182182

183183
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.
184184

‎packages/api/src/ops.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,7 @@ const _ops = {
664664
limit: input.limit,
665665
offset: input.offset,
666666
cursor: input.cursor,
667+
populate: false,
667668
})
668669
return {
669670
items: result.items.map((i) => ({

0 commit comments

Comments
 (0)