Skip to content

Commit 3d1e7b2

Browse files
jherrclaude
andcommitted
feat(kody): headless-api CMS starter as a Kody package app (spike)
First of the four CMS-starters-on-Kody (spec §3.1), the platform-proof spike. Converts starters/headless-api to a hosted Kody package app: node:http server -> default-exported `{ fetch }` entry (D8); embedded storage -> external Postgres via createPostgresStorage with a secret resolver (D2); two Kody jobs calling runEventDispatch / runScheduledPublishing (D6); header-role auth unchanged (D5). Schema is carried over verbatim. Built and locally validated against a real Postgres (scripts/local-smoke.mts -> SMOKE PASS): fetch entry + Postgres storage + role auth (editor ok / viewer 403) + governance stage/approve/read + both jobs. Lives in a top-level kody/ dir outside the pnpm workspace globs, so it does not affect any monorepo check. Dep URLs are pkg-pr-new @ref placeholders; remaining go-day deltas (URL pin, U1 secret accessor, kody.jobs schema confirm, U2 pg-over-workerd) are in kody/headless-api/GO-DAY.md. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent eefc321 commit 3d1e7b2

12 files changed

Lines changed: 427 additions & 0 deletions

File tree

‎kody/headless-api/.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

‎kody/headless-api/AGENTS.md‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# @tanstack/cms-starter-headless-api — agent notes
2+
3+
## What this is
4+
5+
The headless-api Kody variant of the monorepo starter `starters/headless-api`.
6+
Only four things change from that starter (spec §3.1): storage (embedded →
7+
external Postgres), the entry (node:http server → Kody `{ fetch }`), background
8+
work (none → two Kody jobs), and the docs. The content schema
9+
(`src/cms.definition.ts`) is carried over verbatim.
10+
11+
## Imports / shape
12+
13+
- `src/entry.ts` — `kody.app.entry`. Default-exports `{ fetch }`; lazily
14+
registers the CMS on the first request, then serves `createCmsApiHandler()`.
15+
- `src/cms.config.ts` — `registerHeadlessCms()` / `ensureRegistered()` (singleton
16+
guard). Passes `storage: createPostgresStorage({ connectionString: () => getDatabaseUrl() })`.
17+
- `src/secrets.ts` — `getDatabaseUrl()`. The **one go-day fill-in** (U1): a
18+
SYNCHRONOUS, context-free read of `CMS_DATABASE_URL` because the store's
19+
resolver is `() => string | undefined`, called at init outside request scope.
20+
Locally reads `process.env`; on Kody, read the package secret synchronously
21+
via `kody:runtime` — or capture it on first request if Kody only exposes it
22+
request-scoped.
23+
- `src/jobs.ts` — `outboxDrain` → `runEventDispatch`, `schedulerTick` →
24+
`runScheduledPublishing` (both public `@tanstack/cms-core/server` exports that
25+
resolve storage internally). Declared under `package.json#kody.jobs`.
26+
27+
## Smoke test
28+
29+
Local (real Postgres, proves storage + auth + governance + jobs):
30+
31+
```sh
32+
createdb kody_headless_smoke # or any empty Postgres db
33+
CMS_DATABASE_URL="postgres://user:pass@localhost:5432/kody_headless_smoke" \
34+
tsx scripts/local-smoke.mts # expects "SMOKE PASS"
35+
```
36+
37+
On Kody after publish: `appFetch` with `synthetic: true` —
38+
`POST /api/cms/v1/ops/save_document` with header `x-cms-role: editor` stages a
39+
write; `GET` reads it back after approval; `POST /api/mcp` lists tools.
40+
41+
## Edge cases / gotchas
42+
43+
- **Auth is the `x-cms-role` header**, not a bearer token, in this starter.
44+
Any role value authenticates as `actor-<role>`; `editor` can stage writes,
45+
`viewer` is denied (403). API-key/token issuance (`createApiKey`) is a
46+
separate path.
47+
- **Writes stage into governance** — they are invisible until `approve()`.
48+
- **`kody.jobs` field schema is best-effort** (`entry` + cron `schedule`).
49+
Confirm exact field names with `repoRunChecks` / the jobs guide on go-day;
50+
the handlers themselves are verified.
51+
- **`pg` over workerd TCP is unproven (U2).** If egress fails on Kody, swap the
52+
pool for a Neon serverless driver — config-side only, because the store types
53+
`PgPoolLike` as a structural interface (no package change).
54+
- `node_modules/` here is local symlink scaffolding for the smoke only; the real
55+
deps resolve from the pkg-pr-new URLs in `package.json` on Kody.

