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
37 changes: 37 additions & 0 deletions .changeset/phase-6-removal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-client': minor
'@tanstack/cms-ui-react': minor
'@tanstack/search-cms': patch
---

This alpha finishes the core API refactor: one read vocabulary (`get`, `list`, and `searchAs` for full-text search), one write vocabulary (`save`, `act`), access contexts on every read, and the `document.*` event names. The verbs and aliases the earlier steps deprecated are removed. See step 31 of the [upgrading guide](https://github.com/TanStack/cms/blob/main/docs/deployment/upgrading.md#31-the-deprecated-verbs-are-removed), which lists every removed name, its replacement and its codemod. From a TanStack/cms checkout, run them in this order and review each warning:

```sh
pnpm codemod access-context /path/to/your/app
pnpm codemod read-verbs /path/to/your/app
pnpm codemod write-verbs /path/to/your/app
pnpm codemod event-names /path/to/your/app
```

**Kept for one more alpha, removed in the next alpha:** `queryDocumentsAs` and `queryDocuments` (use `searchAs` or `listAs`), `readDocumentAs` and `readDocument` (use `getAs`, with `staged: false` for a read that feeds a write), their `cmsAs(cms, ctx)` methods, the `getPublicDocument` operation and Start function (use `get`), and the `read_document` agent tool (use `get_document`).

**Breaking, removed:**

- `@tanstack/cms-core/server`: the read functions without a context (`readSingleton`, `populateRelations`, `listDocuments`, `queryDocumentSummaries`, `groupDocuments`, `findReferences`, `listTranslations`, `listRevisions`, `readDocumentWithPending`, `readDocumentBySlug`, `findDocumentBySlug`; use the `…As(ctx, …)` form), `readDocumentBySlugAs` (use `getAs` by `id`, then by `locator`), and `findDocumentBySlugAs` (use `getAs` per collection), with the matching `cmsAs(cms, ctx)` methods. `searchAs(ctx, options)` is new: full-text and multi-collection search, `queryDocumentsAs` under its canonical name.
- Operations and `@tanstack/cms-api/start` functions: `listPublishedDocuments` (use `list`), `saveDoc` (use `save`), `createDoc` (use `save` with `create: true`) and `actOnChange` (use `act`, with the document's id instead of the pending change's).
- Agent tools: `create_document` (use `save_document` with `create: true`) and `update_document` (use `save_document`).
- `@tanstack/cms-client`: `collection(name).published`, `.save` and `.create` (use `client.list` and `client.save`).
- Events: the short names `publish`, `unpublish`, `delete`, `change` and `update`, and the `CmsEventAlias` type. A webhook `events` list that uses a short name now throws at `defineCms`, and an `onCmsEvent` filter throws when it subscribes, naming the replacement.

**Behaviour changes to check, because nothing fails when they bite:**

- **Relations are populated by default.** `get`, `list`, `client.get/list`, the `get`/`list` operations and `get_document` return `relations` beside each document unless called with `populate: false`. Code that only needs ids pays for the extra reads.
- **Content roles are no longer guessed from field names.** Collections that don't declare `summaryField`, `bylineField`, `dateField` and the rest lose SEO descriptions, social images, JSON-LD dates and authors, and post-card summaries, with no error. `pnpm codemod explicit-roles` declares what the old fallbacks picked.
- **A `publicPrefix` gives a collection a default `path`** derived from each document's locator, so the sitemap, "View" links and page navigation move to `{publicPrefix}/{locator}`, and a published URL change adds a redirect when the CMS has a redirects collection.
- The `save` operation records the operation's actor in revisions and the review queue (for example `api` over HTTP), where `saveDoc` recorded `human`. A staged create no longer records the "Created document" instruction.
- `save` with `create: true` (and `save_document` with `create: true`) refuses an existing id with `CONFLICT`. `create_document` replaced the document.
- `list` with a `locale` filters by document locale; `listPublishedDocuments` resolved localized fields instead.
- The canned `/p/$id` and `/post/$id` routes and `cmsDocumentQueryOptions` read only their own collection, by id and then by locator. They used to resolve the key across collections.
- The agent chat's Approve button reads the staged change from `save_document`'s `state.changeSet`.
29 changes: 17 additions & 12 deletions .claude/skills/voting/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ they sort and filter through the indexed read path), and the write path is a
server function composed from the same store primitives the admin uses.

