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
5 changes: 5 additions & 0 deletions .changeset/cli-read-verbs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/cms-cli': patch
---

`tanstack-cms atproto publish` reads the document with `getAs` instead of the deprecated `readDocumentAs`. Behaviour is unchanged: it still reads the published document as the public.
2 changes: 1 addition & 1 deletion .claude/skills/astro-starlight-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ components themselves are the gap. Self-test: `node scripts/mdx-to-markdown.mjs`
naming the files); key frontmatter, slugs, sidebar fields, and a body
survived byte-for-byte (minus flattened MDX); loading through the engine
works (`seedContent({ force: true })` or `parseCmsExport` +
`importContent`, then `queryDocuments`/`readDocument`); and
`importContent`, then `listAs`/`getAs`); and
`resolveRedirect('/start/installation/')` from `@tanstack/cms-core/server`
returns the new URL. `closeStore()` after each test.
- Live check: `pnpm --filter <app> dev`; the sidebar matches Starlight's,
Expand Down
6 changes: 3 additions & 3 deletions .claude/skills/emdash-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ Self-test: `node scripts/portable-text-to-markdown.mjs`.
`content` (hardcode them with a comment naming the file); titles, slugs,
excerpts, and a Portable Text body survived; and loading through the engine
works (`seedContent({ force: true })` or `parseCmsExport` + `importContent`,
then `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` and
`readDocumentAs`/`queryDocuments` with `populate: true` resolving `authors`).
then `listAs(ctx, { where: { tags: 'opinion' } })` and `getAs`, whose
default `relations` resolve `authors`).
`closeStore()` after each test.
- Live check: `pnpm --filter <app> dev`, then
`curl -X POST localhost:<port>/api/cms/v1/ops/listDocumentSummaries -H 'content-type: application/json' -d '{"collection":"post","status":"all"}'`
Expand All @@ -240,7 +240,7 @@ tables you used, the Portable Text coverage, how the content was loaded, and a

- **Hierarchical taxonomies** — flattened into a `multiselect` (parents lost),
or modelled as a collection + `relation`. Taxonomy archive pages
(`/category/<slug>`) need an app route (`queryDocumentsAs(ctx, { where })`).
(`/category/<slug>`) need an app route (`listAs(ctx, { where })`).
- **Bylines** — the built-in post page renders the plain-text `author` field
(declared as `bylineField`), not the `authors` relation; byline roles and ordering beyond the array order
need app work.
Expand Down
60 changes: 30 additions & 30 deletions .claude/skills/payload-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,31 +116,31 @@ functions (AI adapter factories, `webhooks[].secret: () => process.env.X`).

**Field types** (Payload → core `type`):

| Payload | core `type` | Notes |
| --------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------- |
| `text` | `text` | |
| `textarea` | `textarea` | |
| `email` | `email` | format-validated |
| `number` | `number` | `min`/`max` carry over |
| `checkbox` | `boolean` | |
| `select`, `radio` | `select` with `options` | `{ label, value }` options carry over as-is |
| `select` with `hasMany` | `multiselect` with `options` | |
| `date` | `datetime` (or `date` for day-only) | Payload stores ISO datetimes |
| `code` | `textarea` | or a `code` block inside `blocks` |
| `json` | `json` | |
| `point` | `json` or a `group` of two numbers | no geo queries |
| `upload` (`relationTo: 'media'`) | `image` | stores the media URL string |
| `relationship` (one target) | `relation` + `collection` | stores the target id |
| `relationship` with `hasMany` | `relation` + `many: true` | array of ids; `populateRelations` / `populate: true` resolves them |
| `relationship` polymorphic (`relationTo: []`) | — | split into one `relation` per target, or `json` — gap report |
| `richText` (Lexical), flat | `richtext` (or `markdown`) | both store Markdown; see §5 |
| `richText` (Lexical), in a block | `richText` block `markdown` | see §5 |
| `blocks` | `blocks` | map each block type → core block (below); keep blocks one level deep |
| `group` | `group` with `fields` | nested object |
| `array` | `array` with `fields` | list of nested objects; `minRows`/`maxRows` → `min`/`max` |
| `tabs` (named) | `group` per tab | unnamed tabs, `row`, `collapsible` are layout only → flatten their fields |
| a text slug (`/about` paths) | `text` + `unique: true` | use `slug` only for kebab-case values (it validates the format) |
| `join`, `ui` | — | `join` is a computed reverse lookup: `queryDocumentsAs(ctx, { where })` instead |
| Payload | core `type` | Notes |
| --------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- |
| `text` | `text` | |
| `textarea` | `textarea` | |
| `email` | `email` | format-validated |
| `number` | `number` | `min`/`max` carry over |
| `checkbox` | `boolean` | |
| `select`, `radio` | `select` with `options` | `{ label, value }` options carry over as-is |
| `select` with `hasMany` | `multiselect` with `options` | |
| `date` | `datetime` (or `date` for day-only) | Payload stores ISO datetimes |
| `code` | `textarea` | or a `code` block inside `blocks` |
| `json` | `json` | |
| `point` | `json` or a `group` of two numbers | no geo queries |
| `upload` (`relationTo: 'media'`) | `image` | stores the media URL string |
| `relationship` (one target) | `relation` + `collection` | stores the target id |
| `relationship` with `hasMany` | `relation` + `many: true` | array of ids; `populateRelations` / `populate: true` resolves them |
| `relationship` polymorphic (`relationTo: []`) | — | split into one `relation` per target, or `json` — gap report |
| `richText` (Lexical), flat | `richtext` (or `markdown`) | both store Markdown; see §5 |
| `richText` (Lexical), in a block | `richText` block `markdown` | see §5 |
| `blocks` | `blocks` | map each block type → core block (below); keep blocks one level deep |
| `group` | `group` with `fields` | nested object |
| `array` | `array` with `fields` | list of nested objects; `minRows`/`maxRows` → `min`/`max` |
| `tabs` (named) | `group` per tab | unnamed tabs, `row`, `collapsible` are layout only → flatten their fields |
| a text slug (`/about` paths) | `text` + `unique: true` | use `slug` only for kebab-case values (it validates the format) |
| `join`, `ui` | — | `join` is a computed reverse lookup: `listAs(ctx, { where })` instead |