‎kody/headless-api/GO-DAY.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Go-day deltas — headless-api
2+
3+
Everything in this package is built and **locally validated** (real Postgres,
4+
`scripts/local-smoke.mts` → SMOKE PASS) against the workspace packages. What
5+
remains is only what requires the external blockers to clear.
6+
7+
## Blocked until the Preview builds land
8+
9+
1. **Pin dependency URLs.** Replace `@REF` in `package.json` for the four
10+
`@tanstack/cms-*` deps with the pkg-pr-new refs the Preview CI job reports
11+
(spec §7-1). `pg` stays an npm dep.
12+
13+
## Blocked on Kody (App install + `package:write` in the tanstack org)
14+
15+
2. **Publish via the git lane** (D3): `packageGetGitRemote({ create: true,
16+
name: '@tanstack/cms-starter-headless-api' })` → clone → copy this package in
17+
→ push → `packagePublishExternalPush`. If it returns `locked`, open the
18+
`approval_url`.
19+
3. **Set the `CMS_DATABASE_URL` package secret** to the prod Postgres string.
20+
4. **Resolve U1 (secret accessor).** Fill `src/secrets.ts#getDatabaseUrl` with
21+
the synchronous `kody:runtime` package-secret read. Confirm whether the value
22+
is available synchronously at module scope; if only request-scoped, capture
23+
it into the module cache on the first request (the resolver is sync by
24+
design — store types.ts:85).
25+
5. **Confirm `kody.jobs` field schema** via `repoRunChecks` (the manifest
26+
validator). Current best-effort shape: `{ entry: "./src/jobs.ts#<fn>",
27+
schedule: "*/5 * * * *" }`.
28+
6. **Run U2 test** (spec §7-5): the first REST call on the published app is the
29+
pg-over-workerd-TCP test. If egress fails, swap the pool for Neon's serverless
30+
driver — config-side only (`PgPoolLike` is a structural interface).
31+
32+
## Post-publish acceptance (spec §8)
33+
34+
`appFetch` (`synthetic: true`): seeded doc readable over REST with no auth;
35+
`x-cms-role` write succeeds and is attributed; MCP tool list answers; a second
36+
package importing `@tanstack/cms-client` reads the same document.
37+
38+
> Note: the §8 "seeded document readable with **no auth**" check needs a seed +
39+
> public read access — not yet added here (the smoke uses authenticated writes).
40+
> Add a small `seed` and confirm anonymous read on go-day.

‎kody/headless-api/README.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# @tanstack/cms-starter-headless-api
2+
3+
A TanStack CMS headless backend — REST, a typed client, and MCP over a single
4+
schema — running as a hosted Kody package app, with external Postgres as the
5+
only infrastructure you bring.
6+
7+
## Intent
8+
9+
Run a TanStack CMS headless backend (REST + typed client + MCP over one schema)
10+
as a hosted Kody app, with Postgres as the only infrastructure you bring. This
11+
is the platform-proof starter: it establishes the dependency, storage, secret,
12+
and job wiring that the UI starters (blog, contact-cards, themed-smb-site)
13+
reuse unchanged. It is API-only — there is no admin UI and no public site; API
14+
consumers and agents authenticate with a role and talk to one content schema
15+
over three transports.
16+
17+
## Prerequisites
18+
19+
- A Postgres database. Put its connection string in the Kody package secret
20+
**`CMS_DATABASE_URL`** (never in source — see `src/secrets.ts`).
21+
- The pkg-pr-new preview builds of `@tanstack/cms-core`, `-api`, `-client`, and
22+
`-store-postgres` (the `package.json` dependency URLs are pinned on go-day;
23+
see `GO-DAY.md`).
24+
25+
## Setup
26+
27+
1. Pin the four `@tanstack/cms-*` dependency URLs in `package.json` to the
28+
pkg-pr-new refs the Preview CI job reports.
29+
2. Set the `CMS_DATABASE_URL` package secret.
30+
3. Publish via the git lane (`packageGetGitRemote` → push →
31+
`packagePublishExternalPush`).
32+
33+
## How you know it's working
34+
35+
- `GET`/`POST` to `/api/cms/v1/ops/*` with an `x-cms-role` header reads and
36+
stages writes against the one content schema.
37+
- `POST /api/mcp` lists and calls the same operations as MCP tools.
38+
- Writes stage into governance and become visible after approval.
39+
- The `cms-outbox-drain` and `cms-scheduler-tick` jobs run every 5 minutes.
40+
41+
The `scripts/local-smoke.mts` script proves all of this locally against a real
42+
Postgres (see `AGENTS.md`).