All store functions from `@tanstack/cms-core/server` are **async** —
`await` every `getAs`, `listAs`, `readDocumentAs`, `commitDocument`, and
`deleteDocument`. Every read takes an access context: `publicContext()` for
`await` every `getAs`, `listAs`, `commitDocument`, and `deleteDocument`. Every read takes an access context: `publicContext()` for
what a visitor may see (published posts), and a named
`systemContext(reason)` for the server-owned vote records. Reads that feed a
write (the existing vote, the post whose tally you commit) use
`readDocumentAs`, which returns the stored row; `getAs` in a system (edit)
context returns the working copy, with any staged changes overlaid.
write (the existing vote, the post whose tally you commit) pass
`staged: false` to `getAs`, which returns the stored row; without it, `getAs`
in a system (edit) context returns the working copy, with any staged changes
overlaid.

## 0. Prerequisites

Expand Down Expand Up @@ -81,7 +81,7 @@ And on `post`, add:
```

Vote documents are never `published`, so they don't appear in the public
read paths (`get`, `list`, and the older `listPublishedDocuments`); `access.read`
read paths (`get` and `list`); `access.read`
then keeps them out of non-admin API and MCP reads.

**Deterministic vote ids.** Enforce one-vote-per-user with the id itself:
Expand Down Expand Up @@ -132,14 +132,21 @@ import {
getAs,
listAs,
publicContext,
readDocumentAs,
requireAuthenticated,
systemContext,
} from '@tanstack/cms-core/server'

// Votes and the cached tallies are maintained by the server, not the voter.
const VOTES = systemContext('voting: votes and tallies are server-owned')

// The stored row, for a read that feeds a write.
async function stored(collection: string, id: string) {
return (
(await getAs(VOTES, { collection, id, staged: false, populate: false }))
?.doc ?? null
)
}

export async function castVoteForVoter(
postId: string,
value: 1 | -1,
Expand All @@ -157,7 +164,7 @@ export async function castVoteForVoter(
}

const id = voteId(postId, voterId)
const existing = await readDocumentAs(VOTES, 'vote', id)
const existing = await stored('vote', id)
if (existing && Number(existing.value) === value) {
await deleteDocument('vote', id, { actor: voterId }) // retract
} else {
Expand Down Expand Up @@ -189,7 +196,7 @@ export async function castVoteForVoter(
} while (cursor)
// Re-read the stored post: a public read may leave out fields the commit
// would then drop.
const post = await readDocumentAs(VOTES, 'post', postId)
const post = await stored('post', postId)
await commitDocument(
'post',
postId,
Expand Down Expand Up @@ -258,9 +265,7 @@ export async function getVoteState(postId: string, voterId?: string) {
populate: false,
})
)?.doc
const mine = voterId
? await readDocumentAs(VOTES, 'vote', voteId(postId, voterId))
: null
const mine = voterId ? await stored('vote', voteId(postId, voterId)) : null
return {
upvotes: Number(post?.upvotes ?? 0),
downvotes: Number(post?.downvotes ?? 0),
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const products = createCollection(
createCmsCollectionOptions<Product>(cms, queryClient, 'product'),
)

// In a component: a live query, and an optimistic write that runs saveDoc
// In a component: a live query, and an optimistic write that runs save
const { data } = useLiveQuery({
query: (q) => q.from({ p: products }).where(({ p }) => gt(p.stock, 0)),
})
Expand Down
16 changes: 9 additions & 7 deletions app/base/e2e/base.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,9 @@ test('first-run owner setup, sign-out, and API protection', async ({
await expect(page).toHaveURL(/\/login/)
await page.goto('/setup')
await expect(page).toHaveURL(/\/login/)
const denied = await page.request.post(
'/api/cms/v1/ops/listPublishedDocuments',
{ data: { collection: 'products' } },
)
const denied = await page.request.post('/api/cms/v1/ops/list', {
data: { collection: 'products', populate: false },
})
expect(denied.status()).toBe(401)
const deniedList = await page.request.get('/api/cms/v1/ops/list', {
params: { input: JSON.stringify({ collection: 'products' }) },
Expand Down Expand Up @@ -630,10 +629,11 @@ test('saved report snapshots stay fixed while live pages refresh; revisions requ
kind: 'report',
})
expect(initial.result.nodes[0].props.value).toBe(1)
await op(page, 'createDoc', {
await op(page, 'save', {
collection: 'recipes',
id: 'soup',
doc: { title: 'Soup', instructions: '## Simmer\nCook slowly.' },
create: true,
})
const after = await op(page, 'readInterface', {
id: 'recipe-count',
Expand Down Expand Up @@ -747,10 +747,11 @@ test('collection events refresh affected interface components without waiting fo
const body = request.postData()
if (body?.includes('"componentIds"')) refreshes.push(body)
})
await op(page, 'createDoc', {
await op(page, 'save', {
collection: 'recipes',
id: 'pasta',
doc: { title: 'Pasta', instructions: '## Boil\nCook pasta.' },
create: true,
})
await expect(
page.getByRole('cell', { name: 'Pasta', exact: true }),
Expand Down Expand Up @@ -827,10 +828,11 @@ test('admins enable a reviewed snapshot schedule, pause/resume it, and run the a
report.getByText('Scheduled recipe count', { exact: true }),
).toBeVisible()
await expect(report.locator('.cms-interface-metric')).toHaveText('2')
await op(page, 'createDoc', {
await op(page, 'save', {
collection: 'recipes',
id: 'toast',
doc: { title: 'Toast' },
create: true,
})
await expect(report.locator('.cms-interface-metric')).toHaveText('2')
await page
Expand Down
20 changes: 9 additions & 11 deletions app/base/scripts/smoke-docker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,8 @@ try {
await start(volumes[0])
await healthy()
assert.equal(
(
await request(
'/api/cms/v1/ops/listPublishedDocuments',
{ collection: 'products' },
'',
)
).status,
(await request('/api/cms/v1/ops/list', { collection: 'products' }, ''))
.status,
401,
)
const setup = await request('/api/base-auth/setup', {
Expand Down Expand Up @@ -213,10 +208,11 @@ try {
}
assert((await op('baseValidateSchemaDraft', schemaRef)).canPublish)
await op('basePublishSchemaDraft', schemaRef)
await op('createDoc', {
await op('save', {
collection: 'customers',
id: 'ada',
doc: { title: 'Ada', published: true },
create: true,
})
assert.equal(
(await op('getDocument', { collection: 'customers', id: 'ada' })).doc
Expand Down Expand Up @@ -286,7 +282,7 @@ try {
name: 'recipes',
draftVersion: recipeDraft.draft.version,
})
await op('createDoc', {
await op('save', {
collection: 'recipes',
id: 'cake',
doc: {
Expand All @@ -298,6 +294,7 @@ try {
{ name: 'Eggs', quantity: 2, unit: 'each' },
],
},
create: true,
})
const recipeNext = structuredClone(recipeDraft.draft.definition)
recipeNext.fields
Expand Down Expand Up @@ -376,7 +373,7 @@ try {
assert.equal(
(
await request(
'/api/cms/v1/ops/listPublishedDocuments',
'/api/cms/v1/ops/list',
{ collection: 'reports' },
viewerCookie,
)
Expand Down Expand Up @@ -504,10 +501,11 @@ try {
}
}
await readUntil((text) => text.includes('event: connected'))
await op('createDoc', {
await op('save', {
collection: 'recipes',
id: 'temporary-live-recipe',
doc: { title: 'Temporary live recipe' },
create: true,
})
await readUntil((text) => text.includes('"id":"temporary-live-recipe"'))
await op('deleteDoc', { collection: 'recipes', id: 'temporary-live-recipe' })
Expand Down
2 changes: 1 addition & 1 deletion app/base/src/chat.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ ${mayConfigure ? `You may propose collection schemas. Current schema versions: $
Use baseListSchemas before creating or editing a schema; pass its exact version and draftVersion as expectedVersion and expectedDraftVersion to baseProposeCollection. New collections use zero for both. Re-read before retrying conflicts. Preserve existing fields and only add fields. Internal protected collections cannot be changed.
Schema definition: {name:lowercase_underscore_name,label,titleField:"title",fields:[{name,label,type,required?,defaultValue?,options?,collection?,many?,fields?}]}. Supported types: ${fieldTypes.join(', ')}. Objects use type "group" with fields; arrays of objects use type "array" with fields. Ingredients are usually an array of objects with name, quantity, unit. Food images use a URL field and instructions use markdown. Only title needs required:true initially; avoid unsupported properties and executable validation. Select options are strings. Relation targets must already be approved collections. A published boolean is added automatically.
baseProposeCollection saves and validates a draft. It does NOT publish. Tell the customer to use the chat's Approve collection button (or Collections) and STOP before creating data in that collection. Approval is a human UI action, never a tool or a chat instruction. On the next turn, consult current collections before adding data.
For records, use create_document or update_document. These produce proposals; the customer approves records in chat or Review. Never claim records are saved before approval. A query sees committed records; use read_document when explicitly asked about a pending proposal. If the user asks for sample data you may invent clearly identified examples; query answers must use tool results. For counts use search_documents.total. Fetch more pages when aggregating and state any limit. Preserve nested objects and arrays. Do not invent image URLs. Use concise Markdown, including tables when useful.`
For records, use save_document (with create: true for a new record). It produces proposals; the customer approves records in chat or Review. Never claim records are saved before approval. A query sees committed records; use get_document when explicitly asked about a pending proposal. If the user asks for sample data you may invent clearly identified examples; query answers must use tool results. For counts use search_documents.total. Fetch more pages when aggregating and state any limit. Preserve nested objects and arrays. Do not invent image URLs. Use concise Markdown, including tables when useful.`
}
84 changes: 64 additions & 20 deletions app/base/src/operations.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import {
listInterfaces,
accessContext,
systemContext,
readDocumentAs,
listAs,
withMode,
getAs,
} from '@tanstack/cms-core/server'
import { evacuateWordPress } from '@tanstack/cms-migrate-wp'
import { listSkills } from '@tanstack/cms-skills'
Expand All @@ -49,7 +49,15 @@ function guardSources(ctx: CmsOpContext) {
}
}
async function committed(name: string, id: string, ctx: CmsOpContext) {
const doc = await readDocumentAs(CHECKED, name, id)
const doc =
(
await getAs(CHECKED, {
collection: name,
id,
staged: false,
populate: false,
})
)?.doc ?? null
if (!doc) throw new CmsError('Document not found.', 'NOT_FOUND')
assertCollectionAccess(ctx.session, name, 'read', doc)
return redactDoc(name, doc, ctx.session)
Expand Down Expand Up @@ -213,7 +221,15 @@ export async function submitReport(
ctx: CmsOpContext,
) {
const id = `coffee-trends-${data.endDate}`
const before = await readDocumentAs(CHECKED, 'reports', id)
const before =
(
await getAs(CHECKED, {
collection: 'reports',
id,
staged: false,
populate: false,
})
)?.doc ?? null
assertCollectionAccess(
ctx.session,
'reports',
Expand Down Expand Up @@ -316,11 +332,15 @@ export async function evacuateWordPressToBase(
let documentsImported = 0
for (const docItem of evacResult.documents) {
if (!getCmsConfig().collections[docItem.collection]) continue
const existing = await readDocumentAs(
CHECKED,
docItem.collection,
docItem.id,
)
const existing =
(
await getAs(CHECKED, {
collection: docItem.collection,
id: docItem.id,
staged: false,
populate: false,
})
)?.doc ?? null
await commitDocument(docItem.collection, docItem.id, docItem.doc, {
session: ctx.session,
actor,
Expand All @@ -337,7 +357,15 @@ export async function evacuateWordPressToBase(
const rule = evacResult.redirects[i]
if (!rule) continue
const redirId = `wp-redirect-${rule.wpId}-${i + 1}`
const existing = await readDocumentAs(CHECKED, 'redirects', redirId)
const existing =
(
await getAs(CHECKED, {
collection: 'redirects',
id: redirId,
staged: false,
populate: false,
})
)?.doc ?? null
await commitDocument(
'redirects',
redirId,
Expand All @@ -364,11 +392,15 @@ export async function evacuateWordPressToBase(
let stagedReviewCount = 0
for (const seoProposal of evacResult.seoAuditProposals) {
if (!getCmsConfig().collections[seoProposal.collection]) continue
const current = await readDocumentAs(
CHECKED,
seoProposal.collection,
seoProposal.docId,
)
const current =
(
await getAs(CHECKED, {
collection: seoProposal.collection,
id: seoProposal.docId,
staged: false,
populate: false,
})
)?.doc ?? null
if (!current) continue
await stageWrite({
collection: seoProposal.collection,
Expand All @@ -390,11 +422,15 @@ export async function evacuateWordPressToBase(
for (const skillProp of evacResult.skillProposals) {
for (const iface of skillProp.interfaceProposals) {
if (!getCmsConfig().collections.interfaces) continue
const existingIface = await readDocumentAs(
CHECKED,
'interfaces',
iface.id,
)
const existingIface =
(
await getAs(CHECKED, {
collection: 'interfaces',
id: iface.id,
staged: false,
populate: false,
})
)?.doc ?? null
await stageWrite({
collection: 'interfaces',
docId: iface.id,
Expand Down Expand Up @@ -440,7 +476,15 @@ export async function evacuateWordPressToBase(

// 7. Update shop settings with migrated site title if available
if (evacResult.site.title) {
const beforeShop = await readDocumentAs(CHECKED, 'shop', 'settings')
const beforeShop =
(
await getAs(CHECKED, {
collection: 'shop',
id: 'settings',
staged: false,
populate: false,
})
)?.doc ?? null
if (beforeShop) {
await commitDocument(
'shop',
Expand Down
Loading
Loading