**Field options:** `required` → `required: true`; `unique` → `unique: true`;
`index` → `index: true`; `defaultValue` → `defaultValue`; `admin.description` →
Expand Down Expand Up @@ -176,9 +176,9 @@ Payload `{ data, originalDoc, req, operation }` → core
`{ doc, id }` (`postRead`), `{ id, actor }` (`preDelete`). Return the
transformed doc from `preValidate` / `postValidate` / `postRead`; throw to
abort a write. Keep hooks under about 50ms. Replace `req.payload.find(…)` with
`queryDocuments`/`readDocumentAs` from `@tanstack/cms-core/server`, and attach
those hooks in the runtime config
(`defineCms(definition, { collections: { post: { hooks } } })`). Hooks that
`listAs`/`getAs` from `@tanstack/cms-core/server`, and attach those hooks in
the runtime config (`defineCms(definition, { collections: { post: { hooks } } })`).
Hooks that
only fan out to other systems (cache purges, search indexing) usually become
`defineCms({ webhooks })` instead. No equivalent: `beforeOperation`,
`afterOperation`, `beforeRead`, `afterError`, auth hooks.
Expand Down Expand Up @@ -271,8 +271,8 @@ custom nodes and list what isn't converted in the gap report. Self-test:
where they came from, e.g. the Payload REST `totalDocs`); key fields
survived (titles, slugs, a Lexical-converted body); and loading through the
engine works (`seedContent({ force: true })` or `parseCmsExport` +
`importContent` from `@tanstack/cms-core/server`, then `queryDocuments` /
`readDocumentAs`, with `populate: true` for relations). `closeStore()` after
`importContent` from `@tanstack/cms-core/server`, then `listAs` / `getAs`,
which populate relations by default). `closeStore()` after
each test.
- Live check: `pnpm --filter <app> dev`, then
`curl -X POST localhost:<port>/api/cms/v1/ops/listDocumentSummaries -H 'content-type: application/json' -d '{"collection":"post","status":"all"}'`
Expand Down
68 changes: 49 additions & 19 deletions .claude/skills/voting/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: voting
description: Build a native upvote/downvote (voting) feature on a TanStack CMS 1.0 (@tanstack/cms-core) app. Use when the user asks to add voting, likes, reactions, upvotes, "hacker news style" ranking, or "reddit style" scores to posts or any collection. Produces schema additions, a vote write path with one-vote-per-user semantics, indexed read paths (counts, top-N), a vote UI component, and tests — all native to the CMS (collections, queryDocuments, revisions) rather than a bolted-on plugin.
description: Build a native upvote/downvote (voting) feature on a TanStack CMS 1.0 (@tanstack/cms-core) app. Use when the user asks to add voting, likes, reactions, upvotes, "hacker news style" ranking, or "reddit style" scores to posts or any collection. Produces schema additions, a vote write path with one-vote-per-user semantics, indexed read paths (counts, top-N), a vote UI component, and tests — all native to the CMS (collections, get/list reads, revisions) rather than a bolted-on plugin.
---