‎kody/headless-api/package.json‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"name": "@tanstack/cms-starter-headless-api",
3+
"type": "module",
4+
"description": "TanStack CMS headless backend (REST + typed client + MCP over one schema) as a hosted Kody app.",
5+
"exports": {
6+
".": "./src/entry.ts"
7+
},
8+
"scripts": {
9+
"smoke": "tsx scripts/local-smoke.mts"
10+
},
11+
"dependencies": {
12+
"@tanstack/cms-api": "https://pkg.pr.new/@tanstack/cms-api@REF",
13+
"@tanstack/cms-client": "https://pkg.pr.new/@tanstack/cms-client@REF",
14+
"@tanstack/cms-core": "https://pkg.pr.new/@tanstack/cms-core@REF",
15+
"@tanstack/cms-store-postgres": "https://pkg.pr.new/@tanstack/cms-store-postgres@REF",
16+
"pg": "^8.13.0"
17+
},
18+
"devDependencies": {
19+
"@types/node": "^24.10.1",
20+
"tsx": "^4.23.12",
21+
"typescript": "5.9.3"
22+
},
23+
"kody": {
24+
"description": "A TanStack CMS headless backend — REST, typed client, and MCP over one schema, on Postgres.",
25+
"category": "apps",
26+
"app": {
27+
"entry": "./src/entry.ts"
28+
},
29+
"jobs": {
30+
"cms-outbox-drain": {
31+
"entry": "./src/jobs.ts#outboxDrain",
32+
"schedule": "*/5 * * * *"
33+
},
34+
"cms-scheduler-tick": {
35+
"entry": "./src/jobs.ts#schedulerTick",
36+
"schedule": "*/5 * * * *"
37+
}
38+
}
39+
}
40+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Local validation of the headless-api Kody variant (spec §3.1) against a real
2+
// Postgres via createPostgresStorage + the pg driver — the prod storage path,
3+
// minus the workerd/U2 question which can't be tested off-platform.
4+
//
5+
// Proves: entry.ts `{ fetch }` handler + Postgres storage substitution (D2) +
6+
// header-role auth (D5) + governance staging/approval + the two jobs (D6).
7+
//
8+
// Run from this package dir: CMS_DATABASE_URL=… tsx scripts/local-smoke.mts
9+
import entry from '../src/entry.ts'
10+
import { outboxDrain, schedulerTick } from '../src/jobs.ts'
11+
import {
12+
approve,
13+
closeStore,
14+
getAs,
15+
listPending,
16+
systemContext,
17+
} from '@tanstack/cms-core/server'
18+
19+
const ops = 'http://localhost/api/cms/v1/ops'
20+
let failures = 0
21+
function check(label: string, ok: boolean, detail?: unknown) {
22+
console.log(`${ok ? '✅' : '❌'} ${label}${detail !== undefined && !ok ? ` — ${JSON.stringify(detail)}` : ''}`)
23+
if (!ok) failures++
24+
}
25+
26+
async function post(op: string, role: string, body: unknown) {
27+
return entry.fetch(
28+
new Request(`${ops}/${op}`, {
29+
method: 'POST',
30+
headers: { 'content-type': 'application/json', 'x-cms-role': role },
31+
body: JSON.stringify(body),
32+
}),
33+
)
34+
}
35+
36+
// 1. Editor stages a write over REST (header-role auth) through the fetch entry.
37+
const writeRes = await post('save_document', 'editor', {
38+
collection: 'contentItem',
39+
id: 'item-smoke',
40+
doc: { title: 'Smoke Item', channel: 'ios', priority: 2 },
41+
create: true,
42+
})
43+
check('editor save_document accepted (2xx)', writeRes.ok, writeRes.status)
44+
45+
// 2. Viewer is denied the same write.
46+
const viewerRes = await post('save_document', 'viewer', {
47+
collection: 'contentItem',
48+
id: 'item-denied',
49+
doc: { title: 'Denied' },
50+
create: true,
51+
})
52+
check('viewer write denied (403)', viewerRes.status === 403, viewerRes.status)
53+
54+
// 3. Governance: the editor write is staged, invisible before approval.
55+
const pending = await listPending()
56+
check('write is staged in governance (>=1 pending)', pending.length >= 1, pending.length)
57+
const beforeApprove =
58+
(await getAs(systemContext('smoke'), {
59+
collection: 'contentItem',
60+
id: 'item-smoke',
61+
staged: false,
62+
populate: false,
63+
}))?.doc ?? null
64+
check('staged doc invisible before approval', beforeApprove === null)
65+
66+
// 4. Approve, then the doc is readable from Postgres.
67+
for (const p of pending) await approve(p.id)
68+
const committed =
69+
(await getAs(systemContext('smoke'), {
70+
collection: 'contentItem',
71+
id: 'item-smoke',
72+
staged: false,
73+
populate: false,
74+
}))?.doc ?? null
75+
check('doc readable after approval', committed?.title === 'Smoke Item', committed)
76+
77+
// 5. The two Kody jobs run without throwing (they resolve storage internally).
78+
try {
79+
await outboxDrain()
80+
await schedulerTick()
81+
check('cms-outbox-drain + cms-scheduler-tick ran', true)
82+
} catch (err) {
83+
check('cms-outbox-drain + cms-scheduler-tick ran', false, String(err))
84+
}
85+
86+
await closeStore()
87+
console.log(failures === 0 ? '\nSMOKE PASS' : `\nSMOKE FAIL (${failures})`)
88+
process.exit(failures === 0 ? 0 : 1)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { defineCms } from '@tanstack/cms-core'
2+
import type { CmsConfig } from '@tanstack/cms-core'
3+
import { createPostgresStorage } from '@tanstack/cms-store-postgres'
4+
import { definition } from './cms.definition'
5+
import { getDatabaseUrl } from './secrets'
6+
7+
// Kody variant of starters/headless-api. Differences from the monorepo starter
8+
// (spec §3.1): no `dataDir`/embedded storage — external Postgres via the
9+
// resolver form so the connection string is read from the Kody secret at
10+
// runtime and never baked in (D2). Header-role auth is unchanged (D5).
11+
export function registerHeadlessCms() {
12+
const auth: NonNullable<CmsConfig['auth']> = {
13+
getUser: ({ request }) => {
14+
const role = request.headers.get('x-cms-role')
15+
if (role) {
16+
return { id: `actor-${role}`, name: role, role }
17+
}
18+
return null
19+
},
20+
}
21+
22+
return defineCms(definition, {
23+
blockTypes: [],
24+
auth,
25+
// `connectionString` accepts a resolver, so the secret stays out of the
26+
// build and is read at connect time (store-postgres types.ts:85).
27+
storage: createPostgresStorage({ connectionString: () => getDatabaseUrl() }),
28+
})
29+
}
30+
31+
// Register at most once per isolate so the fetch handler and the jobs share a
32+
// single CMS instance / Postgres pool instead of re-creating it per request or
33+
// per tick.
34+
let registered = false
35+
export function ensureRegistered(): void {
36+
if (registered) return
37+
registerHeadlessCms()
38+
registered = true
39+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import {
2+
defineCmsDefinition,
3+
defineCollection,
4+
} from '@tanstack/cms-core/definition'
5+
6+
// Schema is carried over verbatim from the monorepo starter
7+
// (starters/headless-api/src/cms.definition.ts). The Kody variant changes only
8+
// storage, auth, entry, and jobs — never the content model (spec §3.1).
9+
export const definition = defineCmsDefinition({
10+
collections: [
11+
defineCollection({
12+
name: 'contentItem',
13+
label: 'Content Items',
14+
titleField: 'title',
15+
bodyField: 'body',
16+
fields: [
17+
{ name: 'title', label: 'Title', type: 'text', required: true },
18+
{ name: 'slug', label: 'Slug', type: 'slug', from: 'title' },
19+
{
20+
name: 'channel',
21+
label: 'Channel',
22+
type: 'select',
23+
options: ['web', 'ios', 'android', 'agent'],
24+
defaultValue: 'web',
25+
},
26+
{
27+
name: 'priority',
28+
label: 'Priority',
29+
type: 'number',
30+
defaultValue: 1,
31+
},
32+
{ name: 'body', label: 'Body', type: 'richtext' },
33+
],
34+
}),
35+
],
36+
})

‎kody/headless-api/src/entry.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { createCmsApiHandler } from '@tanstack/cms-api/http'
2+
import { ensureRegistered } from './cms.config'
3+
4+
// kody.app.entry — the whole adapter. The node:http wrapper from the monorepo
5+
// starter's server.ts is gone; the handler it wrapped is already a fetch
6+
// handler, and Kody's entry contract is a default-exported `{ fetch }` that
7+
// receives the mount-stripped Request (spec §3.1 step 2, D8).
8+
//
9+
// Registration is lazy so the first request (not module load) constructs the
10+
// CMS and its Postgres pool — this is also where a request-scoped secret could
11+
// be captured if §9-U1 takes that branch.
12+
let handler: ((request: Request) => Promise<Response>) | undefined
13+
14+
export default {
15+
async fetch(request: Request): Promise<Response> {
16+
if (!handler) {
17+
ensureRegistered()
18+
handler = createCmsApiHandler()
19+
}
20+
return handler(request)
21+
},
22+
}

0 commit comments

Comments
 (0)