diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..3f51909d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,63 @@ +# AGENTS — TanStack CMS monorepo + +## Status: pre-publication — restructure freely + +This library is **pre-publication**. None of the `@tanstack/cms-*` / `@tanstack/search-*` +packages are on npm, and **nothing outside this repo depends on them**. That means: + +- **Break public APIs at will.** Rename, move, split, merge, or delete modules, + exports, entry points, and types whenever it makes the design better. No + backward-compatibility burden, no deprecation cycles, no changesets required + for consumer-facing breaks. +- **Reshape package boundaries freely** — new entry points (e.g. a tree-shakeable + `/read` surface), new packages, re-layering of `core` internals, etc. +- The only bar is **internal consistency**: the monorepo must still build and its + tests must pass after a change. Update all in-repo call sites (apps, examples, + starters) as part of the same change. + +Don't preserve an awkward API out of compat fear — spindle, fold, and mutilate +as needed, then make the whole repo green. + +## Architectural direction (edge-first reads) + +Deploying to edge runtimes (e.g. Kody/workerd) proved that the **read/render +path must be tree-shakeable to a tiny bundle with no server engine** — no +`@tanstack/cms-core/server` barrel, no embedded PGlite (WASM/eval), no AI / +code-mode / MCP, no `node:*`. See issues #63 (edge-read refactor) and #64 (Kody +platform ask for the write/admin engine). Target split: + +- **read path** (public pages): pure query + renderers, edge-deployable. +- **write / admin / migrate path**: the heavy engine, runs on a warm/Node-ish + runtime, never in the hot read worker. + +## Capability injection — core never imports an optional capability + +The engine ships no built-in storage, AI, code-mode, or MCP. Each is an **opt-in +capability the app injects** via `defineCms`, supplied by a dedicated entry whose +static imports pull the heavy dependency. Core never imports these packages, so +they only enter a bundle when the app imports the opt-in entry. This is enforced +at **bundle time** (not just runtime) by `packages/core/tests/bundle-seams.test.ts` +— a dynamic `import()` is not enough, because a single-file bundler inlines it. + +| Capability | Inject into `defineCms` | Opt-in entry | Heavy dep | +| -------------------- | ---------------------------------------------------------------- | --------------------------------------- | ---------------------------------- | +| Storage | `storage: createPgliteStorage` (a `StorageFactory`) | `@tanstack/cms-store-postgres/pglite` | PGlite (WASM) | +| AI agent tools | `ai: { runtime: aiRuntime() }` | `@tanstack/cms-core/ai` | `@tanstack/ai` | +| Code-mode interfaces | `interfaces: { collection, runtime: quickjsInterfaceRuntime() }` | `@tanstack/cms-core/interfaces-quickjs` | QuickJS + `@tanstack/ai-code-mode` | +| WebMCP (browser) | import `startWebMcpServer` | `@tanstack/cms-core/webmcp` | MCP SDK + MCP-B | +| HTTP MCP (server) | `createCmsApiHandler({ mcp: cmsMcp })` | `@tanstack/cms-api/mcp` | `@tanstack/ai-mcp` | + +Rules for new work: + +- **Never statically or dynamically import an optional capability from a core + engine module** (`index`, `server`, `read`, `config`, `storage`, `schema`, …). + If a feature needs one, add a capability type to the config (typed opaquely or + via `import type`, which is erased) and a dedicated opt-in entry that provides + it; the engine reads the injected value. +- **Fail with an actionable error.** A missing capability must throw a + `NOT_CONFIGURED` `CmsError` naming the exact import to add — never silently + fall back to a package of its own. +- MCP tools are agent tools: an app serving `/api/mcp` also needs `ai.runtime`. +- Tests get the embedded engine back via the `@tanstack/cms-store-postgres/testing` + vitest `setupFiles` (it calls `setDefaultStorageFactory`, an opt-in escape + hatch that stays `null` in production so bundles remain clean). diff --git a/app/base/package.json b/app/base/package.json index d6ad9ef8..d86f1bc9 100644 --- a/app/base/package.json +++ b/app/base/package.json @@ -33,6 +33,7 @@ "@tanstack/cms-core": "workspace:*", "@tanstack/cms-migrate-wp": "workspace:*", "@tanstack/cms-skills": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@tanstack/cms-ui-react": "workspace:*", "@tanstack/db": "0.15.2", "@tanstack/onboarding-core": "workspace:*", diff --git a/app/base/src/cms.config.ts b/app/base/src/cms.config.ts index 026a5e52..40a9f00b 100644 --- a/app/base/src/cms.config.ts +++ b/app/base/src/cms.config.ts @@ -1,17 +1,22 @@ import { createServerOnlyFn } from '@tanstack/react-start' import { defineCms, interfaceScheduleHandlers } from '@tanstack/cms-core' +import { aiRuntime } from '@tanstack/cms-core/ai' +import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { seed } from './seed' import { baseOps } from './operations' import { definition } from './cms.definition' import { collectionRuntimes } from './collection-runtime' export const cms = defineCms(definition, { + storage: createPgliteStorage, collections: collectionRuntimes, blockTypes: [], seed, ops: baseOps, interfaces: { collection: 'interfaces', + runtime: quickjsInterfaceRuntime(), scheduleSession: createServerOnlyFn(async (userId: string) => (await import('./auth.server')).scheduleSession(userId), ), @@ -35,6 +40,7 @@ export const cms = defineCms(definition, { events: { dispatch: 'manual' }, security: { trustForwardedHost: true }, ai: { + runtime: aiRuntime(), textAdapter: createServerOnlyFn(async () => (await import('./ai.server')).textAdapter(), ), diff --git a/app/base/src/schema-registry.server.ts b/app/base/src/schema-registry.server.ts index cb2e7969..c8536a27 100644 --- a/app/base/src/schema-registry.server.ts +++ b/app/base/src/schema-registry.server.ts @@ -13,7 +13,6 @@ import { } from '@tanstack/cms-core' import { CmsError, - ensureDefaultAdapter, getStorage, resolveStorageAdapter, shareCmsEventScope, @@ -78,10 +77,8 @@ async function registryFrom(tx: StorageOps): Promise { export async function readRegistry(): Promise { // Open the registry before getStorage can run scheduled publishing, so // scheduled documents use the persisted schema even on a cold process. - // `resolveStorageAdapter()` is synchronous, so the embedded default engine - // (when an app configures no `storage`) must be constructed first — otherwise - // it throws "Default storage is not initialized yet" on a cold process. - await ensureDefaultAdapter() + // `resolveStorageAdapter()` constructs the configured adapter synchronously + // (a `StorageFactory` is resolved on first access), so no priming step. const adapter = resolveStorageAdapter() await adapter.init() if (await adapter.getMeta(SCHEMA_META_KEY)) { @@ -606,7 +603,11 @@ export async function publishCollectionBlueprints( .map((e) => [e.name, runtimeCollection(e)]), ) if (cfg.storage) { - cfg.storage = snapshotStorage(cfg.storage, updatedRegistry.revision) + // `cfg.storage` may be a `StorageFactory`; snapshot the resolved adapter. + cfg.storage = snapshotStorage( + resolveStorageAdapter(), + updatedRegistry.revision, + ) } const storeCtx = registryContext.getStore() if (storeCtx) { diff --git a/app/base/tests/base.test.ts b/app/base/tests/base.test.ts index b8dd8604..d42fc0ee 100644 --- a/app/base/tests/base.test.ts +++ b/app/base/tests/base.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { defineCms, normalizeSession } from '@tanstack/cms-core' +import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs' import { accessContext, approve, @@ -86,7 +87,10 @@ beforeEach(() => { blockTypes: [], seed, ops: baseOps, - interfaces: { collection: 'interfaces' }, + interfaces: { + collection: 'interfaces', + runtime: quickjsInterfaceRuntime(), + }, dataDir: dir, auth: { getUser: ({ request }) => dbUser(request), diff --git a/app/base/tests/chat.test.ts b/app/base/tests/chat.test.ts index af753384..3f77174c 100644 --- a/app/base/tests/chat.test.ts +++ b/app/base/tests/chat.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { chat } from '@tanstack/ai' import { defineCms } from '@tanstack/cms-core' +import { aiRuntime } from '@tanstack/cms-core/ai' import { closeStore, listPending, @@ -66,6 +67,7 @@ beforeEach(() => { }), }, ai: { + runtime: aiRuntime(), textAdapter: () => ({ name: 'fake' }), agentInstructions: instructions, }, diff --git a/app/base/tests/schema-registry.test.ts b/app/base/tests/schema-registry.test.ts index 9f29ac16..667668ed 100644 --- a/app/base/tests/schema-registry.test.ts +++ b/app/base/tests/schema-registry.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, afterEach, describe, it, expect } from 'vitest' import { defineCms, getCmsConfig, normalizeSession } from '@tanstack/cms-core' +import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs' import type { CmsOpContext, Doc } from '@tanstack/cms-core' import { accessContext, @@ -87,7 +88,10 @@ beforeEach(() => { blockTypes: [], seed, ops: baseOps, - interfaces: { collection: 'interfaces' }, + interfaces: { + collection: 'interfaces', + runtime: quickjsInterfaceRuntime(), + }, dataDir: dir, events: { dispatch: 'manual' }, auth: { diff --git a/app/base/tests/worker.test.ts b/app/base/tests/worker.test.ts index 3dc9c372..ba565405 100644 --- a/app/base/tests/worker.test.ts +++ b/app/base/tests/worker.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -52,7 +53,11 @@ describe('Base background interface worker', () => { seed, blockTypes: [], dataDir: dir, - interfaces: { collection: 'interfaces', scheduleSession }, + interfaces: { + collection: 'interfaces', + scheduleSession, + runtime: quickjsInterfaceRuntime(), + }, events: { dispatch: 'manual' }, eventHandlers: interfaceScheduleHandlers( 'interfaces', diff --git a/app/base/vitest.config.ts b/app/base/vitest.config.ts index ace66a6b..da811eab 100644 --- a/app/base/vitest.config.ts +++ b/app/base/vitest.config.ts @@ -3,6 +3,11 @@ export default defineConfig({ test: { name: 'base', environment: 'node', + // Core ships no storage default; restore the embedded PGlite engine for + // tests that don't inject their own `storage`. Base uses the on-disk + // variant: the recover-owner test spawns a subprocess that reads the + // database file, so it needs real persistence, not the shared in-memory VM. + setupFiles: ['@tanstack/cms-store-postgres/testing-disk'], include: ['tests/**/*.test.ts'], fileParallelism: false, // Tests drive the embedded PGlite engine (WASM init) and multi-step diff --git a/app/docs-preview/package.json b/app/docs-preview/package.json index 12487278..a97ff189 100644 --- a/app/docs-preview/package.json +++ b/app/docs-preview/package.json @@ -19,6 +19,7 @@ "@tanstack/ai-anthropic": "^0.23.0", "@tanstack/cms-api": "workspace:*", "@tanstack/cms-core": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@tanstack/cms-ui-react": "workspace:*", "@tanstack/react-router": "^1.170.46", "@tanstack/react-start": "^1.169.4", diff --git a/app/docs-preview/src/cms.config.ts b/app/docs-preview/src/cms.config.ts index 7748f5e5..048dee96 100644 --- a/app/docs-preview/src/cms.config.ts +++ b/app/docs-preview/src/cms.config.ts @@ -8,6 +8,7 @@ * tree never collides with the first. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createServerOnlyFn } from '@tanstack/react-start' import { definition } from './cms.definition' import { askAgentConfig } from './agents/ask' @@ -57,6 +58,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, ...(initialDataDir ? { dataDir: initialDataDir } : {}), blockTypes, ai, diff --git a/app/prm/src/agents/ask.ts b/app/prm/src/agents/ask.ts index dc1644b0..fb4efd80 100644 --- a/app/prm/src/agents/ask.ts +++ b/app/prm/src/agents/ask.ts @@ -27,7 +27,7 @@ Non-negotiable rules (§6.1): 4. CROSS-PERSON BRIEFINGS: When asked for a briefing (e.g. "Brief me on everyone I'm seeing at the Summit" or "Who do I know working on durable state for agents?"), group results in priority tier order (\`tier-1\`, \`tier-2\`, \`tier-3\`, \`unranked\`), include each person's headline, talk title + hook, and whether we have already interacted with them.` export async function createAskExtraTools() { - const { loadTanstackAi } = await import('@tanstack/cms-core/server') + const { loadTanstackAi } = await import('@tanstack/cms-api') const { toolDefinition } = await loadTanstackAi() const offerNextStep = toolDefinition({ name: 'offer_next_step', diff --git a/app/prm/src/agents/enrich.ts b/app/prm/src/agents/enrich.ts index 90d2be46..6e13425a 100644 --- a/app/prm/src/agents/enrich.ts +++ b/app/prm/src/agents/enrich.ts @@ -49,7 +49,7 @@ Rules (§2, §4, §5, §8): export async function createEnrichmentWebTools( depth: EnrichmentDepth = 'deep', ) { - const { loadTanstackAi } = await import('@tanstack/cms-core/server') + const { loadTanstackAi } = await import('@tanstack/cms-api') const { toolDefinition } = await loadTanstackAi() const budget = createBudgetTracker(depth) const provider = getSearchProvider() diff --git a/app/prm/src/cms.config.ts b/app/prm/src/cms.config.ts index 93e77003..585ea5f8 100644 --- a/app/prm/src/cms.config.ts +++ b/app/prm/src/cms.config.ts @@ -15,6 +15,8 @@ */ import { createServerOnlyFn } from '@tanstack/react-start' import { defineCms, PERMISSIONS } from '@tanstack/cms-core' +import { aiRuntime } from '@tanstack/cms-core/ai' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { seed } from './seed' import { importPeopleOp } from './ops/import-people' import { enrichAgentConfig, ENRICHMENT_SKILL_PROMPT } from './agents/enrich' @@ -39,6 +41,7 @@ if (typeof process !== 'undefined' && process.versions?.node) { } export const cms = defineCms(definition, { + storage: createPgliteStorage, ...(initialDataDir ? { dataDir: initialDataDir } : {}), blockTypes: [], ops: [importPeopleOp], @@ -109,6 +112,7 @@ export const cms = defineCms(definition, { ], }, ai: { + runtime: aiRuntime(), textAdapter: async () => { if (!process.env.ANTHROPIC_API_KEY) return null const { anthropicText } = await import('@tanstack/ai-anthropic') diff --git a/app/prm/tests/crm.test.ts b/app/prm/tests/crm.test.ts index 592d04f3..6c213b9e 100644 --- a/app/prm/tests/crm.test.ts +++ b/app/prm/tests/crm.test.ts @@ -29,6 +29,7 @@ import { PERMISSIONS, } from '@tanstack/cms-core' import type { AnyDocumentStateStrategy, Field } from '@tanstack/cms-core' +import { aiRuntime } from '@tanstack/cms-core/ai' import { accessContext, actOnDocument, @@ -44,6 +45,7 @@ import { } from '@tanstack/cms-core/server' import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createCmsApiHandler, invokeAnyOp } from '@tanstack/cms-api' +import { cmsMcp } from '@tanstack/cms-api/mcp' import { createCmsSearch } from '@tanstack/search-cms' import { createSearchStore } from '@tanstack/search-headless' import { crmCollections, person } from '../src/collections' @@ -105,6 +107,7 @@ function setupCrmTest(extra?: { ], }, ai: { + runtime: aiRuntime(), ...(extra?.textAdapter ? { textAdapter: extra.textAdapter } : {}), agents: { enrich: enrichAgentConfig, @@ -613,7 +616,7 @@ describe('CRM acceptance criteria (§11)', () => { it('§11.12 & §13: /api/mcp refuses unauthenticated calls, scopes read-only key to read tools, and attributes writes to mcp:', async () => { setupCrmTest() await seedContent() - const handler = createCmsApiHandler() + const handler = createCmsApiHandler({ mcp: cmsMcp }) // 1. Unauthenticated call -> 401 const unauth = await handler( diff --git a/examples/astro-starlight-after/src/cms.config.ts b/examples/astro-starlight-after/src/cms.config.ts index ee6984c5..3b6fea19 100644 --- a/examples/astro-starlight-after/src/cms.config.ts +++ b/examples/astro-starlight-after/src/cms.config.ts @@ -4,6 +4,7 @@ * is in ./cms.definition.ts. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { seedDocuments } from './seed-data' import { definition } from './cms.definition' @@ -37,6 +38,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, ai, seed: { documents: seedDocuments }, diff --git a/examples/blog-voting/src/cms.config.ts b/examples/blog-voting/src/cms.config.ts index 96bf2fb6..c7749320 100644 --- a/examples/blog-voting/src/cms.config.ts +++ b/examples/blog-voting/src/cms.config.ts @@ -8,6 +8,7 @@ * and block palette. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -148,6 +149,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, ai, seed, diff --git a/examples/blog/src/cms.config.ts b/examples/blog/src/cms.config.ts index f7731bf1..3b2ec644 100644 --- a/examples/blog/src/cms.config.ts +++ b/examples/blog/src/cms.config.ts @@ -8,6 +8,7 @@ * and block palette. */ import { defineBlock, defineCms, livePublishing } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -171,6 +172,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, ai, seed, diff --git a/examples/db-federated/package.json b/examples/db-federated/package.json index 06236481..f1c0998d 100644 --- a/examples/db-federated/package.json +++ b/examples/db-federated/package.json @@ -15,6 +15,7 @@ "@tanstack/cms-api": "workspace:*", "@tanstack/cms-client": "workspace:*", "@tanstack/cms-core": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@tanstack/cms-ui-react": "workspace:*", "@tanstack/db": "0.15.2", "@tanstack/query-core": "^5.105.0", diff --git a/examples/db-federated/src/cms.config.ts b/examples/db-federated/src/cms.config.ts index a95bca7c..0795b914 100644 --- a/examples/db-federated/src/cms.config.ts +++ b/examples/db-federated/src/cms.config.ts @@ -7,6 +7,7 @@ * keyed by (locale, region). */ import { defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -80,6 +81,7 @@ const seed: SeedStore = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes: [], seed, auth: createMockAuth(), diff --git a/examples/db-sqlite/package.json b/examples/db-sqlite/package.json index 77726b3c..deaca523 100644 --- a/examples/db-sqlite/package.json +++ b/examples/db-sqlite/package.json @@ -15,6 +15,7 @@ "@tanstack/cms-api": "workspace:*", "@tanstack/cms-client": "workspace:*", "@tanstack/cms-core": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@tanstack/cms-ui-react": "workspace:*", "@tanstack/db": "0.15.2", "@tanstack/query-core": "^5.105.0", diff --git a/examples/db-sqlite/src/cms.config.ts b/examples/db-sqlite/src/cms.config.ts index d2cb8bc2..2c0687cc 100644 --- a/examples/db-sqlite/src/cms.config.ts +++ b/examples/db-sqlite/src/cms.config.ts @@ -5,6 +5,7 @@ * admin UI. Same collection, two editors. */ import { defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -35,6 +36,7 @@ const seed: SeedStore = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes: [], seed, auth: createMockAuth(), diff --git a/examples/emdash-after/src/cms.config.ts b/examples/emdash-after/src/cms.config.ts index 04065b6e..5afdd91c 100644 --- a/examples/emdash-after/src/cms.config.ts +++ b/examples/emdash-after/src/cms.config.ts @@ -4,6 +4,7 @@ * ./cms.definition.ts. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { seedDocuments } from './seed-data' import { definition } from './cms.definition' @@ -37,6 +38,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, ai, seed: { documents: seedDocuments }, diff --git a/examples/payload-after/src/cms.config.ts b/examples/payload-after/src/cms.config.ts index 497f61ce..f2bc4fe7 100644 --- a/examples/payload-after/src/cms.config.ts +++ b/examples/payload-after/src/cms.config.ts @@ -4,6 +4,7 @@ * ./cms.definition.ts. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { seedDocuments } from './seed-data' import { definition } from './cms.definition' @@ -70,6 +71,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, ai, seed: { documents: seedDocuments }, diff --git a/examples/picks/src/cms.config.ts b/examples/picks/src/cms.config.ts index bf233bfd..493057e9 100644 --- a/examples/picks/src/cms.config.ts +++ b/examples/picks/src/cms.config.ts @@ -1,8 +1,10 @@ import { defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { createMockAuth } from '@tanstack/cms-ui-react' import { pickDocuments } from './seed' import { definition } from './cms.definition' export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes: [], seed: { documents: { picks: pickDocuments } }, auth: createMockAuth({ defaultRole: 'unauthenticated' }), diff --git a/examples/wordpress-after/src/cms.config.ts b/examples/wordpress-after/src/cms.config.ts index 689eeb47..26b59d67 100644 --- a/examples/wordpress-after/src/cms.config.ts +++ b/examples/wordpress-after/src/cms.config.ts @@ -4,6 +4,7 @@ * ./cms.definition.ts. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import { seedDocuments } from './seed-data' import { definition } from './cms.definition' @@ -36,6 +37,7 @@ const ai = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, ai, seed: { documents: seedDocuments }, diff --git a/examples/wp-vs-tanstack/package.json b/examples/wp-vs-tanstack/package.json index 3f366c72..6caf066c 100644 --- a/examples/wp-vs-tanstack/package.json +++ b/examples/wp-vs-tanstack/package.json @@ -15,6 +15,7 @@ "@tanstack/cms-api": "workspace:*", "@tanstack/cms-compat-wp": "workspace:*", "@tanstack/cms-core": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@tanstack/cms-ui-react": "workspace:*", "@tanstack/react-router": "^1.170.46", "@tanstack/react-start": "^1.169.4", diff --git a/examples/wp-vs-tanstack/src/cms.config.ts b/examples/wp-vs-tanstack/src/cms.config.ts index 6f925919..4a1b1327 100644 --- a/examples/wp-vs-tanstack/src/cms.config.ts +++ b/examples/wp-vs-tanstack/src/cms.config.ts @@ -5,6 +5,7 @@ * ./cms.renderers.tsx. */ import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' import type { CmsConfig } from '@tanstack/cms-core' import { createCompatWpPlugin } from '@tanstack/cms-compat-wp' import { definition, wpDefinition } from './cms.definition' @@ -315,6 +316,7 @@ const auth: NonNullable = { } export const cms = defineCms(definition, { + storage: createPgliteStorage, blockTypes, // WordPress-compatibility plugin: the server-side preview op behind the // "WP Import" wizard (its admin route is registered via the definition). Pass diff --git a/kody/blog/AGENTS.md b/kody/blog/AGENTS.md new file mode 100644 index 00000000..8be450b9 --- /dev/null +++ b/kody/blog/AGENTS.md @@ -0,0 +1,36 @@ +# AGENTS — TanStack CMS blog on Kody + +## Runtime contract + +- `kody.app.entry` = `./src/entry.ts`, default-exported `{ fetch }`, receives the + mount-stripped Request. Kody bundles source with esbuild; no Vite/Nitro. +- No TCP / no `node:*` / no filesystem in the isolate. Postgres is reached with + `@neondatabase/serverless` (`Pool` over WebSocket) — set + `neonConfig.webSocketConstructor = WebSocket` at module scope. +- Secrets: `packageSecrets.get('DATABASE_URL')` (real value on hosted runs; + placeholder under `kody dev`). Build the pool lazily on first request. + +## Store wiring (stage 2+) + +- Pass a `pool` (Neon) to `createPostgresStorage({ pool })` — NOT a + `connectionString`, which makes store-postgres build stock `pg` (won't load on + workerd). Neon's `Pool` satisfies store-postgres `PgPoolLike` structurally + (`connect()` → client with `query`/`release`, plus `on`/`end`). +- `@tanstack/*` deps are pinned to pkg.pr.new commit URLs (not on npm yet). + +## React SSR + +- Import `renderToReadableStream` from `react-dom/server.edge` (bare + `react-dom/server` resolves to the Node build and crashes on load). +- Two graphs: server entry may import `kody:runtime`; the browser client bundle + must not. Hydrate `#root` with the same data the server embedded. + +## Images + +- No native/WASM. Use Jimp (pure JS) behind the CMS `media.imageTransformer` + seam; lean on the transform cache and cap input dimensions. + +## Smoke + +- Stage 1: `appFetch` `GET /` → `{ ok: true, version: "PostgreSQL …" }`. + `GET /healthz` → `{ ok: true }`. diff --git a/kody/blog/README.md b/kody/blog/README.md new file mode 100644 index 00000000..676e690b --- /dev/null +++ b/kody/blog/README.md @@ -0,0 +1,32 @@ +# TanStack CMS blog on Kody + +A TanStack CMS blog recomposed as a hosted Kody app: a fetch-handler entry that +reuses the framework-agnostic CMS pieces (content model, store, renderers) on +Kody's Worker runtime, backed by Neon serverless Postgres. It is **not** a port +of the TanStack Start blog — Start's Vite/Nitro build does not fit Kody's +source-only, esbuild, two-graph app contract. + +## Prerequisites + +- A Neon (or other serverless/HTTP-reachable) Postgres. Save its pooled + connection string as the package secret `DATABASE_URL`. +- No local build step: Kody installs deps from npm and bundles at publish. + +## Stages + +1. **DB probe (current)** — `GET /` reads the `DATABASE_URL` secret, opens a Neon + Pool over WebSocket, and returns `select version()`. Proves secret-read + + Neon-on-workerd before the CMS is wired in. `/healthz` → `{ ok: true }`. +2. **Public site** — first-boot migrate + seed, then React-SSR published pages + and posts via `@tanstack/cms-core` + `@tanstack/cms-ui-react/site`. +3. **Admin + API** — mount `createCmsApiHandler` and real auth. + +## Done-when + +Stage 1: `GET /` returns `{ ok: true, version: "PostgreSQL …" }` from the hosted +URL. Then advance to stage 2. + +## Intent + +Prove and then ship a TanStack CMS blog deployable to a personal Kody account +with a live URL and zero infra, non-WASM image handling (Jimp), and no AI. diff --git a/kody/blog/package.json b/kody/blog/package.json new file mode 100644 index 00000000..1d94941a --- /dev/null +++ b/kody/blog/package.json @@ -0,0 +1,18 @@ +{ + "name": "@jherr/blog", + "type": "module", + "description": "TanStack CMS blog as a hosted Kody app (Neon serverless store, pre-bundled CMS).", + "exports": { + ".": "./dist/entry.mjs" + }, + "dependencies": { + "@neondatabase/serverless": "^0.10.4" + }, + "kody": { + "description": "A TanStack CMS blog on Kody \u2014 Neon Postgres, server-rendered.", + "category": "apps", + "app": { + "entry": "./dist/entry.mjs" + } + } +} diff --git a/kody/blog/src/db.ts b/kody/blog/src/db.ts new file mode 100644 index 00000000..ca86428f --- /dev/null +++ b/kody/blog/src/db.ts @@ -0,0 +1,57 @@ +import { neon } from '@neondatabase/serverless' +import { packageStorage } from 'kody:runtime' +import type { ReadRecord, ReadStore } from '@tanstack/cms-core/read' + +// Lightweight Neon integration: the HTTP (`neon()`) driver is a stateless +// fetch-per-query — no WebSocket, no pool, nothing to instantiate at boot. + +const DB_KEY = 'DATABASE_URL' + +export async function getConnectionString(): Promise { + const value = await packageStorage().get(DB_KEY) + return typeof value === 'string' && value.length > 0 ? value : undefined +} + +export async function setConnectionString(value: string): Promise { + await packageStorage().set(DB_KEY, value) +} + +function toRecord(row: { id: unknown; doc: unknown }): ReadRecord { + const doc = + row.doc && typeof row.doc === 'object' + ? (row.doc as Record) + : typeof row.doc === 'string' + ? (JSON.parse(row.doc) as Record) + : {} + return { id: String(row.id), doc } +} + +/** + * A ~15-line `ReadStore` (from `@tanstack/cms-core/read`) over the CMS's + * `cms_documents` table via the Neon HTTP driver. This is the whole DB layer a + * public site needs — no engine, no pool. + */ +export function makeReadStore(connectionString: string): ReadStore { + const sql = neon(connectionString) + return { + async getDocument(collection, id) { + const rows = (await sql` + select id, doc from cms_documents + where collection = ${collection} and id = ${id} + limit 1 + `) as Array<{ id: unknown; doc: unknown }> + return rows.length ? toRecord(rows[0]) : null + }, + async queryDocuments({ collections, limit = 100 }) { + const collection = collections[0] + const rows = (await sql` + select id, doc from cms_documents + where collection = ${collection} and published = true + order by (doc->>'publishedDate') desc nulls last + limit ${limit} + `) as Array<{ id: unknown; doc: unknown }> + const items = rows.map(toRecord) + return { items, total: items.length } + }, + } +} diff --git a/kody/blog/src/entry.ts b/kody/blog/src/entry.ts new file mode 100644 index 00000000..d917dd35 --- /dev/null +++ b/kody/blog/src/entry.ts @@ -0,0 +1,81 @@ +import { getDocument, listDocuments } from '@tanstack/cms-core/read' +import { kody, packageContext } from 'kody:runtime' +import { getConnectionString, makeReadStore, setConnectionString } from './db' +import { renderHome, renderNotFound, renderPost } from './render' + +// Public blog read worker, built on @tanstack/cms-core/read: a tiny ReadStore +// over Neon (HTTP) + the shared renderers. No CMS engine, no WebSocket pool. + +const base = String(packageContext?.appBasePath ?? '').replace(/\/+$/, '') + +async function isOwner(): Promise { + try { + const me = await kody.metaGetCurrentUser({}) + return me?.role != null + } catch { + return false + } +} + +function page(body: string, status = 200): Response { + return new Response(body, { + status, + headers: { 'content-type': 'text/html; charset=utf-8' }, + }) +} + +export default { + async fetch(request: Request): Promise { + const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/' + + if (path.endsWith('/healthz')) return Response.json({ ok: true }) + + if (request.method === 'POST' && path.endsWith('/_setup')) { + if (!(await isOwner())) return new Response('owner only', { status: 403 }) + const body = (await request.text()).trim() + if (!/^postgres(ql)?:\/\//.test(body)) { + return new Response('expected a postgres:// connection string', { + status: 400, + }) + } + await setConnectionString(body) + return Response.json({ ok: true, saved: true }) + } + + const conn = await getConnectionString() + if (!conn) { + return new Response( + 'Database not configured. Owner: POST the Neon connection string to /_setup.', + { status: 503, headers: { 'content-type': 'text/plain' } }, + ) + } + + try { + const store = makeReadStore(conn) + + const postMatch = /\/post\/([^/]+)$/.exec(path) + if (postMatch) { + const id = decodeURIComponent(postMatch[1]) + const doc = await getDocument(store, 'post', id, { + publishedOnly: true, + }) + return doc + ? page(renderPost(base, doc)) + : page(renderNotFound(base), 404) + } + + if (path === '/' || path === '') { + const home = await getDocument(store, 'page', 'home') + const posts = await listDocuments(store, 'post', { limit: 50 }) + return page(renderHome(base, home, posts)) + } + + return page(renderNotFound(base), 404) + } catch (err) { + return new Response( + `render failed: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, + { status: 500, headers: { 'content-type': 'text/plain' } }, + ) + } + }, +} diff --git a/kody/blog/src/kody-runtime.d.ts b/kody/blog/src/kody-runtime.d.ts new file mode 100644 index 00000000..44938930 --- /dev/null +++ b/kody/blog/src/kody-runtime.d.ts @@ -0,0 +1,31 @@ +// Ambient shim for local `tsc`. At publish Kody rewrites `kody:` imports to real +// runtime proxies and supplies the full generated declaration; this covers only +// what the blog app uses. +declare module 'kody:runtime' { + export const packageContext: + | { + appBasePath?: string + assetBasePath?: string + hostedUrl?: string + clientModuleUrl?: string | null + } + | undefined + + // Durable per-package KV the app reads/writes in plaintext (unlike secrets, + // which the gateway only injects into outbound fetch and never hand to code). + export function packageStorage(): { + get: (key: string) => Promise + set: (key: string, value: unknown) => Promise + delete: (key: string) => Promise + } + + export const kody: { + // Verified identity of the current visitor; `role` is their role in the + // owning org (null for non-members). Throws for anonymous visitors. + metaGetCurrentUser: (args: Record) => Promise<{ + user_id: string + username: string + role: string | null + }> + } +} diff --git a/kody/blog/src/render.ts b/kody/blog/src/render.ts new file mode 100644 index 00000000..2d70ae22 --- /dev/null +++ b/kody/blog/src/render.ts @@ -0,0 +1,83 @@ +import { + escapeHtml, + renderBlocks, + renderMarkdown, + type Doc, + type ReadRecord, +} from '@tanstack/cms-core/read' + +// The app owns layout + styling + page composition; block/markdown rendering +// comes from @tanstack/cms-core/read (the shared, tree-shakeable renderer). + +const str = (v: unknown): string => (typeof v === 'string' ? v : '') + +function layout(base: string, title: string, body: string): string { + return `${escapeHtml( + title, + )}
jherr's blogTanStack CMS · on Kody · Neon
${body}
Served from Postgres by a Kody Worker — rendered by @tanstack/cms-core/read.
` +} + +export function renderHome( + base: string, + page: Doc | null, + posts: Array, +): string { + const blocks = renderBlocks(page?.blocks) + const list = `