# Voting on TanStack CMS
Expand All @@ -20,10 +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 `readDocumentAs`, `queryDocumentsAs`, `commitDocument`, and
`await` every `getAs`, `listAs`, `readDocumentAs`, `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.
`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.

## 0. Prerequisites

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

Vote documents are never `published`, so they don't appear in the public
read paths (`listPublishedDocuments`, `getPublicDocument`); `access.read`
read paths (`get`, `list`, and the older `listPublishedDocuments`); `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 @@ -126,8 +129,9 @@ import { createServerFn } from '@tanstack/react-start'
import {
commitDocument,
deleteDocument,
getAs,
listAs,
publicContext,
queryDocumentsAs,
readDocumentAs,
requireAuthenticated,
systemContext,
Expand All @@ -143,7 +147,12 @@ export async function castVoteForVoter(
) {
if (value !== 1 && value !== -1) throw new Error('Invalid vote')
// Voters only ever see published posts.
if (!(await readDocumentAs(publicContext(), 'post', postId))) {
const visible = await getAs(publicContext(), {
collection: 'post',
id: postId,
populate: false,
})
if (!visible) {
throw new Error('Post not found')
}

Expand All @@ -159,13 +168,25 @@ export async function castVoteForVoter(
{ actor: voterId },
)
}
// Recount from source; never trust client-supplied counts.
const votes = await queryDocumentsAs(VOTES, {
collection: 'vote',
where: { post: postId },
})
const upvotes = votes.items.filter((v) => Number(v.doc.value) > 0).length
const downvotes = votes.items.filter((v) => Number(v.doc.value) < 0).length
// Recount from source; never trust client-supplied counts. A list page
// holds at most 500 documents, so page through every vote.
let upvotes = 0
let downvotes = 0
let cursor: string | undefined
do {
const votes = await listAs(VOTES, {
collection: 'vote',
where: { post: postId },
limit: 500,
cursor,
populate: false,
})
for (const v of votes.items) {
if (Number(v.doc.value) > 0) upvotes++
else if (Number(v.doc.value) < 0) downvotes++
}
cursor = votes.nextCursor
} 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)
Expand All @@ -190,8 +211,10 @@ export const castVote = createServerFn({ method: 'POST' })
})
```

The worked example also resolves posts by slug (`readDocumentBySlugAs`) so
links using either form work.
The worked example reads the post with
`getAs(publicContext(), { collection: 'post', id: postId })`, then
`{ locator: postId }` (the slug) when no post has that id, so links using
either form work.

**Atomicity gap (report it, don't hide it).** `commitDocument` and
`deleteDocument` each run in their own storage transaction, so the vote write
Expand Down Expand Up @@ -228,7 +251,13 @@ report (§8). Concurrent votes on the same post can also race the tally
```ts
// What the UI needs for one post:
export async function getVoteState(postId: string, voterId?: string) {
const post = await readDocumentAs(publicContext(), 'post', postId)
const post = (
await getAs(publicContext(), {
collection: 'post',
id: postId,
populate: false,
})
)?.doc
const mine = voterId
? await readDocumentAs(VOTES, 'vote', voteId(postId, voterId))
: null
Expand All @@ -242,10 +271,11 @@ export async function getVoteState(postId: string, voterId?: string) {

// Top posts — score is an indexed number field:
export async function getTopPosts(limit = 10) {
return queryDocumentsAs(publicContext(), {
return listAs(publicContext(), {
collection: 'post',
sort: { field: 'score', dir: 'desc' },
limit,
populate: false,
})
}
```
Expand Down Expand Up @@ -300,11 +330,11 @@ a temp `dataDir` per test via `defineCms({ dataDir, collections: [...] })` and
- invalid value / unknown post / malformed voter id throw
- `getVoteState` reports the caller's own vote
- `getTopPosts` orders by score desc
- vote docs appear in `queryDocumentsAs(VOTES, { collection: 'vote' })` (auditability)
- vote docs appear in `listAs(VOTES, { collection: 'vote' })` (auditability)

Then write the **gap report**: every place where you reached for something
the core doesn't have. Known ones in 1.0: composable transactions across
document writes, composite uniqueness, aggregation queries ("top voters",
"votes today" mean scanning with `queryDocuments`), and app-defined rate-limit
"votes today" mean scanning with `listAs`), and app-defined rate-limit
buckets. Be specific: name the primitive, the use case, and the workaround you
used.
Loading
Loading