From 7bfcfe54592a89d72d951563bc05d9800e6527b2 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 6 Nov 2026 14:23:37 +0000 Subject: [PATCH] =?UTF-8?q?feat!:=20get/list=20populate=20relations=20by?= =?UTF-8?q?=20default=20=E2=80=94=20depth=201,=20batched,=20cycle-safe,=20?= =?UTF-8?q?with=20typed=20related()=20(3b)=20(#35)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: jherr --- .changeset/populate-sidecar.md | 15 ++ docs/api/cms-client.md | 9 +- docs/api/cms-core-server.md | 34 +-- docs/api/cms-core.md | 11 + docs/api/routes-and-endpoints.md | 4 +- docs/deployment/upgrading.md | 29 +++ docs/mcp/operations-registry.md | 8 +- packages/api/src/ops.ts | 1 + packages/api/tests/read-verbs.test.ts | 21 +- packages/client/src/client.ts | 27 ++- packages/client/src/index.ts | 1 + packages/client/tests/client.test.ts | 4 + packages/client/tests/register.test.ts | 44 +++- packages/core/src/index.ts | 3 + packages/core/src/ops.ts | 67 ++++-- packages/core/src/related.ts | 57 +++++ packages/core/src/server/cms-as.ts | 4 +- packages/core/src/server/cms-ops.ts | 4 +- packages/core/src/server/store/query.ts | 21 +- packages/core/src/server/store/read.ts | 219 +++++++++++++------- packages/core/src/server/store/verbs.ts | 26 ++- packages/core/tests/access-context.test.ts | 2 +- packages/core/tests/field-access.test.ts | 2 +- packages/core/tests/read-verbs.test.ts | 230 +++++++++++++++++++-- 24 files changed, 677 insertions(+), 166 deletions(-) create mode 100644 .changeset/populate-sidecar.md create mode 100644 packages/core/src/related.ts diff --git a/.changeset/populate-sidecar.md b/.changeset/populate-sidecar.md new file mode 100644 index 00000000..edb6d7d1 --- /dev/null +++ b/.changeset/populate-sidecar.md @@ -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. diff --git a/docs/api/cms-client.md b/docs/api/cms-client.md index 31480390..44aa9af9 100644 --- a/docs/api/cms-client.md +++ b/docs/api/cms-client.md @@ -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)` diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 8e0b2f2a..fcedad83 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -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 // 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 @@ -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 { +interface ReadResult { id: string - collection: string + collection: C doc: TDoc - relations?: Record | null> // with `populate` + relations?: Record | null> // unless `populate: false` } -interface ListResult { - items: Array> +interface ListResult { + items: Array> total: number nextCursor?: string } @@ -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 = [] 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) @@ -222,7 +232,7 @@ interface QueryDocumentsOptions { collections?: Array // 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 | ReadonlyArray // see "Filters" below sort?: { field: string; dir?: 'asc' | 'desc' } // a system column or a field path (`seo.score`) limit?: number @@ -399,7 +409,7 @@ function populateRelationsAs(ctx: AccessContext, collectionName: string, doc: Do function populateRelations(collectionName: string, doc: Doc): Promise | 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?)` diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 494dd4a7..9dce8f85 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -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>( + result: { collection: C; relations?: Relations }, + path: P, +): RelatedAt +``` + +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 diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index dba38b78..2f57df31 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -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 }` | diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index e2bbcaa0..798b92a3 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -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 diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 7f60e017..1b2fdbdb 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -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 }` | @@ -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 `_` (`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 `_` (`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. diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 9e55025c..54190307 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -664,6 +664,7 @@ const _ops = { limit: input.limit, offset: input.offset, cursor: input.cursor, + populate: false, }) return { items: result.items.map((i) => ({ diff --git a/packages/api/tests/read-verbs.test.ts b/packages/api/tests/read-verbs.test.ts index ac08eb04..aac334f0 100644 --- a/packages/api/tests/read-verbs.test.ts +++ b/packages/api/tests/read-verbs.test.ts @@ -49,6 +49,7 @@ const collections: Partial = { type: 'text', access: { read: ['editor', 'admin'] }, }, + { name: 'page', label: 'Page', type: 'relation', collection: 'page' }, ], }, { @@ -62,14 +63,15 @@ const collections: Partial = { } async function seed() { + await commitDocument('page', 'about', { title: 'About', published: true }) await commitDocument('post', 'hello', { title: 'Hello', slug: 'hello-world', internalNotes: 'secret', + page: 'about', published: true, }) await commitDocument('post', 'draft', { title: 'Draft' }) - await commitDocument('page', 'about', { title: 'About', published: true }) await stageWrite({ collection: 'post', docId: 'hello', @@ -86,7 +88,7 @@ describe('get and list over HTTP', () => { const all = allOps() for (const verb of readVerbs) { expect(all[verb.name]?.description).toContain(verb.description) - expect(all[`${verb.name}_${verb.noun}`]?.input).toBe(verb.input) + expect(all[`${verb.name}_${verb.noun}`]?.input).toBe(verb.agentInput) } }) @@ -103,13 +105,26 @@ describe('get and list over HTTP', () => { id: 'hello', collection: 'post', doc: expect.objectContaining({ title: 'Hello' }), + relations: { page: expect.objectContaining({ title: 'About' }) }, }) expect(JSON.stringify(got.result)).not.toContain('secret') + expect( + ( + await call( + 'get', + { collection: 'post', id: 'hello', populate: false }, + { get: true }, + ) + ).result, + ).not.toHaveProperty('relations') expect( (await call('get', { collection: 'post', id: 'draft' })).result, ).toBeNull() const listed = await call('list', { collection: 'post' }) - expect(listed.result).toMatchObject({ total: 1, items: [{ id: 'hello' }] }) + expect(listed.result).toMatchObject({ + total: 1, + items: [{ id: 'hello', relations: { page: { title: 'About' } } }], + }) // Published pages read as the public site reads them, as before. expect((await call('list', { collection: 'page' })).result).toMatchObject({ total: 1, diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index b9b3566c..8a0db7a5 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -33,6 +33,9 @@ import type { ListResult, ReadResult, RegisteredCollectionName, + RelatedAt, + Relations, + RelationPath, RegisteredDoc, RegisteredOpInput, RegisteredOpName, @@ -143,15 +146,20 @@ export interface CmsClient { readonly mode?: ReadMode /** * One document by `id` or `locator` (its slug), or `null` when it is - * missing or the caller can't see it. Typed from `Register`. + * missing or the caller can't see it. Typed from `Register`. Related + * documents come back under `relations` unless `populate` is `false`; + * read them with `related(result, path)`. */ get: ( options: GetOptions, - ) => Promise> | null> - /** One page of documents, with filters, sort, and cursor paging. */ + ) => Promise, C> | null> + /** + * One page of documents, with filters, sort, and cursor paging, each + * populated like `get`. + */ list: ( options?: ListOptions, - ) => Promise>> + ) => Promise, C>> /** * Create or change a document: `doc` holds the fields to change. Returns * the working copy, the state (its `revision` and `changeSet.version` are @@ -198,6 +206,17 @@ export interface CmsClient { fetch: (path: string, init?: RequestInit) => Promise } +/** + * The related document(s) at `path` of a populated `get`/`list` result, + * typed from `Register` (see `related` in `@tanstack/cms-core`). + */ +export function related>( + result: { collection: C; relations?: Relations }, + path: P, +): RelatedAt { + return (result.relations?.[path] ?? null) as RelatedAt +} + export function createCmsClient(options: CmsClientOptions): CmsClient { const baseUrl = options.baseUrl.replace(/\/$/, '') const doFetch = options.fetch ?? fetch diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 8cbac47f..e9e0968a 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -6,6 +6,7 @@ export { CmsApiError, CMS_API_PATH, CMS_READ_MODE_HEADER, + related, } from './client' export type { CmsClient, diff --git a/packages/client/tests/client.test.ts b/packages/client/tests/client.test.ts index 94ce88ab..59ca6e6a 100644 --- a/packages/client/tests/client.test.ts +++ b/packages/client/tests/client.test.ts @@ -86,7 +86,11 @@ describe('createCmsClient', () => { id: 'a', collection: 'post', doc: expect.objectContaining({ title: 'A' }), + relations: {}, }) + expect( + await anon.get({ collection: 'post', id: 'a', populate: false }), + ).not.toHaveProperty('relations') expect(await anon.get({ collection: 'post', id: 'b' })).toBeNull() const page = await anon.list({ collection: 'post' }) expect(page.items.map((i) => i.id)).toEqual(['a']) diff --git a/packages/client/tests/register.test.ts b/packages/client/tests/register.test.ts index 601d1a1b..5c18376e 100644 --- a/packages/client/tests/register.test.ts +++ b/packages/client/tests/register.test.ts @@ -1,7 +1,7 @@ import { describe, expectTypeOf, it } from 'vitest' import { defineCms, defineCollection, defineOp } from '@tanstack/cms-core' -import { createCmsClient } from '../src/index' -import type { StandardSchemaV1 } from '@tanstack/cms-core' +import { createCmsClient, related } from '../src/index' +import type { Doc, StandardSchemaV1 } from '@tanstack/cms-core' // A minimal Standard Schema whose inferred input/output is `T`, so the test // needs no validator library (zod isn't a client dependency). @@ -42,8 +42,27 @@ const typedCms = { fields: [ { name: 'title', label: 'Title', type: 'text' }, { name: 'views', label: 'Views', type: 'number' }, + { + name: 'author', + label: 'Author', + type: 'relation', + collection: 'author', + }, + { + name: 'coauthors', + label: 'Co-authors', + type: 'relation', + collection: 'author', + many: true, + }, ], }), + defineCollection({ + name: 'author', + label: 'Authors', + titleField: 'name', + fields: [{ name: 'name', label: 'Name', type: 'text' }], + }), ], blockTypes: [], ops: [greetOp], @@ -85,6 +104,27 @@ describe('Register augmentation', () => { }).toBeFunction() }) + it('types get/list results and related() from the relation fields', () => { + const cms = createCmsClient({ baseUrl: 'http://x' }) + expectTypeOf(async () => { + const post = await cms.get({ collection: 'post', id: 'a' }) + if (!post) return + expectTypeOf(post.collection).toEqualTypeOf<'post'>() + expectTypeOf(post.doc.title).toEqualTypeOf() + const author = related(post, 'author') + expectTypeOf(author?.name).toEqualTypeOf() + const coauthors = related(post, 'coauthors') + expectTypeOf(coauthors?.[0]?.name).toEqualTypeOf() + expectTypeOf(related(post, 'blocks.0.author')).toEqualTypeOf< + Doc | Array | null + >() + const page = await cms.list({ collection: 'post' }) + expectTypeOf(related(page.items[0]!, 'author')?.name).toEqualTypeOf< + string | undefined + >() + }).toBeFunction() + }) + it('keeps call() permissive for unregistered / dynamic names', () => { const cms = createCmsClient({ baseUrl: 'http://x' }) expectTypeOf(() => { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 69a64307..00a1d812 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -244,6 +244,7 @@ export type { OpInputOf, OpOutputOf, OpSchema, + PopulateSelection, ReadResult, ReadVerbName, Relations, @@ -252,6 +253,8 @@ export type { WriteState, WriteVerbName, } from './ops' +export { related } from './related' +export type { RelatedAt, RelationPath } from './related' // Async events: the post-commit, durable half of the eventing design. The // catalog, the typed envelope, and `defineEventHandler` are client-safe (the diff --git a/packages/core/src/ops.ts b/packages/core/src/ops.ts index 586f9c77..3054c706 100644 --- a/packages/core/src/ops.ts +++ b/packages/core/src/ops.ts @@ -218,12 +218,28 @@ export const sortInput = z.object({ dir: z.enum(['asc', 'desc']).optional(), }) -const populateInput = z - .boolean() - .optional() - .describe( - 'Also return the documents its relation fields point to, under `relations` (keyed by field path). Default false.', - ) +/** + * Which relation paths to populate: every one (`true`), none (`false`), or + * the listed paths and the relation paths under them (`['author', 'blocks']`). + */ +export type PopulateSelection = boolean | ReadonlyArray + +const populateSelection = z.union([ + z.boolean(), + z.array(z.string().min(1)).max(64), +]) + +const POPULATE_HELP = + 'Related documents come back under `relations`, keyed by relation field path (`author`, `blocks.2.author`), depth 1 (their own relations stay ids). Missing and unreadable targets are null, and dropped from arrays. `false` returns ids only; an array of paths selects those relations (and the ones under them).' + +const populateInput = populateSelection + .default(true) + .describe(`${POPULATE_HELP} Default true.`) + +/** The agent tools' list and search default: ids only, unless asked. */ +const agentPopulateInput = populateSelection + .default(false) + .describe(`${POPULATE_HELP} Default false: ids only, to keep results small.`) /** * The `get` bag: one document by `id` or by `locator`, never both. What the @@ -300,7 +316,8 @@ export type GetOptions = { /** `false`: the committed document, without staged changes (see `getInput`). */ staged?: boolean locale?: string - populate?: boolean + /** Default `true`. */ + populate?: PopulateSelection } & ({ id: string; locator?: never } | { locator: string; id?: never }) /** `list`'s options (see `listInput`). */ @@ -312,21 +329,25 @@ export interface ListOptions { limit?: number offset?: number cursor?: string - populate?: boolean + /** Default `true`. */ + populate?: PopulateSelection } /** One document as `get` and `list` return it. */ -export interface ReadResult { +export interface ReadResult { id: string - collection: string + collection: C doc: TDoc - /** With `populate`: the related documents the reader may see. */ + /** + * The related documents the reader may see, when populated (the default). + * Read them with `related(result, path)`. + */ relations?: Relations } /** One page of `list`. */ -export interface ListResult { - items: Array> +export interface ListResult { + items: Array> total: number /** Pass as `cursor` to read the next page; absent on the last page. */ nextCursor?: string @@ -337,22 +358,28 @@ export interface ListResult { * registry: the store (`cmsAs(cms, ctx).get`), HTTP and Start (`get`), the * client (`client.get`) and the agent tools (`get_document`, via * `agentToolName`). Full-text search stays its own verb - * (`search_documents`). + * (`search_documents`). `agentInput` carries the agent tools' one + * difference: `list_documents` returns ids unless the agent asks for + * relations. */ export const readVerbs = [ { name: 'get', noun: 'document', description: - 'Read one document by collection and id, or by collection and locator (its slug). Returns { id, collection, doc }, or null when it is missing or not visible to the reader. A live reader sees the published version; preview and edit readers see the working copy, staged changes included.', + 'Read one document by collection and id, or by collection and locator (its slug). Returns { id, collection, doc, relations }, or null when it is missing or not visible to the reader. A live reader sees the published version; preview and edit readers see the working copy, staged changes included. Populated by default: the documents its relation fields point to come back under relations (pass populate: false for ids only).', input: getInput, + agentInput: getInput, }, { name: 'list', noun: 'documents', description: - 'List documents of one collection (or of every collection the reader may read), with field filters, sort, and paging. Returns { items: [{ id, collection, doc }], total, nextCursor? }. A live reader sees published documents only.', + 'List documents of one collection (or of every collection the reader may read), with field filters, sort, and paging. Returns { items: [{ id, collection, doc, relations }], total, nextCursor? }. A live reader sees published documents only. Populated by default (pass populate: false for ids only).', + agentDescription: + 'List documents of one collection (or of every collection the reader may read), with field filters, sort, and paging. Returns { items: [{ id, collection, doc }], total, nextCursor? }. A live reader sees published documents only. Relation fields are ids only unless you pass populate (true, or the relation paths you need).', input: listInput, + agentInput: listInput.extend({ populate: agentPopulateInput }), }, ] as const @@ -533,8 +560,9 @@ export const opSchemas: Array = [ ...readVerbs.map((verb): OpSchema => ({ name: agentToolName(verb), kind: 'read', - description: verb.description, - inputSchema: verb.input, + description: + 'agentDescription' in verb ? verb.agentDescription : verb.description, + inputSchema: verb.agentInput, })), ...writeVerbs.flatMap((verb): Array => verb.agent @@ -728,7 +756,7 @@ export const opSchemas: Array = [ name: 'search_documents', kind: 'read', description: - 'Search and filter documents across one or all collections by text query, field filters, locale, and published status.', + 'Search and filter documents across one or all collections by text query, field filters, locale, and published status. Relation fields are ids only unless you pass populate (true, or the relation paths you need).', inputSchema: z.object({ collection: z.string().optional(), query: z @@ -752,6 +780,7 @@ export const opSchemas: Array = [ .string() .optional() .describe('`nextCursor` from the previous page of the same query.'), + populate: agentPopulateInput, }), }, { diff --git a/packages/core/src/related.ts b/packages/core/src/related.ts new file mode 100644 index 00000000..7efee9af --- /dev/null +++ b/packages/core/src/related.ts @@ -0,0 +1,57 @@ +import type { RegisteredCollections, RegisteredDoc } from './config' +import type { Relations } from './ops' +import type { Collection, Doc } from './schema' + +type FieldsOf = C extends keyof RegisteredCollections + ? RegisteredCollections[C] extends Collection + ? RegisteredCollections[C]['fields'][number] + : never + : never + +type RelatedField = Extract< + FieldsOf, + { name: P; type: 'relation' | 'asset' } +> + +/** + * What `related(result, path)` returns: for a top-level relation field of a + * registered collection, the target's document type (an array for + * `many: true`); for a nested path (`blocks.2.author`) or an unregistered + * app, any related document. `null` when the path wasn't populated, or the + * target is missing or hidden. + */ +export type RelatedAt = [ + RelatedField, +] extends [never] + ? Doc | Array | null + : RelatedField extends { collection: infer T extends string } + ? RelatedField extends { many: true } + ? Array> | null + : RegisteredDoc | null + : RelatedField extends { many: true } + ? Array | null + : Doc | null + +/** The paths `related` suggests for `C`: its top-level relation fields. */ +export type RelationPath = + | Extract, { type: 'relation' | 'asset' }>['name'] + | (string & {}) + +/** + * The related document(s) at `path` of a populated `get`/`list` result, + * typed from the registered collection: + * + * ```ts + * const post = await client.get({ collection: 'post', locator: 'hello' }) + * const author = post && related(post, 'author') // Author | null + * ``` + * + * Paths are relation field paths as `relations` keys them (`author`, + * `seo.image`, `blocks.2.author`). + */ +export function related>( + result: { collection: C; relations?: Relations }, + path: P, +): RelatedAt { + return (result.relations?.[path] ?? null) as RelatedAt +} diff --git a/packages/core/src/server/cms-as.ts b/packages/core/src/server/cms-as.ts index cdd39834..1948bd7f 100644 --- a/packages/core/src/server/cms-as.ts +++ b/packages/core/src/server/cms-as.ts @@ -63,11 +63,11 @@ export interface CmsReads { /** One document by `id` or `locator`, or `null` (see `getAs`). */ get: ( options: GetOptions, - ) => Promise> | null> + ) => Promise, C> | null> /** One page of documents (see `listAs`). */ list: ( options?: ListOptions, - ) => Promise>> + ) => Promise, C>> queryDocuments: Bound groupDocuments: Bound queryDocumentSummaries: Bound diff --git a/packages/core/src/server/cms-ops.ts b/packages/core/src/server/cms-ops.ts index 50cb228e..c43095b2 100644 --- a/packages/core/src/server/cms-ops.ts +++ b/packages/core/src/server/cms-ops.ts @@ -504,7 +504,7 @@ async function dispatch( } case 'list_documents': - return store.listAs(ctx, input) + return store.listAs(ctx, { ...input, populate: input?.populate ?? false }) case 'get_document': return store.getAs(ctx, input) @@ -513,6 +513,7 @@ async function dispatch( const found = await store.getAs(withMode(ctx, 'edit'), { collection: input.collection, id: input.id, + populate: false, }) if (!found) { throw new CmsError( @@ -610,6 +611,7 @@ async function dispatch( limit: input?.limit, offset: input?.offset, cursor: input?.cursor, + populate: input?.populate, }) case 'list_revisions': diff --git a/packages/core/src/server/store/query.ts b/packages/core/src/server/store/query.ts index 308528bc..ce0e8621 100644 --- a/packages/core/src/server/store/query.ts +++ b/packages/core/src/server/store/query.ts @@ -25,7 +25,8 @@ import { import { denormalize } from '../indexing' import { getStorage } from '../storage' import { applyPostRead, collections, isScalarField } from './internal' -import { populateRelationsAs } from './read' +import { resolveRelationsAs, wantsRelations } from './read' +import type { PopulateSelection } from '../../ops' import type { AccessContext } from '../access-context' import type { Doc } from '../../schema' import type { @@ -43,7 +44,11 @@ export interface QueryDocumentsOptions { query?: string textQuery?: { fields: ReadonlyArray; terms: ReadonlyArray } locale?: string - populate?: boolean + /** + * Related documents under each item's `relations`: every relation path + * (`true`), or these paths and the ones under them. Default `false`. + */ + populate?: PopulateSelection /** * Filters. An object maps field paths to a value (`eq`), an array (`in`), * `null` (missing), or an operator object (`{ gte: 3, lt: 10 }`); `and`, @@ -294,11 +299,13 @@ export async function queryDocumentsAs( : row.id, doc: visible, published: row.published, - ...(options?.populate - ? { - relations: await populateRelationsAs(ctx, row.collection, doc), - } - : {}), + }) + } + const populate = options?.populate + if (wantsRelations(populate)) { + const relations = await resolveRelationsAs(ctx, page, populate) + page.forEach((item, i) => { + item.relations = relations[i] }) } const total = result.total diff --git a/packages/core/src/server/store/read.ts b/packages/core/src/server/store/read.ts index 65c08236..88955810 100644 --- a/packages/core/src/server/store/read.ts +++ b/packages/core/src/server/store/read.ts @@ -27,6 +27,7 @@ import { getStorage } from '../storage' import { applyPostRead, collections, requireCollection } from './internal' import { collectRelations, nestedRelationTargets } from './relations' import type { AccessContext } from '../access-context' +import type { PopulateSelection, Relations } from '../../ops' import type { Collection, Doc, Field, JsonValue } from '../../schema' import type { IndexedDocumentRecord, @@ -530,10 +531,146 @@ export function populateRelations( return populateRelationsAs(publicContext(), collectionName, doc) } +/** Whether `select` asks for any relations at all. @internal */ +export function wantsRelations( + select: PopulateSelection | undefined, +): select is true | ReadonlyArray { + return select === true || (Array.isArray(select) && select.length > 0) +} + +interface RelationSlot { + path: string + target: string + ids: Array + many: boolean +} + +function relationSlots( + fields: ReadonlyArray, + value: Record | undefined, + prefix: Array, + out: Array, +): void { + if (!value) return + for (const f of fields) { + if (!(f.name in value) && prefix.length > 0) continue + const v = value[f.name] + const at = [...prefix, f.name] + const target = relationTarget(f) + if (target) { + const ids = f.many + ? (Array.isArray(v) ? v.map(String) : []).filter(Boolean) + : typeof v === 'string' && v + ? [v] + : [] + if (prefix.length > 0 && ids.length === 0) continue + out.push({ path: at.join('.'), target, ids, many: Boolean(f.many) }) + } else if (f.type === 'group' && f.fields && isRecord(v)) { + relationSlots(f.fields, v, at, out) + } else if (f.type === 'array' && f.fields && Array.isArray(v)) { + for (const [i, item] of v.entries()) { + if (isRecord(item)) + relationSlots(f.fields, item, [...at, String(i)], out) + } + } else if (f.type === 'blocks' && Array.isArray(v)) { + const types = blockTypeMap() + for (const [i, block] of v.entries()) { + if (!isRecord(block)) continue + const typeName = + typeof block._type === 'string' + ? block._type + : typeof block.type === 'string' + ? block.type + : undefined + const bt = typeName ? types[typeName] : undefined + if (bt) relationSlots(bt.fields, block, [...at, String(i)], out) + } + } + } +} + +function isSelected(path: string, select: PopulateSelection): boolean { + if (typeof select === 'boolean') return select + return select.some((s) => path === s || path.startsWith(`${s}.`)) +} + +/** Ids per storage read, well under SQLite's bound-parameter limit. */ +const RELATION_BATCH = 500 + +/** + * The related documents of many documents at once, one `Relations` map per + * item. Ids are batched per target collection across every item, so a list + * costs one storage read per target collection, not one per row and field. + * Depth 1: related documents come back as stored, their own relation fields + * left as ids, so cycles can't recurse. A target that is missing, trashed, + * or not visible to `ctx` (its collection included) is `null`, dropped from + * a `many` array, so a reader can't tell hidden from missing. Every related + * document is redacted for `ctx`. + * + * @internal + */ +export async function resolveRelationsAs( + ctx: AccessContext, + items: ReadonlyArray<{ collection: string; doc: Doc }>, + select: PopulateSelection = true, +): Promise> { + const live = isLiveRead(ctx) + const slotsPerItem = items.map(({ collection, doc }) => { + const schema = collections()[collection] + if (!schema) return [] + const slots: Array = [] + relationSlots(schema.fields, redactFor(ctx, collection, doc), [], slots) + return slots.filter((slot) => isSelected(slot.path, select)) + }) + const wanted = new Map>() + for (const slot of slotsPerItem.flat()) { + if (!canReadCollection(ctx, slot.target)) continue + const ids = wanted.get(slot.target) ?? new Set() + for (const id of slot.ids) ids.add(id) + wanted.set(slot.target, ids) + } + const storage = await getStorage() + const found = new Map>() + await Promise.all( + [...wanted].map(async ([target, idSet]) => { + const visible = new Map() + found.set(target, visible) + const ids = [...idSet] + for (let i = 0; i < ids.length; i += RELATION_BATCH) { + const rows = await storage.getDocuments( + target, + ids.slice(i, i + RELATION_BATCH), + ) + for (const row of rows) { + if (row.deletedAt) continue + if (live && !row.published) continue + const doc = await applyPostRead(target, row.id, row.doc, ctx) + if (live && !doc.published) continue + if (!canReadDocument(ctx, target, row)) continue + visible.set(row.id, redactFor(ctx, target, doc)) + } + } + }), + ) + return slotsPerItem.map((slots) => { + const out: Relations = {} + for (const slot of slots) { + const visible = found.get(slot.target) + const docs = slot.ids.flatMap((id) => { + const doc = visible?.get(id) + return doc ? [doc] : [] + }) + out[slot.path] = slot.many ? docs : (docs[0] ?? null) + } + return out + }) +} + /** * Resolve every `relation` field on a document (including inside `group`, * `array`, and `blocks`) into the target `Doc`s `ctx` may read (an * `Array` for `many: true`), keyed by field name or dotted path. A + * missing, trashed or hidden target is `null` (dropped from an array), and a * `publicRead` context sees published targets the way it sees the source. */ export async function populateRelationsAs( @@ -541,82 +678,10 @@ export async function populateRelationsAs( collectionName: string, doc: Doc, ): Promise | null>> { - const collection = collections()[collectionName] - if (!collection) return {} - const live = isLiveRead(ctx) - const sourceDoc = redactFor(ctx, collectionName, doc) - const storage = await getStorage() - const resolved: Record | null> = {} - - const resolveField = async ( - field: Field, - raw: unknown, - path: string, - isNested: boolean, - ) => { - const targetName = relationTarget(field) - if (!targetName) return - if (!canReadCollection(ctx, targetName)) return - const ids = field.many - ? (Array.isArray(raw) ? raw.map(String) : []).filter(Boolean) - : typeof raw === 'string' && raw - ? [raw] - : [] - if (isNested && ids.length === 0) return - const rows = await storage.getDocuments(targetName, ids) - const docs: Array = [] - for (const row of rows) { - if (live && !row.published) continue - const targetDoc = await applyPostRead(targetName, row.id, row.doc, ctx) - if (live && !targetDoc.published) continue - if (!canReadDocument(ctx, targetName, row)) continue - docs.push(redactFor(ctx, targetName, targetDoc)) - } - resolved[path] = field.many ? docs : (docs[0] ?? null) - } - - const walk = async ( - fields: ReadonlyArray, - value: Record | undefined, - prefix: Array, - ): Promise => { - if (!value) return - for (const f of fields) { - if (!(f.name in value) && prefix.length > 0) continue - const v = value[f.name] - const at = [...prefix, f.name] - const path = at.join('.') - if (relationTarget(f)) { - await resolveField(f, v, path, prefix.length > 0) - } else if (f.type === 'group' && f.fields && isRecord(v)) { - await walk(f.fields, v, at) - } else if (f.type === 'array' && f.fields && Array.isArray(v)) { - for (const [i, item] of v.entries()) { - if (isRecord(item)) { - await walk(f.fields, item, [...at, String(i)]) - } - } - } else if (f.type === 'blocks' && Array.isArray(v)) { - const types = blockTypeMap() - for (const [i, block] of v.entries()) { - if (!isRecord(block)) continue - const typeName = - typeof block._type === 'string' - ? block._type - : typeof block.type === 'string' - ? block.type - : undefined - const bt = typeName ? types[typeName] : undefined - if (bt) { - await walk(bt.fields, block, [...at, String(i)]) - } - } - } - } - } - - await walk(collection.fields, sourceDoc, []) - return resolved + const [relations] = await resolveRelationsAs(ctx, [ + { collection: collectionName, doc }, + ]) + return relations ?? {} } /** @@ -657,8 +722,6 @@ export async function readSingletonAs( return { id: row.id, doc: redactFor(ctx, collectionName, doc) } } -type Relations = Record | null> - /** * `readDocumentBySlugAs` as `publicContext()`. * diff --git a/packages/core/src/server/store/verbs.ts b/packages/core/src/server/store/verbs.ts index fa1fe242..dae869d6 100644 --- a/packages/core/src/server/store/verbs.ts +++ b/packages/core/src/server/store/verbs.ts @@ -11,10 +11,11 @@ import { canReadCollection, isLiveRead } from '../access-context' import { collections } from './internal' import { queryDocumentsAs } from './query' import { - populateRelationsAs, readBySlug, readDocumentAs, readDocumentWithPendingAs, + resolveRelationsAs, + wantsRelations, } from './read' import type { AccessContext } from '../access-context' import type { GetOptions, ListOptions, ListResult, ReadResult } from '../../ops' @@ -24,7 +25,8 @@ import type { GetOptions, ListOptions, ListResult, ReadResult } from '../../ops' * id; leading slashes ignored). A `live` context reads the published * version; `preview` and `edit` read the working copy, with staged changes * overlaid. `null` when the document is missing or `ctx` can't see it; the - * returned document is redacted for `ctx`. + * returned document is redacted for `ctx`. Relations are populated unless + * `populate` is `false` (see `resolveRelationsAs`). */ export async function getAs( ctx: AccessContext, @@ -44,20 +46,22 @@ export async function getAs( ? await readDocumentAs(ctx, collection, id) : (await readDocumentWithPendingAs(ctx, collection, id)).doc if (!doc) return null - return { - id, - collection, - doc, - ...(bag.populate - ? { relations: await populateRelationsAs(ctx, collection, doc) } - : {}), - } + const populate = bag.populate + if (!wantsRelations(populate)) return { id, collection, doc } + const [relations] = await resolveRelationsAs( + ctx, + [{ collection, doc }], + populate, + ) + return { id, collection, doc, relations: relations ?? {} } } /** * One page of the documents `ctx` may read, in one collection or across * every collection `ctx` may read. Filtering or sorting on a field `ctx` may - * not read is `FORBIDDEN`; documents are redacted for `ctx`. + * not read is `FORBIDDEN`; documents are redacted for `ctx`. Each item's + * relations are populated unless `populate` is `false`, with one storage + * read per target collection for the whole page. */ export async function listAs( ctx: AccessContext, diff --git a/packages/core/tests/access-context.test.ts b/packages/core/tests/access-context.test.ts index 789c741d..690f2f41 100644 --- a/packages/core/tests/access-context.test.ts +++ b/packages/core/tests/access-context.test.ts @@ -333,7 +333,7 @@ describe('derivation', () => { cms, accessContext({ session: as('viewer') }), ).populateRelations('post', { title: 'x', author: 'm-live' }) - expect(ruled).toEqual({}) + expect(ruled).toEqual({ author: null }) const admin = cmsAs(cms, accessContext({ session: as('admin') })) const [live] = ( diff --git a/packages/core/tests/field-access.test.ts b/packages/core/tests/field-access.test.ts index f81b14cb..e8dbe67a 100644 --- a/packages/core/tests/field-access.test.ts +++ b/packages/core/tests/field-access.test.ts @@ -552,7 +552,7 @@ describe('nested and document-aware field access', () => { articleDoc, ) // secretCol is not readable by viewer - expect(viewerRels.secretRef).toBeUndefined() + expect(viewerRels.secretRef).toBeNull() // nested relations in group, array, and blocks are populated and redacted expect(viewerRels['meta.editor']).toMatchObject({ name: 'Alice', diff --git a/packages/core/tests/read-verbs.test.ts b/packages/core/tests/read-verbs.test.ts index 6400eb83..2c5c5941 100644 --- a/packages/core/tests/read-verbs.test.ts +++ b/packages/core/tests/read-verbs.test.ts @@ -1,7 +1,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { agentToolName, createCms, @@ -11,10 +11,12 @@ import { normalizeSession, opSchemas, readVerbs, + related, } from '../src/index' import { closeStore, commitDocument, + deleteDocument, getAs, listAs, queryDocuments, @@ -28,6 +30,7 @@ import { systemContext, } from '../src/server/access-context' import { cmsAs } from '../src/server/cms-as' +import { getStorage } from '../src/server/storage' import type { Cms, CmsConfig, Doc, ListResult, ReadResult } from '../src/index' const dirs: Array = [] @@ -77,10 +80,41 @@ const memo = defineCollection({ fields: [{ name: 'title', label: 'Title', type: 'text' }], }) +const node = defineCollection({ + name: 'node', + label: 'Nodes', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'parent', label: 'Parent', type: 'relation', collection: 'node' }, + { + name: 'links', + label: 'Links', + type: 'relation', + collection: 'node', + many: true, + }, + { name: 'memo', label: 'Memo', type: 'relation', collection: 'memo' }, + { + name: 'meta', + label: 'Meta', + type: 'group', + fields: [ + { + name: 'owner', + label: 'Owner', + type: 'relation', + collection: 'author', + }, + ], + }, + ], +}) + function config(): CmsConfig { const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-verbs-')) dirs.push(dataDir) - return { dataDir, collections: [author, post, memo], blockTypes: [] } + return { dataDir, collections: [author, post, memo, node], blockTypes: [] } } async function seeded(): Promise { @@ -110,6 +144,24 @@ async function seeded(): Promise { author: 'bob', }) await commitDocument('memo', 'm1', { title: 'Memo', published: true }) + await commitDocument('node', 'a', { title: 'A', published: true }) + await commitDocument('node', 'gone', { title: 'Gone', published: true }) + await commitDocument('node', 'b', { + title: 'B', + parent: 'a', + links: ['a', 'gone'], + memo: 'm1', + meta: { owner: 'bob' }, + published: true, + }) + await commitDocument('node', 'a', { + title: 'A', + parent: 'b', + links: ['a', 'b'], + meta: { owner: 'ada' }, + published: true, + }) + await deleteDocument('node', 'gone', { purge: true, force: true }) await stageWrite({ collection: 'post', docId: 'hello', @@ -132,6 +184,7 @@ describe('get', () => { id: 'hello', collection: 'post', doc: expect.objectContaining({ title: 'Hello' }), + relations: { author: expect.objectContaining({ name: 'Ada' }) }, }) expect(byId?.doc).not.toHaveProperty('secret') expect((await pub.get({ collection: 'post', locator: '/hello' }))?.id).toBe( @@ -186,20 +239,80 @@ describe('get', () => { ).toBe('m1') }) - it('populates only when asked (no default flip in this phase)', async () => { + it('populates by default; populate: false returns ids only', async () => { const cms = await seeded() const db = cmsAs(cms, publicContext()) - expect( - await db.get({ collection: 'post', id: 'hello' }), - ).not.toHaveProperty('relations') - const populated = await db.get({ + const populated = await db.get({ collection: 'post', id: 'hello' }) + expect(populated && related(populated, 'author')).toEqual( + expect.objectContaining({ name: 'Ada' }), + ) + const plain = await db.get({ collection: 'post', id: 'hello', - populate: true, + populate: false, }) - expect(populated?.relations?.author).toEqual( - expect.objectContaining({ name: 'Ada' }), + expect(plain).not.toHaveProperty('relations') + expect(plain?.doc.author).toBe('ada') + expect(plain && related(plain, 'author')).toBeNull() + }) + + it('populates only the selected paths', async () => { + const cms = await seeded() + const db = cmsAs(cms, systemContext('test: populate')) + const got = await db.get({ + collection: 'node', + id: 'a', + populate: ['links', 'meta'], + }) + expect(Object.keys(got?.relations ?? {}).sort()).toEqual([ + 'links', + 'meta.owner', + ]) + expect( + (await db.get({ collection: 'node', id: 'a', populate: ['meta.owner'] })) + ?.relations, + ).toEqual({ 'meta.owner': expect.objectContaining({ name: 'Ada' }) }) + expect( + await db.get({ collection: 'node', id: 'a', populate: [] }), + ).not.toHaveProperty('relations') + }) + + it('populates depth 1, so cycles and self-references stay ids', async () => { + const cms = await seeded() + const db = cmsAs(cms, systemContext('test: populate')) + const a = await db.get({ collection: 'node', id: 'a' }) + expect(a?.relations?.parent).toEqual( + expect.objectContaining({ title: 'B', parent: 'a' }), ) + expect(a?.relations?.links).toEqual([ + expect.objectContaining({ title: 'A', links: ['a', 'b'] }), + expect.objectContaining({ title: 'B' }), + ]) + }) + + it('resolves trashed, missing and hidden targets to null', async () => { + const cms = await seeded() + await cms.run(() => + deleteDocument('author', 'ada', { actor: 'test', force: true }), + ) + const sys = cmsAs(cms, systemContext('test: populate')) + expect( + (await sys.get({ collection: 'post', id: 'hello' }))?.relations, + ).toEqual({ author: null }) + expect( + (await sys.get({ collection: 'node', id: 'b' }))?.relations?.links, + ).toEqual([expect.objectContaining({ title: 'A' })]) + const viewer = cmsAs( + cms, + accessContext({ session: as('viewer'), mode: 'live' }), + ) + const b = await viewer.get({ collection: 'node', id: 'b' }) + // Bob is a draft author; memos are for editors only. + expect(b?.relations?.['meta.owner']).toBeNull() + expect(b?.relations?.memo).toBeNull() + expect(b?.relations?.links).toEqual([ + expect.objectContaining({ title: 'A' }), + ]) }) it('takes exactly one of id or locator', async () => { @@ -227,6 +340,7 @@ describe('list', () => { id: 'hello', collection: 'post', doc: expect.not.objectContaining({ secret: 's1' }), + relations: { author: expect.objectContaining({ name: 'Ada' }) }, }) expect( (await pub.list({ collection: 'post', locale: 'es' })).items.map( @@ -261,7 +375,7 @@ describe('list', () => { const viewer = accessContext({ session: as('viewer'), mode: 'live' }) const all = await cmsAs(cms, viewer).list() expect(new Set(all.items.map((i) => i.collection))).toEqual( - new Set(['author', 'post']), + new Set(['author', 'post', 'node']), ) }) @@ -276,22 +390,54 @@ describe('list', () => { }) }) - it('populates per item only when asked', async () => { + it('populates per item by default, unless populate is false', async () => { const cms = await seeded() const db = cmsAs(cms, systemContext('test: populate')) - const plain = await db.list({ collection: 'post' }) + const plain = await db.list({ collection: 'post', populate: false }) expect(plain.items.every((i) => !('relations' in i))).toBe(true) const populated = await db.list({ collection: 'post', sort: { field: 'rank' }, - populate: true, }) - expect(populated.items.map((i) => i.relations?.author ?? null)).toEqual([ + expect(populated.items.map((i) => related(i, 'author'))).toEqual([ expect.objectContaining({ name: 'Bob' }), expect.objectContaining({ name: 'Ada' }), null, ]) }) + + it('reads each target collection once per page', async () => { + const cms = await seeded() + await cms.run(async () => { + for (let i = 0; i < 20; i++) { + await commitDocument('post', `p${i}`, { + title: `P${i}`, + author: i % 2 ? 'ada' : 'bob', + }) + } + const storage = await getStorage() + const spy = vi.spyOn(storage, 'getDocuments') + try { + const page = await listAs(systemContext('test: populate'), { + collection: 'post', + }) + expect(page.items).toHaveLength(23) + expect(spy.mock.calls.map(([target]) => target)).toEqual(['author']) + expect(new Set(spy.mock.calls[0]?.[1])).toEqual(new Set(['ada', 'bob'])) + spy.mockClear() + await listAs(systemContext('test: populate'), { + collection: 'node', + }) + expect(spy.mock.calls.map(([target]) => target).sort()).toEqual([ + 'author', + 'memo', + 'node', + ]) + } finally { + spy.mockRestore() + } + }) + }) }) describe('the old verbs keep their defaults', () => { @@ -318,11 +464,63 @@ describe('the registry', () => { ]) const tool = (name: string) => opSchemas.find((s) => s.name === name) expect(tool('get_document')?.inputSchema).toBe(getInput) - expect(tool('list_documents')?.inputSchema).toBe(listInput) + expect(tool('list_documents')?.inputSchema).not.toBe(listInput) + expect(readVerbs[1].agentInput.shape.where).toBe(listInput.shape.where) expect(tool('read_document')?.description).toMatch(/^Deprecated/) expect(tool('search_documents')).toBeDefined() }) + it('populates get_document by default, list and search only when asked', async () => { + const cms = await seeded() + await cms.run(async () => { + const ctx = editor() + const got = (await runOp( + 'get_document', + { collection: 'post', id: 'draft' }, + 'agent', + ctx, + )) as ReadResult + expect(got.relations).toEqual({ + author: expect.objectContaining({ name: 'Bob' }), + }) + const listed = (await runOp( + 'list_documents', + { collection: 'post' }, + 'agent', + ctx, + )) as ListResult + expect(listed.items.some((i) => 'relations' in i)).toBe(false) + const asked = (await runOp( + 'list_documents', + { collection: 'post', populate: ['author'] }, + 'agent', + ctx, + )) as ListResult + expect(asked.items.some((i) => i.relations?.author)).toBe(true) + const searched = (await runOp( + 'search_documents', + { collection: 'post' }, + 'agent', + ctx, + )) as { items: Array<{ relations?: unknown }> } + expect(searched.items.some((i) => 'relations' in i)).toBe(false) + const searchedPopulated = (await runOp( + 'search_documents', + { collection: 'post', populate: true }, + 'agent', + ctx, + )) as { items: Array<{ relations?: unknown }> } + expect(searchedPopulated.items.some((i) => i.relations)).toBe(true) + const legacy = (await runOp( + 'read_document', + { collection: 'post', id: 'hello' }, + 'agent', + ctx, + )) as Doc + expect(legacy).not.toHaveProperty('relations') + }) + }) + it('serves get and list as agent tools; read_document keeps its shape', async () => { const cms = await seeded() await cms.run(async () => {