Posts

    ${posts + .map( + ({ id, doc }) => + `
  • ${escapeHtml(doc.title)}${ + str(doc.excerpt) + ? ` — ${escapeHtml(doc.excerpt)}` + : '' + }
  • `, + ) + .join('')}
` + return layout(base, str(page?.title) || 'Blog', blocks + list) +} + +export function renderPost(base: string, doc: Doc): string { + const meta = [ + str(doc.author) ? `by ${escapeHtml(doc.author)}` : '', + escapeHtml(doc.publishedDate), + ] + .filter(Boolean) + .join(' · ') + const body = `

${escapeHtml(doc.title)}

${ + meta ? `

${meta}

` : '' + }${renderMarkdown(str(doc.body))}

← all posts

` + return layout(base, str(doc.title) || 'Post', body) +} + +export function renderNotFound(base: string): string { + return layout( + base, + 'Not found', + `

Not found

← home

`, + ) +} + +const CSS = ` +:root{color-scheme:light dark;--fg:#1a1a1a;--bg:#fff;--muted:#666;--accent:#0b7285;--line:#e5e5e5} +@media(prefers-color-scheme:dark){:root{--fg:#eee;--bg:#14171a;--muted:#9aa;--accent:#3bc9db;--line:#2a2f33}} +*{box-sizing:border-box} +body{margin:0;font:16px/1.65 system-ui,sans-serif;color:var(--fg);background:var(--bg)} +header.site{display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap;max-width:46rem;margin:0 auto;padding:1.25rem;border-bottom:1px solid var(--line)} +.brand{font-weight:700;font-size:1.15rem;color:var(--fg);text-decoration:none} +.tag{color:var(--muted);font-size:.8rem} +main{max-width:46rem;margin:0 auto;padding:1.5rem 1.25rem 3rem} +h1{line-height:1.2} +.cms-hero h1{font-size:2.1rem;margin:.2em 0} +.cms-lede{font-size:1.2rem;color:var(--muted)} +a{color:var(--accent)} +blockquote{border-left:3px solid var(--accent);margin:1.5rem 0;padding:.2rem 0 .2rem 1rem;color:var(--muted);font-style:italic} +blockquote cite{display:block;font-style:normal;font-size:.9rem;margin-top:.4rem} +pre{background:rgba(127,127,127,.12);padding:1rem;border-radius:8px;overflow:auto} +.cms-callout{background:rgba(127,127,127,.1);border-radius:8px;padding:.8rem 1rem;margin:1.2rem 0} +.cms-cta a{display:inline-block;margin-top:.5rem} +figure{margin:1.2rem 0}figure img{max-width:100%;border-radius:8px} +.posts{margin-top:2.5rem;border-top:1px solid var(--line);padding-top:1rem} +.posts ul{list-style:none;padding:0}.posts li{padding:.5rem 0;border-bottom:1px solid var(--line)} +.excerpt{color:var(--muted)}.meta{color:var(--muted);font-size:.9rem} +footer{max-width:46rem;margin:0 auto;padding:1.5rem 1.25rem;color:var(--muted);font-size:.85rem;border-top:1px solid var(--line)} +` diff --git a/kody/blog/tsconfig.json b/kody/blog/tsconfig.json new file mode 100644 index 00000000..c0635132 --- /dev/null +++ b/kody/blog/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "module": "esnext", + "moduleResolution": "bundler", + "target": "es2022", + "lib": ["es2023", "dom", "dom.iterable"], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "verbatimModuleSyntax": true + }, + "include": ["src"] +} diff --git a/packages/api/package.json b/packages/api/package.json index a5827da2..f1a50c50 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -23,6 +23,7 @@ ".": "./src/index.ts", "./start": "./src/start.ts", "./http": "./src/http.ts", + "./mcp": "./src/mcp.ts", "./markdown": "./src/markdown.ts", "./package.json": "./package.json" }, @@ -48,6 +49,10 @@ "types": "./dist/http.d.ts", "import": "./dist/http.js" }, + "./mcp": { + "types": "./dist/mcp.d.ts", + "import": "./dist/mcp.js" + }, "./markdown": { "types": "./dist/markdown.d.ts", "import": "./dist/markdown.js" diff --git a/packages/api/src/ai.ts b/packages/api/src/ai.ts index 267d70d9..d66e8644 100644 --- a/packages/api/src/ai.ts +++ b/packages/api/src/ai.ts @@ -6,8 +6,30 @@ * Server-only. */ import { cmsLogger, getCmsConfig } from '@tanstack/cms-core' -import { CmsError } from '@tanstack/cms-core/server' +import { + CmsError, + isMissingModule, + missingPeer, +} from '@tanstack/cms-core/server' import type { AnyImageAdapter, AnyTextAdapter } from '@tanstack/ai' +import type * as TanstackAi from '@tanstack/ai' + +/** + * Load `@tanstack/ai` (chat, image generation, tool helpers), or throw + * `NOT_CONFIGURED` naming the package to install. Lives here, not in core, so + * the engine never reaches for `@tanstack/ai`; `@tanstack/cms-api` is the AI + * integration surface. + */ +export async function loadTanstackAi(): Promise { + try { + return await import('@tanstack/ai') + } catch (e) { + if (isMissingModule(e, '@tanstack/ai')) { + throw missingPeer('@tanstack/ai', 'AI features') + } + throw e + } +} export interface CmsAiCapabilityFlags { text: boolean diff --git a/packages/api/src/http.ts b/packages/api/src/http.ts index 822b2c25..96caaf6d 100644 --- a/packages/api/src/http.ts +++ b/packages/api/src/http.ts @@ -81,7 +81,7 @@ import type { ImageTransform, CmsEvent, } from '@tanstack/cms-core/server' -import { cmsMcp } from './mcp' +import type { CmsMcpHandler } from './mcp' import { agentActorName, allOps, findOp, invokeAnyOp } from './ops' import { CMS_API_BASE, CMS_API_VERSION, buildOpenApiDocument } from './openapi' import type { ResolvedOp } from './ops' @@ -276,8 +276,16 @@ async function dispatchCmsApi(request: Request): Promise { } } -/** MCP endpoint: `GET|POST|DELETE /api/mcp` (Streamable HTTP). */ -export async function handleMcpApi(request: Request): Promise { +/** + * MCP endpoint: `GET|POST|DELETE /api/mcp` (Streamable HTTP). MCP is opt-in — + * pass the server from `@tanstack/cms-api/mcp`: + * `handleMcpApi(request, cmsMcp)`. Keeping it a parameter means an API that + * doesn't serve MCP never imports `@tanstack/ai-mcp` into its bundle. + */ +export async function handleMcpApi( + request: Request, + mcp: CmsMcpHandler, +): Promise { let access: Awaited> try { assertTrustedOrigin(request) @@ -316,7 +324,7 @@ export async function handleMcpApi(request: Request): Promise { mode: 'edit', agent: agentActorName('mcp', session), }) - return await cmsMcp.fetch(boundedRequest, agent) + return await mcp.fetch(boundedRequest, agent) } catch (e) { return opError(e, request) } @@ -513,6 +521,12 @@ export interface CmsApiHandlerOptions { * instances in the same server process. */ config?: CmsConfig | ResolvedCmsConfig + /** + * Opt in to the Streamable HTTP MCP server at `/api/mcp` by passing `cmsMcp` + * from `@tanstack/cms-api/mcp`. Omit it and `/api/mcp` answers + * `NOT_CONFIGURED` — and `@tanstack/ai-mcp` never enters the bundle. + */ + mcp?: CmsMcpHandler } const openStreams = new WeakMap< @@ -801,7 +815,14 @@ export function createCmsApiHandler( return handleCmsApi(request) } if (path === '/api/mcp') { - return handleMcpApi(request) + if (!options.mcp) { + return errorJson( + 'NOT_CONFIGURED', + "MCP is not enabled. Mount it: import { cmsMcp } from '@tanstack/cms-api/mcp' " + + 'and pass `createCmsApiHandler({ mcp: cmsMcp })`.', + ) + } + return handleMcpApi(request, options.mcp) } if (path === '/api/media' && request.method === 'POST') { return handleMediaUploadApi(request) diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 592a9453..6f83a909 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -20,7 +20,12 @@ export { resolveAuthSession, runAgent, } from './ops' -export { aiCapabilities, resolveImageAdapter, resolveTextAdapter } from './ai' +export { + aiCapabilities, + loadTanstackAi, + resolveImageAdapter, + resolveTextAdapter, +} from './ai' export type { CmsAiCapabilityFlags } from './ai' export type { ChangeSetReview, @@ -33,7 +38,10 @@ export type { OpOutput, ResolvedOp, } from './ops' -export { cmsMcp } from './mcp' +// `cmsMcp` (and the MCP server, which pulls `@tanstack/ai-mcp`) lives at the +// `@tanstack/cms-api/mcp` subpath so the main entry stays MCP-free. Mount it via +// `createCmsApiHandler({ mcp: cmsMcp })` or `handleMcpApi(request, cmsMcp)`. +export type { CmsMcpHandler } from './mcp' export type { MediaItem, MediaKind } from '@tanstack/cms-core/server' export { createCmsApiHandler, diff --git a/packages/api/src/interface-ops.ts b/packages/api/src/interface-ops.ts index 216c2729..b36982b3 100644 --- a/packages/api/src/interface-ops.ts +++ b/packages/api/src/interface-ops.ts @@ -23,10 +23,9 @@ import { getInterfaceScheduleStatus, setInterfaceSchedulePaused, refreshInterfaceSnapshot, - loadTanstackAi, interfaceCollectionName, } from '@tanstack/cms-core/server' -import { requireTextAdapter } from './ai' +import { loadTanstackAi, requireTextAdapter } from './ai' const ref = z.object({ id: z.string().regex(/^[a-z][a-z0-9-]{0,99}$/) }) const readInput = ref.extend({ @@ -213,7 +212,11 @@ export const interfaceOps = { return { valid: true, components: preview.result.nodes.length } }) const codeMode = createCodeMode({ - driver: await interfaceDriver(), + // Core types the driver structurally (it never imports the isolate + // package); narrow to code-mode's own driver type at the boundary. + driver: (await interfaceDriver()) as Parameters< + typeof createCodeMode + >[0]['driver'], tools: [queryTool, setTool], timeout: 15000, memoryLimit: 64, diff --git a/packages/api/src/mcp.ts b/packages/api/src/mcp.ts index ec32c614..8a796db4 100644 --- a/packages/api/src/mcp.ts +++ b/packages/api/src/mcp.ts @@ -78,7 +78,12 @@ function serverFor( return server } -export const cmsMcp = { +/** Serves Streamable HTTP MCP requests; pass to the CMS API handler's `mcp`. */ +export interface CmsMcpHandler { + fetch: (request: Request, access: AccessContext) => Promise +} + +export const cmsMcp: CmsMcpHandler = { /** * Serve one MCP request. Tools are listed for, and every call reads and * writes as, `access` (e.g. `accessContext({ session, agent: 'mcp', diff --git a/packages/api/src/media-ops.ts b/packages/api/src/media-ops.ts index ff92eb37..43fe3bea 100644 --- a/packages/api/src/media-ops.ts +++ b/packages/api/src/media-ops.ts @@ -19,7 +19,6 @@ import { getAs, getMediaItem, listMediaItems, - loadTanstackAi, rateLimit, readMedia, readDocumentWithPendingAs, @@ -29,7 +28,7 @@ import { systemContext, updateMediaItem, } from '@tanstack/cms-core/server' -import { requireImageAdapter } from './ai' +import { loadTanstackAi, requireImageAdapter } from './ai' import { maybeMediaItemOutput, mediaItemOutput, diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index fafc38d2..d24c2bec 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -50,7 +50,6 @@ import { assertTrustedOrigin, runOp, cmsTools, - loadTanstackAi, resolveRedirect, discardDraft, deleteDocument, @@ -105,7 +104,7 @@ import { pendingReleaseChanges, rollbackRelease, } from '@tanstack/cms-core/server' -import { aiCapabilities, requireTextAdapter } from './ai' +import { aiCapabilities, loadTanstackAi, requireTextAdapter } from './ai' import { mediaOps } from './media-ops' import { interfaceOps } from './interface-ops' import { diff --git a/packages/api/tests/access.test.ts b/packages/api/tests/access.test.ts index 2c4133a4..5b48edf8 100644 --- a/packages/api/tests/access.test.ts +++ b/packages/api/tests/access.test.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs' +import { cmsMcp } from '../src/mcp' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { PERMISSIONS } from '@tanstack/cms-core' @@ -10,7 +11,7 @@ import type { CmsConfig } from '@tanstack/cms-core' afterEach(cleanup) -const handler = createCmsApiHandler() +const handler = createCmsApiHandler({ mcp: cmsMcp }) async function call( name: string, diff --git a/packages/api/tests/contract/s3-s5-contract.test.ts b/packages/api/tests/contract/s3-s5-contract.test.ts index 0cc255b9..fdcec3ac 100644 --- a/packages/api/tests/contract/s3-s5-contract.test.ts +++ b/packages/api/tests/contract/s3-s5-contract.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it } from 'vitest' +import { cmsMcp } from '../../src/mcp' import { CMS_EXPORT_FORMAT, CMS_EXPORT_VERSION, @@ -15,7 +16,7 @@ import { cleanup, cookieAuth, req, setupCms } from '../helpers' afterEach(cleanup) -const handler = createCmsApiHandler() +const handler = createCmsApiHandler({ mcp: cmsMcp }) function setupContractCms() { return setupCms({ diff --git a/packages/api/tests/hardening.test.ts b/packages/api/tests/hardening.test.ts index a5b632d4..598681e1 100644 --- a/packages/api/tests/hardening.test.ts +++ b/packages/api/tests/hardening.test.ts @@ -1,10 +1,11 @@ import { afterEach, describe, expect, it } from 'vitest' +import { cmsMcp } from '../src/mcp' import { createCmsApiHandler } from '../src/http' import { PNG, cleanup, req, setupCms } from './helpers' afterEach(cleanup) -const handler = createCmsApiHandler() +const handler = createCmsApiHandler({ mcp: cmsMcp }) function save(headers: Record, role = 'admin') { return handler( diff --git a/packages/api/tests/helpers.ts b/packages/api/tests/helpers.ts index 147fcfb5..40223c4e 100644 --- a/packages/api/tests/helpers.ts +++ b/packages/api/tests/helpers.ts @@ -2,6 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { defineCms } from '@tanstack/cms-core' +import { aiRuntime } from '@tanstack/cms-core/ai' import { closeStore, getStorage } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' @@ -20,6 +21,7 @@ export const cookieAuth: NonNullable = { export function setupCms(extra: Partial = {}): string { const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-api-')) dirs.push(dataDir) + const { ai, ...rest } = extra defineCms({ dataDir, collections: [ @@ -35,7 +37,10 @@ export function setupCms(extra: Partial = {}): string { ], blockTypes: [], auth: cookieAuth, - ...extra, + ...rest, + // Agent tools need an injected AI runtime; always provide it and let a + // test's own `ai` (textAdapter / agents) merge on top. + ai: { runtime: aiRuntime(), ...ai }, }) return dataDir } diff --git a/packages/api/tests/interface-ops.test.ts b/packages/api/tests/interface-ops.test.ts index d82bfddf..3dc019f1 100644 --- a/packages/api/tests/interface-ops.test.ts +++ b/packages/api/tests/interface-ops.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { chat } from '@tanstack/ai' import { defineInterfaceCollection, getCmsConfig } from '@tanstack/cms-core' +import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs' import { commitDocument, listPending } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { cleanup, req, setupCms } from './helpers' @@ -36,7 +37,10 @@ async function call(name: string, input: unknown, role = 'admin') { } beforeEach(async () => { setupCms({ - interfaces: { collection: 'interfaces' }, + interfaces: { + collection: 'interfaces', + runtime: quickjsInterfaceRuntime(), + }, collections: [ defineInterfaceCollection(), { diff --git a/packages/api/tests/optional-peers.test.ts b/packages/api/tests/optional-peers.test.ts index a0580387..36715a75 100644 --- a/packages/api/tests/optional-peers.test.ts +++ b/packages/api/tests/optional-peers.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { cmsMcp } from '../src/mcp' import { cleanup, req, setupCms } from './helpers' vi.mock('@tanstack/ai', () => { @@ -7,6 +8,15 @@ vi.mock('@tanstack/ai', () => { vi.mock('@tanstack/ai-mcp/server', () => { throw new Error("Cannot find package '@tanstack/ai-mcp' imported from test") }) +// `@tanstack/cms-core/ai`'s real `aiRuntime()` statically imports `@tanstack/ai` +// (mocked absent above). The test harness injects a runtime, so stub the entry +// with a trivial one — the assertions below exercise the actual AI op / MCP +// paths, which still resolve `@tanstack/ai` / `@tanstack/ai-mcp` at call time. +vi.mock('@tanstack/cms-core/ai', () => ({ + aiRuntime: () => ({ + toolDefinition: (_def: unknown) => ({ server: () => ({}) }), + }), +})) afterEach(cleanup) @@ -14,7 +24,7 @@ describe('without the optional AI peers', () => { it('loads the API and serves non-AI operations', async () => { const { createCmsApiHandler } = await import('../src/index') setupCms() - const handler = createCmsApiHandler() + const handler = createCmsApiHandler({ mcp: cmsMcp }) const res = await handler( req( '/api/cms/v1/ops/list?input=' + @@ -27,7 +37,7 @@ describe('without the optional AI peers', () => { it('reports AI operations as NOT_CONFIGURED, naming the package', async () => { const { createCmsApiHandler } = await import('../src/index') setupCms({ ai: { textAdapter: () => ({}) as never } }) - const res = await createCmsApiHandler()( + const res = await createCmsApiHandler({ mcp: cmsMcp })( req('/api/cms/v1/ops/editFieldWithAi', { method: 'POST', role: 'admin', @@ -51,7 +61,7 @@ describe('without the optional AI peers', () => { it('answers /api/mcp with NOT_CONFIGURED instead of crashing', async () => { const { createCmsApiHandler } = await import('../src/index') setupCms() - const res = await createCmsApiHandler()( + const res = await createCmsApiHandler({ mcp: cmsMcp })( req('/api/mcp', { method: 'POST', role: 'admin', diff --git a/packages/api/tests/readiness.test.ts b/packages/api/tests/readiness.test.ts index da64ed23..58f6b0a1 100644 --- a/packages/api/tests/readiness.test.ts +++ b/packages/api/tests/readiness.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it } from 'vitest' +import { cmsMcp } from '../src/mcp' import { defineCms, getCmsConfig, runWithCmsConfig } from '@tanstack/cms-core' import type { CmsConfig } from '@tanstack/cms-core' import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' @@ -206,7 +207,7 @@ describe('1.0 request invariants', () => { deletedAt: null, }, ) - const response = await createCmsApiHandler()( + const response = await createCmsApiHandler({ mcp: cmsMcp })( req('/api/cms/v1/ops/save', { method: 'POST', role: 'author', @@ -585,7 +586,7 @@ describe('1.0 request invariants', () => { doc: { title: '🎉'.repeat(20) }, }) expect(body.length).toBeLessThan(100) - const response = await createCmsApiHandler()( + const response = await createCmsApiHandler({ mcp: cmsMcp })( req('/api/cms/v1/ops/save', { method: 'POST', role: 'editor', @@ -598,7 +599,7 @@ describe('1.0 request invariants', () => { it('applies the JSON byte limit to authenticated MCP requests', async () => { setupCms({ security: { maxJsonBytes: 100 } }) - const response = await createCmsApiHandler()( + const response = await createCmsApiHandler({ mcp: cmsMcp })( req('/api/mcp', { method: 'POST', role: 'editor', @@ -628,7 +629,9 @@ describe('1.0 request invariants', () => { body, duplex: 'half', } as RequestInit) - expect((await createCmsApiHandler()(request)).status).toBe(413) + expect((await createCmsApiHandler({ mcp: cmsMcp })(request)).status).toBe( + 413, + ) expect(chunks).toBeLessThan(10) expect(cancelled).toBe(true) }) diff --git a/packages/api/tsdown.config.ts b/packages/api/tsdown.config.ts index 4e73b591..db102e52 100644 --- a/packages/api/tsdown.config.ts +++ b/packages/api/tsdown.config.ts @@ -1,7 +1,13 @@ import { defineConfig } from 'tsdown' export default defineConfig({ - entry: ['src/index.ts', 'src/start.ts', 'src/http.ts', 'src/markdown.ts'], + entry: [ + 'src/index.ts', + 'src/start.ts', + 'src/http.ts', + 'src/mcp.ts', + 'src/markdown.ts', + ], format: 'esm', platform: 'neutral', unbundle: true, diff --git a/packages/api/vitest.config.ts b/packages/api/vitest.config.ts index 9b8c0639..f9c40d8e 100644 --- a/packages/api/vitest.config.ts +++ b/packages/api/vitest.config.ts @@ -7,6 +7,9 @@ export default defineConfig({ dir: './', watch: false, environment: 'node', + // Core ships no storage default; restore the embedded PGlite engine + // for tests that don't inject their own `storage`. + setupFiles: ['@tanstack/cms-store-postgres/testing'], // DB-backed tests (embedded PGlite) flake at the 5s default on the loaded // minimum-Node runner; match cms-cli's headroom. testTimeout: 30_000, diff --git a/packages/cli/package.json b/packages/cli/package.json index 976309a9..a2c467f2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -69,6 +69,7 @@ }, "devDependencies": { "@tanstack/cms-core": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@types/node": "^24.10.1", "typescript": "5.9.3" } diff --git a/packages/cli/tests/fixtures/app/src/cms.config.ts b/packages/cli/tests/fixtures/app/src/cms.config.ts index 3d1df2f7..cf08ea94 100644 --- a/packages/cli/tests/fixtures/app/src/cms.config.ts +++ b/packages/cli/tests/fixtures/app/src/cms.config.ts @@ -1,6 +1,8 @@ import { defineCms } from '@tanstack/cms-core' +import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite' export const cms = defineCms({ + storage: createPgliteStorage, dataDir: process.env.CMS_FIXTURE_DATA_DIR, collections: [ { diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts index 2f5f69c3..cd19ffe0 100644 --- a/packages/cli/vitest.config.ts +++ b/packages/cli/vitest.config.ts @@ -7,6 +7,9 @@ export default defineConfig({ dir: './', watch: false, environment: 'node', + // Core ships no storage default; restore the embedded PGlite engine + // for tests that don't inject their own `storage`. + setupFiles: ['@tanstack/cms-store-postgres/testing'], include: ['tests/**/*.test.ts'], // The first command cold-loads the fixture app's config through the TS loader. testTimeout: 30_000, diff --git a/packages/client/package.json b/packages/client/package.json index edd9dd0b..dc3ea6a4 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -85,6 +85,7 @@ "devDependencies": { "@tanstack/cms-api": "workspace:*", "@tanstack/cms-core": "workspace:*", + "@tanstack/cms-store-postgres": "workspace:*", "@tanstack/db": "0.15.2", "@tanstack/query-core": "^5.105.0", "@tanstack/query-db-collection": "1.4.8", diff --git a/packages/client/vitest.config.ts b/packages/client/vitest.config.ts index b613aef6..a42361eb 100644 --- a/packages/client/vitest.config.ts +++ b/packages/client/vitest.config.ts @@ -8,6 +8,9 @@ export default defineConfig({ dir: './', watch: false, environment: 'node', + // Core ships no storage default; restore the embedded PGlite engine + // for tests that don't inject their own `storage`. + setupFiles: ['@tanstack/cms-store-postgres/testing'], include: ['tests/**/*.test.ts'], coverage: { provider: 'v8', diff --git a/packages/core/package.json b/packages/core/package.json index 242c8173..fc187d81 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -22,7 +22,11 @@ "exports": { ".": "./src/index.ts", "./definition": "./src/definition.ts", + "./read": "./src/read.ts", "./server": "./src/server.ts", + "./ai": "./src/ai.ts", + "./webmcp": "./src/webmcp.ts", + "./interfaces-quickjs": "./src/interfaces-quickjs.ts", "./flags": "./src/flags.ts", "./storage": "./src/storage.ts", "./storage/conformance": "./src/storage/conformance.ts", @@ -49,10 +53,26 @@ "types": "./dist/definition.d.ts", "import": "./dist/definition.js" }, + "./read": { + "types": "./dist/read.d.ts", + "import": "./dist/read.js" + }, "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" }, + "./ai": { + "types": "./dist/ai.d.ts", + "import": "./dist/ai.js" + }, + "./webmcp": { + "types": "./dist/webmcp.d.ts", + "import": "./dist/webmcp.js" + }, + "./interfaces-quickjs": { + "types": "./dist/interfaces-quickjs.d.ts", + "import": "./dist/interfaces-quickjs.js" + }, "./flags": { "types": "./dist/flags.d.ts", "import": "./dist/flags.js" @@ -147,6 +167,7 @@ "@tanstack/ai-code-mode": "0.5.5", "@tanstack/ai-isolate-quickjs": "0.3.2", "@tanstack/cms-store-postgres": "workspace:*", + "esbuild": "^0.25.0", "sharp": "^0.35.5", "typescript": "5.9.3", "xstate": "^5.33.3" diff --git a/packages/core/src/ai.ts b/packages/core/src/ai.ts new file mode 100644 index 00000000..e37a80d1 --- /dev/null +++ b/packages/core/src/ai.ts @@ -0,0 +1,17 @@ +/** + * The `@tanstack/ai` runtime for CMS agent tools. Import this entry only when + * you enable agent tools / MCP / the content agent — it statically imports + * `@tanstack/ai`, so the core engine stays free of it unless you opt in: + * + * import { aiRuntime } from '@tanstack/cms-core/ai' + * defineCms({ ai: { runtime: aiRuntime(), textAdapter, ... } }) + * + * Server-only. + */ +import { toolDefinition } from '@tanstack/ai' +import type { CmsAiRuntime } from './config' + +/** The `@tanstack/ai` runtime for `defineCms({ ai: { runtime } })`. */ +export function aiRuntime(): CmsAiRuntime { + return { toolDefinition } +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index d4db6b53..a842a7d3 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -42,7 +42,7 @@ import type { StandardSchemaV1, } from './schema' import type { CmsAuthConfig, CmsSession } from './lib/auth' -import type { StorageAdapter } from './storage/types' +import type { StorageAdapter, StorageFactory } from './storage/types' import type { MediaAdapter } from './media/types' import type { MediaKind } from './media/sniff' import type { CollectionAccess, Permission } from './lib/access' @@ -52,6 +52,7 @@ import type { OpInputOf, OpOutputOf, } from './ops' +import type { InterfaceRuntime } from './interfaces' import type { CmsEventsConfig, EventHandlerDefinition } from './events' import type { AnyDocumentStateStrategy } from './document-state' import type { PublishingStrategy } from './publishing' @@ -135,7 +136,25 @@ export interface CmsAgentConfig { tools?: (ctx: CmsOpContext) => Array | Promise> } +/** + * The `@tanstack/ai` bits the engine needs to expose CMS ops as agent tools. + * Injected via `defineCms({ ai: { runtime } })` so core never imports + * `@tanstack/ai` itself — use `aiRuntime()` from `@tanstack/cms-core/ai`. + * `toolDefinition` is typed opaquely here (keeping core config free of + * `@tanstack/ai` types); the server-only agent-tools builder narrows it. + */ +export interface CmsAiRuntime { + /** `@tanstack/ai`'s `toolDefinition`. */ + toolDefinition: unknown +} + export interface CmsAiConfig { + /** + * The `@tanstack/ai` runtime used to build agent tools (required for agent + * tools / MCP / the content agent). Supply with `aiRuntime()` from + * `@tanstack/cms-core/ai`. Text/image generation live in `@tanstack/cms-api`. + */ + runtime?: CmsAiRuntime /** A `@tanstack/ai` text adapter (OpenAI, Anthropic, Gemini, Ollama, …). */ textAdapter?: () => unknown /** A `@tanstack/ai` image adapter; it must accept an input image to support edits. */ @@ -292,6 +311,13 @@ export interface CmsConfig { /** Opt in to persisted code-mode pages/reports using a CMS content collection. */ interfaces?: { collection: string + /** + * The sandbox runtime that runs interface code. Required when `interfaces` + * is set, so core never imports the isolate/code-mode packages itself: + * `import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs'` + * then `runtime: quickjsInterfaceRuntime()`. + */ + runtime: InterfaceRuntime /** Resolve the schedule owner's CURRENT access; null suspends execution. Server-only. */ scheduleSession?: ( userId: string, @@ -315,11 +341,14 @@ export interface CmsConfig { */ publishing?: PublishingStrategy /** - * Persistence backend. Defaults to the embedded Postgres engine (PGlite) at - * `/pglite` via `@tanstack/cms-store-postgres/pglite`; use - * `createPostgresStorage()` against a server for production (D12). + * Persistence backend — required (the engine has no built-in default, so core + * never imports a storage package). For the embedded Postgres engine (PGlite): + * `import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite'` + * then `storage: createPgliteStorage` (a {@link StorageFactory} the engine + * hands the resolved `/pglite`). Use `createPostgresStorage({...})` + * against a server for production (D12). May also be a ready `StorageAdapter`. */ - storage?: StorageAdapter + storage?: StorageAdapter | StorageFactory /** * Media byte store. Defaults to `createLocalMedia()` at `/uploads`. See * `@tanstack/cms-core/media` and `@tanstack/cms-media-s3`. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 8028c942..388489e8 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -364,9 +364,8 @@ export type { CreateMockAuthOptions, } from './lib/mock-auth' -// In-page WebMCP server (framework-agnostic, optional MCP peer deps). -export { startWebMcpServer } from './lib/webmcp' -export type { WebMcpServerHandle } from './lib/webmcp' +// The in-page WebMCP server moved to its own entry (`@tanstack/cms-core/webmcp`) +// so the main surface never references the MCP SDK. // Roles & permissions (client-safe so UIs can hide what a user can't do). export { diff --git a/packages/core/src/interfaces-quickjs.ts b/packages/core/src/interfaces-quickjs.ts new file mode 100644 index 00000000..a62f4c59 --- /dev/null +++ b/packages/core/src/interfaces-quickjs.ts @@ -0,0 +1,23 @@ +/** + * The default code-mode interface runtime: a QuickJS WASM isolate + * (`@tanstack/ai-isolate-quickjs`) plus TypeScript stripping + * (`@tanstack/ai-code-mode`). Import this entry only when you enable + * `interfaces` — it statically pulls those (heavy, WASM) packages, so the core + * engine stays free of them unless you opt in: + * + * import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs' + * defineCms({ interfaces: { collection: 'interfaces', runtime: quickjsInterfaceRuntime() } }) + * + * Server-only. + */ +import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs' +import { stripTypeScript } from '@tanstack/ai-code-mode' +import type { InterfaceRuntime, IsolateDriver } from './interfaces' + +/** The QuickJS + code-mode interface runtime for `defineCms({ interfaces })`. */ +export function quickjsInterfaceRuntime(): InterfaceRuntime { + return { + createDriver: () => createQuickJSIsolateDriver() as IsolateDriver, + stripTypeScript, + } +} diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts index 5f3183b0..2ab74344 100644 --- a/packages/core/src/interfaces.ts +++ b/packages/core/src/interfaces.ts @@ -125,6 +125,44 @@ export interface InterfaceResult { /** Component ID -> collections actually read during this execution. */ subscriptions?: Record> } + +/** A host-exposed function the sandboxed code may call (an isolate binding). */ +export interface IsolateBinding { + name: string + description: string + inputSchema: unknown + execute: (args: any) => Promise | unknown +} + +/** One throwaway sandbox execution context (see `@tanstack/ai-isolate-quickjs`). */ +export interface IsolateContext { + execute: (code: string) => Promise<{ + success: boolean + value?: unknown + error?: { message?: string } + }> + dispose: () => Promise +} + +/** Creates isolated contexts to run untrusted interface code (QuickJS, …). */ +export interface IsolateDriver { + createContext: (options: { + bindings: Record + timeout?: number + memoryLimit?: number + }) => Promise | IsolateContext +} + +/** + * The sandbox + TypeScript-stripping runtime that executes code-mode + * interfaces. Injected via `defineCms({ interfaces: { collection, runtime } })` + * so core never imports the (heavy, WASM) isolate/code-mode packages itself — + * use `quickjsInterfaceRuntime()` from `@tanstack/cms-core/interfaces-quickjs`. + */ +export interface InterfaceRuntime { + createDriver: () => Promise | IsolateDriver + stripTypeScript: (code: string) => Promise +} export const interfaceInputSchema = z .object({ id: z.string().regex(/^[a-z][a-z0-9-]{0,99}$/), diff --git a/packages/core/src/read.ts b/packages/core/src/read.ts new file mode 100644 index 00000000..1f9033be --- /dev/null +++ b/packages/core/src/read.ts @@ -0,0 +1,163 @@ +/** + * `@tanstack/cms-core/read` — the tree-shakeable read + render surface for + * public pages on any runtime, including the edge (Kody/workerd, Cloudflare + * Workers, etc.). + * + * This module is deliberately **self-contained**: it imports nothing from + * `config`, `schema`, `server`, the storage engine, AI/MCP/code-mode, or + * `node:*`. That is what lets a public site bundle to a few KB with no WASM, + * no `eval`, and no server engine. The write/admin/migrate engine + * (`@tanstack/cms-core/server`) is a separate, heavier world; this is the half + * a blog, docs site, or marketing site needs to render. + */ + +// --- Document shape ------------------------------------------------------- + +/** A stored document's content (the `doc` JSONB in the CMS schema). */ +export type Doc = Record + +/** A content block: `{ _type, ...fields }`. */ +export type Block = { _type?: string; [key: string]: unknown } + +/** A document as returned from a store: its id + content. */ +export interface ReadRecord { + id: string + collection?: string + doc: Doc +} + +const asString = (v: unknown): string => (typeof v === 'string' ? v : '') + +export function isPublished(doc: Doc | null | undefined): boolean { + return !!doc && doc.published !== false +} + +// --- HTML + markdown primitives ------------------------------------------- + +export function escapeHtml(value: unknown): string { + return asString(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') +} + +/** + * Intentionally tiny markdown: blank-line paragraphs, `**bold**`, `` `code` ``. + * Enough for block/body text without pulling a markdown dependency into an edge + * bundle. Swap in a full renderer app-side if you need one. + */ +export function renderMarkdown(text: string): string { + return asString(text) + .split(/\n{2,}/) + .filter((p) => p.trim()) + .map((p) => { + const inner = escapeHtml(p) + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/`([^`]+)`/g, '$1') + return `

${inner}

` + }) + .join('') +} + +// --- Block rendering ------------------------------------------------------ + +export interface RenderContext { + escapeHtml: (v: unknown) => string + renderMarkdown: (text: string) => string +} + +export type BlockRenderer = (block: Block, ctx: RenderContext) => string + +/** Renderers for the built-in block palette → semantic, unstyled HTML. */ +export const defaultBlockRenderers: Record = { + hero: (b, c) => + `

${c.escapeHtml(b.heading)}

${ + asString(b.subheading) + ? `

${c.escapeHtml(b.subheading)}

` + : '' + }
`, + richText: (b, c) => c.renderMarkdown(asString(b.markdown)), + quote: (b, c) => + `

${c.escapeHtml(b.text)}

${ + asString(b.attribution) + ? `${c.escapeHtml(b.attribution)}` + : '' + }
`, + image: (b, c) => + asString(b.image) + ? `
${c.escapeHtml(b.caption)}${ + asString(b.caption) + ? `
${c.escapeHtml(b.caption)}
` + : '' + }
` + : '', + cta: (b, c) => + `

${ + c.escapeHtml(b.label) || c.escapeHtml(b.heading) + }

`, + callout: (b, c) => + ``, + code: (b, c) => `
${c.escapeHtml(b.code)}
`, +} + +const DEFAULT_CTX: RenderContext = { escapeHtml, renderMarkdown } + +/** + * Render an array of blocks to an HTML string. Pass `renderers` to override or + * extend the built-ins (merged over the defaults); unknown block types render + * to empty string. + */ +export function renderBlocks( + blocks: ReadonlyArray | unknown, + renderers: Record = {}, + ctx: RenderContext = DEFAULT_CTX, +): string { + if (!Array.isArray(blocks)) return '' + const map = { ...defaultBlockRenderers, ...renderers } + return (blocks as Array) + .map((b) => (b && map[String(b._type)] ? map[String(b._type)](b, ctx) : '')) + .join('') +} + +// --- Reading published documents ------------------------------------------ + +/** + * The minimal read surface the helpers below need. Implement it over whatever + * store you like — the full `@tanstack/cms-core/server` storage adapter + * satisfies it, and so does a ~10-line edge adapter over a serverless Postgres + * HTTP driver. Keeping it this small is what keeps the engine out of the bundle. + */ +export interface ReadStore { + getDocument: (collection: string, id: string) => Promise + queryDocuments: (query: { + collections: Array + limit?: number + }) => Promise<{ items: Array; total: number }> +} + +/** Get a single document by id, or null. Pass `publishedOnly` to gate drafts. */ +export async function getDocument( + store: ReadStore, + collection: string, + id: string, + options: { publishedOnly?: boolean } = {}, +): Promise { + const rec = await store.getDocument(collection, id) + if (!rec) return null + if (options.publishedOnly && !isPublished(rec.doc)) return null + return rec.doc +} + +/** List documents in a collection. Published-only by default. */ +export async function listDocuments( + store: ReadStore, + collection: string, + options: { limit?: number; publishedOnly?: boolean } = {}, +): Promise> { + const { limit = 100, publishedOnly = true } = options + const res = await store.queryDocuments({ collections: [collection], limit }) + return publishedOnly ? res.items.filter((r) => isPublished(r.doc)) : res.items +} diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index e70eef8e..2525b511 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -855,7 +855,11 @@ export function isCollectionReadOnly( if (typeof collection === 'string') { col = cfg.collections[collection] } - globalReadOnly = Boolean(cfg.storage?.readOnly) + // A `StorageFactory` is resolved lazily; don't construct it here just to + // read a flag. Factories are the writable embedded/server engines, so treat + // them as not read-only (a ready read-only adapter still reports via object). + globalReadOnly = + typeof cfg.storage === 'function' ? false : Boolean(cfg.storage?.readOnly) } catch { // config not registered } diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 04515374..20782ceb 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -15,9 +15,9 @@ export { isCmsError, toCmsError, statusForCode, - ensureDefaultAdapter, getStorage, resolveStorageAdapter, + setDefaultStorageFactory, isScalarField, closeStore, listCollectionsMeta, @@ -312,7 +312,7 @@ export { CMS_ACCESS_KEY, } from './server/cms-tools' export type { CoreSkillSummary, CmsToolsOptions } from './server/cms-tools' -export { isMissingModule, loadTanstackAi, missingPeer } from './server/optional' +export { isMissingModule, missingPeer } from './server/optional' export { resolveSession, requirePermission, diff --git a/packages/core/src/server/cms-tools.ts b/packages/core/src/server/cms-tools.ts index 8d651e5b..e4288fe7 100644 --- a/packages/core/src/server/cms-tools.ts +++ b/packages/core/src/server/cms-tools.ts @@ -6,10 +6,12 @@ * writes to the surface that proposed them and every read is scoped to the * agent. * - * `@tanstack/ai` is an optional peer, loaded on first call. + * The `@tanstack/ai` runtime is injected via `defineCms({ ai: { runtime } })` + * (`aiRuntime()` from `@tanstack/cms-core/ai`), so core never imports it. * * Server-only. */ +import { getCmsConfig } from '../config' import type { CmsOpDefinition, CmsToolResult } from '../ops' import { agentOps, @@ -18,7 +20,6 @@ import { runOp, } from './cms-ops' import type { CoreSkillSummary } from './cms-ops' -import { loadTanstackAi } from './optional' import { isAccessContext } from './access-context' import type { AccessContext } from './access-context' import { hasPermission } from '../lib/access' @@ -62,7 +63,19 @@ function callAccess(toolCtx: unknown): AccessContext | undefined { } export async function cmsTools(actor: string, options?: CmsToolsOptions) { - const { toolDefinition } = await loadTanstackAi() + const runtime = getCmsConfig().ai?.runtime + if (!runtime) { + throw new CmsError( + 'Agent tools need an AI runtime. Add: ' + + "import { aiRuntime } from '@tanstack/cms-core/ai'" + + ' then `defineCms({ ai: { runtime: aiRuntime(), ... } })`.', + 'NOT_CONFIGURED', + ) + } + // A type-only `import()` keeps the precise `@tanstack/ai` type without a + // value import (which would pull it into core's bundle). + // oxlint-disable-next-line typescript/consistent-type-imports + const toolDefinition = runtime.toolDefinition as typeof import('@tanstack/ai').toolDefinition const buildSession = options?.access?.session const observe = ( result: Omit & { result: unknown }, diff --git a/packages/core/src/server/content-migrations.ts b/packages/core/src/server/content-migrations.ts index 55c3b612..ceb01d35 100644 --- a/packages/core/src/server/content-migrations.ts +++ b/packages/core/src/server/content-migrations.ts @@ -13,11 +13,7 @@ import { getCmsConfig } from '../config' import { CmsError } from '../errors' import { collections, isCollectionReadOnly, schemaFor } from '../schema' import { denormalize } from './indexing' -import { - ensureDefaultAdapter, - getStorage, - resolveStorageAdapter, -} from './storage' +import { getStorage, resolveStorageAdapter } from './storage' import type { Collection, ContentMigration, Doc } from '../schema' import type { PendingRecord, StorageOps } from '../storage/types' import type { WhereClause } from '../storage/where' @@ -156,7 +152,6 @@ export async function contentMigrationStatus(): Promise< ) if (!migrating.length) return [] // Opening the store applies schema migrations; a status check mustn't. - await ensureDefaultAdapter() const schema = await resolveStorageAdapter().schemaStatus?.() const storage = schema?.current !== undefined && schema.current < (schema.latest ?? 0) diff --git a/packages/core/src/server/interfaces.ts b/packages/core/src/server/interfaces.ts index 3c62b438..6c088718 100644 --- a/packages/core/src/server/interfaces.ts +++ b/packages/core/src/server/interfaces.ts @@ -10,7 +10,9 @@ import { import type { InterfaceDefinition, InterfaceResult, + InterfaceRuntime, InterfaceState, + IsolateDriver, } from '../interfaces' import type { CmsOpContext } from '../ops' import type { Doc, JsonValue } from '../schema' @@ -114,10 +116,22 @@ export function createInterfaceQuery( return { items, total: result.total } } } -export async function interfaceDriver() { - const { createQuickJSIsolateDriver } = - await import('@tanstack/ai-isolate-quickjs') - return createQuickJSIsolateDriver() +/** The injected interface runtime, or a `NOT_CONFIGURED` error naming the fix. */ +function interfaceRuntime(): InterfaceRuntime { + const runtime = getCmsConfig().interfaces?.runtime + if (!runtime) { + throw new CmsError( + 'Code-mode interfaces need a runtime. Add: ' + + "import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs'" + + ' then `defineCms({ interfaces: { collection, runtime: quickjsInterfaceRuntime() } })`.', + 'NOT_CONFIGURED', + ) + } + return runtime +} + +export async function interfaceDriver(): Promise { + return interfaceRuntime().createDriver() } const jsonResult = z.record(z.string(), z.json()) /** Every run uses fresh isolates; persistence is the stored code, not a shared VM. */ @@ -171,9 +185,10 @@ export async function executeInterface( return { result, evidence } } async function validateHandlerSyntax(code: string) { - const { stripTypeScript } = await import('@tanstack/ai-code-mode') + const runtime = interfaceRuntime() + const { stripTypeScript } = runtime const sandbox = await ( - await interfaceDriver() + await runtime.createDriver() ).createContext({ bindings: {}, timeout: 2000, memoryLimit: 32 }) try { const js = await stripTypeScript(`async function action() { ${code}\n }`) @@ -195,8 +210,9 @@ async function executeCode( event?: JsonValue, stageWrites = true, ) { - const { stripTypeScript } = await import('@tanstack/ai-code-mode') - const driver = await interfaceDriver() + const runtime = interfaceRuntime() + const { stripTypeScript } = runtime + const driver = await runtime.createDriver() let bindingError: unknown let writes = 0 const sandbox = await driver.createContext({ diff --git a/packages/core/src/server/optional.ts b/packages/core/src/server/optional.ts index 7c22f532..9333e47c 100644 --- a/packages/core/src/server/optional.ts +++ b/packages/core/src/server/optional.ts @@ -1,11 +1,13 @@ /** - * Loaders for optional peer dependencies, so the engine only needs them when - * a feature that uses them runs. + * Helpers for optional peer dependencies: detect "not installed" and build the + * actionable error. Core never loads an optional peer itself — capabilities are + * injected via `defineCms` (storage / ai.runtime / interfaces.runtime). These + * helpers remain for consumers that load their own peers (e.g. `@tanstack/cms-api` + * loading `@tanstack/ai` or `@tanstack/ai-mcp`). * * Server-only. */ import { CmsError } from '../errors' -import type * as TanstackAi from '@tanstack/ai' /** * Whether `error` (or an error it wraps as `cause`) is a failure to resolve @@ -36,15 +38,3 @@ export function missingPeer(specifier: string, feature: string): CmsError { 'NOT_CONFIGURED', ) } - -/** Load `@tanstack/ai`, or throw `NOT_CONFIGURED` naming the package to install. */ -export async function loadTanstackAi(): Promise { - try { - return await import('@tanstack/ai') - } catch (e) { - if (isMissingModule(e, '@tanstack/ai')) { - throw missingPeer('@tanstack/ai', 'AI features') - } - throw e - } -} diff --git a/packages/core/src/server/storage.ts b/packages/core/src/server/storage.ts index 4d9cec46..1186b665 100644 --- a/packages/core/src/server/storage.ts +++ b/packages/core/src/server/storage.ts @@ -13,6 +13,7 @@ import { randomUUID } from 'node:crypto' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' +import { CmsError } from '../errors' import { cmsLogger, getCmsConfig, runWithCmsConfig } from '../config' import { isCollectionReadOnly } from '../schema' import { evaluateStorageQuery } from '../storage/evaluate' @@ -29,10 +30,12 @@ import type { OutboxOps, PendingRecord, StorageAdapter, + StorageFactory, StorageOps, } from '../storage/types' -const defaultAdapters = new Map() +/** Adapters built from a `StorageFactory`, resolved once per config. */ +const factoryAdapters = new Map() const compositeAdapters = new WeakMap() const ready = new WeakMap>() const lastScheduledRun = new WeakMap() @@ -108,63 +111,49 @@ export function notifyStorageCommit(): void { dispatchLoading.set(config, loading) } -/** The embedded default engine's data directory for the active config. */ -function defaultPglitePath(): string { - return `${resolveDataDir()}/pglite` -} +const MISSING_STORAGE = + 'No `storage` configured. The engine has no built-in default. For the ' + + 'embedded Postgres engine (dev): install @tanstack/cms-store-postgres and ' + + '@electric-sql/pglite, then `import { createPgliteStorage } from ' + + "'@tanstack/cms-store-postgres/pglite'` and pass " + + '`defineCms({ storage: createPgliteStorage })`. For production, pass ' + + '`createPostgresStorage({ ... })` against a Postgres server.' + +let defaultStorageFactory: StorageFactory | null = null /** - * Load and cache the default store when an app configures none: embedded - * Postgres (PGlite), the dev engine (D12), keyed by its data directory so each - * config/test gets its own. A dynamic `import()` keeps core free of a static - * dependency on `@tanstack/cms-store-postgres` (which depends on core); the - * `init` scaffold installs it + `@electric-sql/pglite`. + * Opt-in process-wide fallback `StorageFactory`, used only when a config omits + * `storage`. Off by default — core ships no storage, so a production app that + * forgets `storage` still gets the `MISSING_STORAGE` error and no storage + * package is ever imported or bundled. This exists for test harnesses and + * single-config dev servers that want the embedded engine without repeating it + * in every `defineCms` (e.g. `@tanstack/cms-store-postgres/testing` wires it to + * `createPgliteStorage`). Pass `null` to clear. */ -async function getDefaultAdapter(): Promise { - const path = defaultPglitePath() - let adapter = defaultAdapters.get(path) - if (!adapter) { - let createPgliteStorage - try { - ;({ createPgliteStorage } = - await import('@tanstack/cms-store-postgres/pglite')) - } catch { - throw new Error( - 'No `storage` configured and the embedded engine is unavailable. ' + - 'Install @tanstack/cms-store-postgres and @electric-sql/pglite, or ' + - 'pass defineCms({ storage }).', - ) - } - adapter = createPgliteStorage({ dataDir: path }) - defaultAdapters.set(path, adapter) - } - return adapter +export function setDefaultStorageFactory(factory: StorageFactory | null): void { + defaultStorageFactory = factory } -/** The cached default adapter for the sync resolvers; `getStorage` loads it first. */ -function requireDefaultAdapter(): StorageAdapter { - const adapter = defaultAdapters.get(defaultPglitePath()) +/** + * The app-configured base adapter: a ready `StorageAdapter`, or a + * `StorageFactory` the engine resolves once (handing it the data directory it + * should persist in). Throws a `NOT_CONFIGURED` `CmsError` naming the exact + * import to add when `storage` is absent — core never falls back to a storage + * package of its own. Synchronous: factories must construct without awaiting + * (both `createPgliteStorage` and `createPostgresStorage` do). + */ +function baseAdapterFor(cfg: ResolvedCmsConfig): StorageAdapter { + const storage = cfg.storage ?? defaultStorageFactory + if (!storage) throw new CmsError(MISSING_STORAGE, 'NOT_CONFIGURED') + if (typeof storage !== 'function') return storage + let adapter = factoryAdapters.get(cfg) if (!adapter) { - throw new Error( - 'Default storage is not initialized yet; call getStorage() first.', - ) + adapter = storage({ dataDir: `${resolveDataDir()}/pglite` }) + factoryAdapters.set(cfg, adapter) } return adapter } -/** - * Construct (not initialize) the default engine so the synchronous resolvers - * can return it. Callers that read the adapter without going through - * `getStorage` (status/migrate/backup) must await this first. - */ -export async function ensureDefaultAdapter(): Promise { - const cfg = getCmsConfig() - const allColsHaveStorage = - Object.keys(cfg.collections).length > 0 && - Object.values(cfg.collections).every((c) => Boolean(c.storage)) - if (!cfg.storage && !allColsHaveStorage) await getDefaultAdapter() -} - function createCompositeStorage(cfg: ResolvedCmsConfig): StorageAdapter { const colAdapters = new Map() for (const col of Object.values(cfg.collections)) { @@ -177,11 +166,14 @@ function createCompositeStorage(cfg: ResolvedCmsConfig): StorageAdapter { Boolean(a.readOnly), ) const needsBaseAdapter = Boolean(cfg.storage) || !allColsHaveStorage - let baseAdapter: StorageAdapter | null = cfg.storage ?? null + // A `StorageFactory` resolves lazily (like the old embedded default), so a + // read-only, all-collections-have-storage config never constructs it. + let baseAdapter: StorageAdapter | null = + typeof cfg.storage === 'function' ? null : (cfg.storage ?? null) function getBase(): StorageAdapter { if (!baseAdapter) { - baseAdapter = requireDefaultAdapter() + baseAdapter = baseAdapterFor(cfg) } return baseAdapter } @@ -754,8 +746,7 @@ export function resolveStorageAdapter(): StorageAdapter { } return composite } - if (cfg.storage) return cfg.storage - return requireDefaultAdapter() + return baseAdapterFor(cfg) } function indexedFields(): Array { @@ -823,7 +814,6 @@ export async function getStorage(options?: { /** Dispatcher internals must not kick themselves while acquiring storage. */ dispatch?: boolean }): Promise { - await ensureDefaultAdapter() const adapter = resolveStorageAdapter() let init = ready.get(adapter) if (!init) { @@ -863,10 +853,12 @@ export async function getStorage(options?: { export async function closeAllStorage(): Promise { await Promise.all(dispatchLoading.values()) await dispatchStop?.() - const adapters = new Set(defaultAdapters.values()) + const adapters = new Set(factoryAdapters.values()) try { const cfg = getCmsConfig() - if (cfg.storage) adapters.add(cfg.storage) + // A factory's adapter is already in `factoryAdapters`; add only a ready one. + if (cfg.storage && typeof cfg.storage !== 'function') + adapters.add(cfg.storage) for (const col of Object.values(cfg.collections)) { if (col.storage) adapters.add(col.storage) } @@ -888,7 +880,7 @@ export async function closeAllStorage(): Promise { // already closed } } - defaultAdapters.clear() + factoryAdapters.clear() } interface LegacyStore { diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 6991db08..c48e95f5 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -12,9 +12,9 @@ export { CmsError, isCmsError, toCmsError, statusForCode } from '../errors' export type { CmsErrorCode, CmsErrorJson } from '../errors' export { - ensureDefaultAdapter, getStorage, resolveStorageAdapter, + setDefaultStorageFactory, } from './storage' export type { WriteType, diff --git a/packages/core/src/server/transfer.ts b/packages/core/src/server/transfer.ts index 9ae24798..52fcf97a 100644 --- a/packages/core/src/server/transfer.ts +++ b/packages/core/src/server/transfer.ts @@ -13,12 +13,7 @@ import { isCollectionReadOnly } from '../schema' import { requireStorageCapability } from '../storage/capabilities' import { denormalize } from './indexing' import { resolveMediaAdapter } from './media' -import { - ensureDefaultAdapter, - getStorage, - resolveStorageAdapter, - uniqueFieldSpecs, -} from './storage' +import { getStorage, resolveStorageAdapter, uniqueFieldSpecs } from './storage' import { enqueueEvent } from './outbox' import { systemContext } from './access-context' import { @@ -713,7 +708,6 @@ export interface StorageStatus { /** Schema version of the configured storage, without migrating or seeding it. */ export async function storageStatus(): Promise { - await ensureDefaultAdapter() const adapter = resolveStorageAdapter() const status = await adapter.schemaStatus?.() return { storage: adapter.name, ...status } @@ -728,7 +722,6 @@ export type StorageHealth = * A schema behind `latest` (run `tanstack-cms migrate`) is unhealthy. */ export async function storageHealth(): Promise { - await ensureDefaultAdapter() const adapter = resolveStorageAdapter() try { const storage = await getStorage() @@ -758,7 +751,6 @@ export async function storageHealth(): Promise { export async function migrateStorage(): Promise< StorageStatus & { applied: Array } > { - await ensureDefaultAdapter() const adapter = resolveStorageAdapter() const applied = adapter.migrate ? await adapter.migrate() : [] if (!adapter.migrate) await adapter.init() diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts index 04caef19..ec76d0cf 100644 --- a/packages/core/src/storage/types.ts +++ b/packages/core/src/storage/types.ts @@ -803,3 +803,21 @@ export interface StorageAdapter extends StorageOps { */ backup?: (path: string) => Promise } + +/** What a {@link StorageFactory} receives when the engine resolves it. */ +export interface StorageFactoryContext { + /** + * The resolved data directory the embedded engine should persist in: + * `/pglite`, else `<$CMS_DATA_DIR>/pglite`, else + * `/.data/pglite`. A factory is free to ignore it (e.g. a server pool). + */ + dataDir: string +} + +/** + * A lazy `StorageAdapter`: `defineCms({ storage })` accepts this so the engine + * injects the resolved {@link StorageFactoryContext} (notably `dataDir`) at + * registration. `createPgliteStorage` has this exact shape, so the common dev + * config is `defineCms({ storage: createPgliteStorage })`. Resolved once. + */ +export type StorageFactory = (ctx: StorageFactoryContext) => StorageAdapter diff --git a/packages/core/src/lib/webmcp.ts b/packages/core/src/webmcp.ts similarity index 78% rename from packages/core/src/lib/webmcp.ts rename to packages/core/src/webmcp.ts index 6beaaa57..ed5505a4 100644 --- a/packages/core/src/lib/webmcp.ts +++ b/packages/core/src/webmcp.ts @@ -1,14 +1,15 @@ /** - * Framework-agnostic WebMCP server startup for `@tanstack/cms-core`. - * - * Exposes CMS tools to an in-browser AI agent (e.g. Claude in Chrome) via an - * in-page MCP server bridged over postMessage (MCP-B). The transport only - * accepts messages from this page's own origin. MCP libs are dynamically - * imported so they never load during SSR. + * In-browser WebMCP server for `@tanstack/cms-core` — its own entry + * (`@tanstack/cms-core/webmcp`) so the engine's main surface never references + * the MCP SDK. Import it only to expose CMS tools to an in-page AI agent (e.g. + * Claude in Chrome) via an MCP server bridged over postMessage (MCP-B). The + * transport only accepts messages from this page's own origin. The MCP libs are + * still dynamically imported here so merely importing this entry stays + * SSR-safe; they load when `startWebMcpServer()` actually runs in the browser. * * Re-exported by `@tanstack/cms-ui-react` and `@tanstack/cms-ui-dom`. */ -import { agentOpSchemas } from '../ops' +import { agentOpSchemas } from './ops' import type { z } from 'zod' async function callCms(op: string, input: unknown, endpoint = '/api/cms') { diff --git a/packages/core/tests/access-context.test.ts b/packages/core/tests/access-context.test.ts index 5644b1ad..862b7eea 100644 --- a/packages/core/tests/access-context.test.ts +++ b/packages/core/tests/access-context.test.ts @@ -2,6 +2,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 { aiRuntime } from '../src/ai' import { PERMISSIONS, UNAUTHENTICATED_SESSION, @@ -87,7 +88,12 @@ const memo = defineCollection({ function config(marker: string): CmsConfig { const dataDir = mkdtempSync(join(tmpdir(), `tanstack-cms-ctx-${marker}-`)) dirs.push(dataDir) - return { dataDir, collections: [post, memo], blockTypes: [] } + return { + dataDir, + collections: [post, memo], + blockTypes: [], + ai: { runtime: aiRuntime() }, + } } async function seeded(): Promise { diff --git a/packages/core/tests/bundle-seams.test.ts b/packages/core/tests/bundle-seams.test.ts new file mode 100644 index 00000000..829368ea --- /dev/null +++ b/packages/core/tests/bundle-seams.test.ts @@ -0,0 +1,86 @@ +import { fileURLToPath } from 'node:url' +import { build } from 'esbuild' +import { describe, expect, it } from 'vitest' + +/** + * The capability-seam lock-in: the engine's own entries must never pull an + * optional capability package into their static bundle graph, and the opt-in + * entries must. This is what actually makes AI / code-mode / MCP / embedded + * storage addable rather than always-present — a dynamic `import()` would not + * be enough (esbuild inlines those into a single-file bundle), so these are the + * tests that keep the seams honest. + * + * Markers are matched against esbuild metafile input paths (pnpm-style, e.g. + * `.../node_modules/@tanstack/ai/dist/...`), so the trailing `/` pins the exact + * package and avoids matching siblings (`@tanstack/ai` vs `@tanstack/ai-mcp`). + */ +const CAPABILITY_MARKERS = { + 'embedded storage (PGlite)': '/@electric-sql/pglite/', + 'store-postgres': '/@tanstack/cms-store-postgres/', + '@tanstack/ai': '/@tanstack/ai/', + 'AI code-mode': '/@tanstack/ai-code-mode/', + 'QuickJS isolate': '/@tanstack/ai-isolate-quickjs/', + 'HTTP MCP (ai-mcp)': '/@tanstack/ai-mcp/', + 'MCP SDK': '/@modelcontextprotocol/', + 'MCP-B transport': '/@mcp-b/', + sucrase: '/sucrase/', +} as const + +async function bundleInputs(entry: string): Promise> { + const result = await build({ + entryPoints: [fileURLToPath(new URL(`../src/${entry}`, import.meta.url))], + bundle: true, + write: false, + metafile: true, + platform: 'node', + format: 'esm', + logLevel: 'silent', + }) + return Object.keys(result.metafile.inputs) +} + +function pull(inputs: Array, marker: string): boolean { + return inputs.some((i) => i.includes(marker)) +} + +describe('bundle seams — engine entries are capability-free', () => { + it('@tanstack/cms-core/server pulls no optional capability', async () => { + const inputs = await bundleInputs('server.ts') + for (const [name, marker] of Object.entries(CAPABILITY_MARKERS)) { + expect(pull(inputs, marker), `core/server must not bundle ${name}`).toBe( + false, + ) + } + }) + + it('@tanstack/cms-core (main) pulls no optional capability', async () => { + const inputs = await bundleInputs('index.ts') + for (const [name, marker] of Object.entries(CAPABILITY_MARKERS)) { + expect(pull(inputs, marker), `core (main) must not bundle ${name}`).toBe( + false, + ) + } + }) + + it('@tanstack/cms-core/read pulls no optional capability', async () => { + const inputs = await bundleInputs('read.ts') + for (const [name, marker] of Object.entries(CAPABILITY_MARKERS)) { + expect(pull(inputs, marker), `core/read must not bundle ${name}`).toBe( + false, + ) + } + }) +}) + +describe('bundle seams — opt-in entries carry their capability', () => { + it('@tanstack/cms-core/ai bundles @tanstack/ai', async () => { + const inputs = await bundleInputs('ai.ts') + expect(pull(inputs, CAPABILITY_MARKERS['@tanstack/ai'])).toBe(true) + }) + + it('@tanstack/cms-core/interfaces-quickjs bundles the isolate + code-mode', async () => { + const inputs = await bundleInputs('interfaces-quickjs.ts') + expect(pull(inputs, CAPABILITY_MARKERS['QuickJS isolate'])).toBe(true) + expect(pull(inputs, CAPABILITY_MARKERS['AI code-mode'])).toBe(true) + }) +}) diff --git a/packages/core/tests/interface-schedules.test.ts b/packages/core/tests/interface-schedules.test.ts index ace54f33..98bc63de 100644 --- a/packages/core/tests/interface-schedules.test.ts +++ b/packages/core/tests/interface-schedules.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { quickjsInterfaceRuntime } from '../src/interfaces-quickjs' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -85,6 +86,7 @@ beforeEach(async () => { ], interfaces: { collection: 'interfaces', + runtime: quickjsInterfaceRuntime(), scheduleSession: () => (enabled ? ctx().session : null), }, events: { dispatch: 'manual' }, diff --git a/packages/core/tests/interfaces.test.ts b/packages/core/tests/interfaces.test.ts index 3a7bcd10..40065bce 100644 --- a/packages/core/tests/interfaces.test.ts +++ b/packages/core/tests/interfaces.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { quickjsInterfaceRuntime } from '../src/interfaces-quickjs' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -112,7 +113,10 @@ beforeEach(async () => { ], blockTypes: [], dataDir: dir, - interfaces: { collection: 'interfaces' }, + interfaces: { + collection: 'interfaces', + runtime: quickjsInterfaceRuntime(), + }, events: { dispatch: 'manual' }, }) await commitDocument('recipes', 'eggs', { diff --git a/packages/core/tests/read.test.ts b/packages/core/tests/read.test.ts new file mode 100644 index 00000000..fcc78d46 --- /dev/null +++ b/packages/core/tests/read.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, it } from 'vitest' +import { + type Block, + type ReadStore, + defaultBlockRenderers, + escapeHtml, + getDocument, + isPublished, + listDocuments, + renderBlocks, + renderMarkdown, +} from '../src/read' + +describe('read: html + markdown primitives', () => { + it('escapes html-significant characters', () => { + expect(escapeHtml('&y')).toBe( + '<a href="x">&y', + ) + expect(escapeHtml(null)).toBe('') + expect(escapeHtml(42)).toBe('') + }) + + it('renders tiny markdown (paragraphs, bold, code)', () => { + expect(renderMarkdown('a\n\nb')).toBe('

a

b

') + expect(renderMarkdown('**bold** and `x`')).toBe( + '

bold and x

', + ) + expect(renderMarkdown('')).toBe('') + // escapes before formatting + expect(renderMarkdown('