diff --git a/.changeset/cms-definition-entry.md b/.changeset/cms-definition-entry.md new file mode 100644 index 00000000..ca711dad --- /dev/null +++ b/.changeset/cms-definition-entry.md @@ -0,0 +1,43 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-ui-react': patch +--- + +Add the light CMS definition entry, `@tanstack/cms-core/definition`, now the +recommended shape for new apps. `defineCmsDefinition({ collections, admin, +plugins })` holds what routing and build tooling need and imports no React, +server code, or Start, so `vite.config.ts` can import it. Its accessors are +derived from it: `adminBasePath()`, `collections()`, `pluginRoutes()`, and +`routeKeys()`. The entry also exports the pure authoring helpers, the same +functions the root exports: `defineCollection`, `defineBlock`, +`defineFieldType`, `definePlugin`, `seoField`, `assetField`, +`redirectsCollection`, `isSafeRedirectTarget`, and `isBuiltInFieldType`. It +exports the types collections use too, so a `cms.definition.ts` and its +collection modules never need the package root. + +`defineCms(definition, runtime)` (and `createCms(definition, runtime)`) extends +a definition with the runtime config: `auth`, `storage`, `ai`, `ops`, +`eventHandlers`, `seed`, and the rest. The runtime config can't repeat +`collections`, `admin`, or `plugins`. It resolves the same config, with the same +plugin merging and name checks, as `defineCms(config)`, which keeps working. + +```ts +// src/cms.definition.ts +import { defineCmsDefinition } from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [post, author], + admin: { basePath: '/admin' }, +}) + +// src/cms.config.ts +export const cms = defineCms(definition, { blockTypes: [], auth, storage }) +``` + +`Register` accepts the definition (`cms: typeof definition`) as well as the full +config, and `RegisteredCollectionName`, `RegisteredDoc`, and +`RegisteredAdminBasePath` infer from it. + +The CMS route keys now live in core as `CMS_ROUTE_KEYS` (grouped by `public`, +`admin`, and `api`). `CmsRouteKey` from `@tanstack/cms-ui-react/virtual-routes` +is the same type, re-exported. diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 2ae99b30..a3a9ae6d 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -2,12 +2,13 @@ title: "@tanstack/cms-core" id: api-cms-core order: 1 -description: "API reference for @tanstack/cms-core: defineCms and the config types, theme and SEO helpers, the schema and field system, the operation registry, the auth contract, roles and permissions, structured errors, plus the /storage and /media entry points." +description: "API reference for @tanstack/cms-core: defineCms, the light /definition entry, and the config types, theme and SEO helpers, the schema and field system, the operation registry, the auth contract, roles and permissions, structured errors, plus the /storage and /media entry points." keywords: - tanstack cms - api reference - "@tanstack/cms-core" - defineCms + - defineCmsDefinition - CmsConfig - schemaFor - cmsHead @@ -16,11 +17,12 @@ keywords: - createLocalMedia --- -`@tanstack/cms-core` is the framework-agnostic engine. It has four entry points: +`@tanstack/cms-core` is the framework-agnostic engine. It has five entry points: | Entry point | Environment | Contents | | --- | --- | --- | | `@tanstack/cms-core` | client and server | Config, schema and fields, theme, SEO head helpers, roles and permissions, errors (this page). | +| `@tanstack/cms-core/definition` | anywhere, including `vite.config.ts` | `defineCmsDefinition()`, the light CMS definition, and the CMS route keys ([below](#the-cms-definition-definecmsdefinition)). | | `@tanstack/cms-core/server` | server only | Store, workflow, media, SEO files, webhooks, transfer, auth guards. See [`@tanstack/cms-core/server`](./cms-core-server). | | `@tanstack/cms-core/storage` | config-safe | `StorageAdapter` contract, `createSqliteStorage()`, and the SQL adapter kit ([below](#tanstackcms-corestorage)). | | `@tanstack/cms-core/media` | config-safe | `MediaAdapter` contract and `createLocalMedia()` ([below](#tanstackcms-coremedia)). | @@ -86,6 +88,103 @@ export const cms = defineCms({ `cms.config.ts` is bundled for the browser too. Read secrets lazily inside functions (AI adapter factories, webhook `url`/`secret` functions), never at module top level. +### The CMS definition: `defineCmsDefinition()` + +**The recommended shape for new apps.** Split the CMS into a light definition and the runtime config that extends it: + +- `src/cms.definition.ts` holds what routing and build tooling need: `collections`, `admin`, and `plugins`. It and its collection modules import only `@tanstack/cms-core/definition`, so `vite.config.ts` can import it without loading auth, storage, AI, ops, or event handlers. +- `src/cms.config.ts` calls `defineCms(definition, runtime)` with everything else. Nothing is repeated. + +```ts +// src/collections.ts +import { defineCollection, seoField } from '@tanstack/cms-core/definition' + +export const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }, seoField()], +}) +``` + +```ts +// src/cms.definition.ts +import { defineCmsDefinition } from '@tanstack/cms-core/definition' +import { post, author } from './collections' + +export const definition = defineCmsDefinition({ + collections: [post, author], + admin: { basePath: '/admin' }, +}) +``` + +```ts +// src/cms.config.ts +import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, { + blockTypes: [], + auth, + storage, + ai, + ops, + eventHandlers, + seed, +}) +``` + +```ts +function defineCmsDefinition( + config: TConfig, +): CmsDefinition + +function defineCms( + definition: CmsDefinition, + runtime: TRuntime, +): WithPlugins> +``` + +`defineCmsDefinition` throws on the same collection and plugin name clashes as `defineCms`. The runtime config is every `CmsConfig` option except `collections`, `admin`, and `plugins`; repeating one of those is a type error and throws. `defineCms(definition, runtime)` resolves exactly the config `defineCms({ ...definitionConfig, ...runtime })` would, and `createCms(definition, runtime)` builds an instance the same way. `defineCms(config)` with one config keeps working, and is fine for an app whose config is already light. + +The definition's accessors are derived from it, never written by hand, and return the same frozen values on every call: + +| Accessor | Returns | +| --- | --- | +| `adminBasePath()` | The normalized `admin.basePath`: `''` or `/segment` without a trailing slash. | +| `collections()` | `{ name }` for each app and plugin collection, in order. Public URL prefixes come later. | +| `pluginRoutes()` | `{ routes, adminRoutes }`, each entry `{ plugin, route }`: the plugins' route nodes, tagged with the plugin name. | +| `routeKeys()` | Every CMS route key (`index`, `content`, `edit`, `review`, `apiV1`, …). The list is `CMS_ROUTE_KEYS`, grouped by surface (`public`, `admin`, `api`); `CmsRouteKey` is its union. | + +`definition.config` is the config as written. `isCmsDefinition(value)` tells a definition apart from a config. + +`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineBlock`, `defineFieldType`, `definePlugin`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, and `isBuiltInFieldType`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, and `CmsPlugin`. `defineInterfaceCollection` stays root-only, because its validators need the interface schemas. + +```ts validate=type +import { defineCms } from '@tanstack/cms-core' +import { defineCmsDefinition } from '@tanstack/cms-core/definition' + +const definition = defineCmsDefinition({ + collections: [ + { + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text', required: true }], + }, + ], + admin: { basePath: '/admin' }, +}) + +definition.adminBasePath() // '/admin' +definition.collections() // [{ name: 'post' }] + +export const cms = defineCms(definition, { blockTypes: [], dataDir: '.data' }) +cms.collections.post.label // 'Posts' +``` + +`pnpm test:definitions` (`scripts/verify-definitions.ts`) loads every `cms.definition.ts` under `app/`, `starters/`, and `examples/` in plain Node and reports any import of `react`, `react-dom`, a `.tsx` file, `@tanstack/react-start`, `@tanstack/react-router`, the `@tanstack/cms-ui-react` root, `@tanstack/cms-core/server`, or a `*.server.*` file. It runs report-only for now; `--strict` makes it fail. + ### `getCmsConfig()` ```ts @@ -372,7 +471,7 @@ interface SeedStore { ### `Register` and registered types ```ts -interface Register {} // augment with { cms: typeof cms } +interface Register {} // augment with { cms: typeof definition } or { cms: typeof cms } type RegisteredCollections // your collections keyed by name, or Record type RegisteredCollectionName // their names (string when nothing is registered) @@ -380,12 +479,12 @@ type RegisteredDoc // InferDoc of collection C, or Doc type RegisteredAdminBasePath // admin.basePath literal, or '' ``` -Augment `Register` once to type `RegisteredDoc`, `adminPath()`, and the `@tanstack/cms-client` collection helpers: +Augment `Register` once to type `RegisteredDoc`, `adminPath()`, and the `@tanstack/cms-client` collection helpers. `cms` may be the definition (collections, plugin collections, and `admin.basePath` are typed from it), the `defineCms` result, or the config passed to it. Register the `defineCms` result instead when you need app ops typed (`RegisteredOps`), since ops live in the runtime config: ```ts declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } ``` diff --git a/docs/api/cms-ui-react.md b/docs/api/cms-ui-react.md index 0d38e378..200b63a0 100644 --- a/docs/api/cms-ui-react.md +++ b/docs/api/cms-ui-react.md @@ -362,8 +362,9 @@ type RelationSearch = ( ```ts function cmsVirtualRoutes(options?: CmsVirtualRoutesOptions): VirtualRootRoute +// Re-exported from @tanstack/cms-core/definition (CMS_ROUTE_KEYS) type CmsRouteKey = - | 'index' | 'page' | 'post' | 'sitemap' | 'robots' | 'notFound' + | 'index' | 'page' | 'post' | 'preview' | 'sitemap' | 'robots' | 'notFound' | 'content' | 'edit' | 'agent' | 'review' | 'settings' | 'apiWebMcp' | 'apiV1' | 'apiMcp' | 'apiMedia' | 'apiMediaFile' ``` diff --git a/knip.json b/knip.json index 246c3738..c9657df5 100644 --- a/knip.json +++ b/knip.json @@ -8,7 +8,8 @@ "ignore": [ "kiira.config.ts", ".claude/skills/**", - "scripts/codemods/__fixtures__/**" + "scripts/codemods/__fixtures__/**", + "scripts/__fixtures__/**" ], "ignoreExportsUsedInFile": true, "workspaces": { @@ -27,8 +28,9 @@ }, "packages/core": { "entry": [ - "src/{index,server,storage,media}.ts", - "src/{storage,media}/conformance.ts" + "src/{index,definition,server,storage,media}.ts", + "src/{storage,media}/conformance.ts", + "tests/register-definition/*.ts" ] }, "packages/ui-react": { diff --git a/package.json b/package.json index 49b9a68e..8d185e3d 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,8 @@ "clean": "pnpm --filter \"./packages/**\" --filter \"./onboarding/packages/**\" run clean", "clean:all": "git clean -fdx --exclude=\"!.env\"", "test": "pnpm run test:ci", - "test:pr": "VITEST_MAX_WORKERS=1 nx affected --targets=test:sherif,test:knip,test:docs,test:starters,test:kiira,test:oxlint,test:lib,test:starter,test:types,test:scripts,test:build,build --exclude=*-before && pnpm test:dts && pnpm test:dialects", - "test:ci": "VITEST_MAX_WORKERS=1 nx run-many --targets=test:sherif,test:knip,test:docs,test:starters,test:kiira,test:oxlint,test:lib,test:starter,test:types,test:scripts,test:build,build --exclude=*-before && pnpm test:dts && pnpm test:dialects", + "test:pr": "VITEST_MAX_WORKERS=1 nx affected --targets=test:sherif,test:knip,test:docs,test:starters,test:kiira,test:oxlint,test:lib,test:starter,test:types,test:scripts,test:build,build --exclude=*-before && pnpm test:dts && pnpm test:dialects && pnpm test:definitions", + "test:ci": "VITEST_MAX_WORKERS=1 nx run-many --targets=test:sherif,test:knip,test:docs,test:starters,test:kiira,test:oxlint,test:lib,test:starter,test:types,test:scripts,test:build,build --exclude=*-before && pnpm test:dts && pnpm test:dialects && pnpm test:definitions", "test:oxlint": "nx affected --target=test:oxlint --exclude=examples/**", "test:sherif": "sherif --ignore-dependency typescript --ignore-package payload-before --ignore-package astro-starlight-before", "test:lib": "VITEST_MAX_WORKERS=1 nx affected --targets=test:lib --exclude=examples/**", @@ -30,7 +30,8 @@ "test:docs": "tsx scripts/verify-links.ts", "test:starters": "tsx scripts/verify-starters.ts", "test:dialects": "tsx scripts/dialect-inventory.ts --check", - "test:scripts": "vitest run scripts/codemods scripts/dialect-inventory.test.ts scripts/seo-snapshots", + "test:definitions": "tsx scripts/verify-definitions.ts", + "test:scripts": "vitest run scripts/codemods scripts/dialect-inventory.test.ts scripts/seo-snapshots scripts/verify-definitions.test.ts", "test:dts": "node scripts/scan-dangling-dts.mjs", "test:kiira": "kiira check", "build": "nx affected --skip-nx-cache --targets=build --exclude=examples/**", @@ -51,6 +52,7 @@ }, "nx": { "includedScripts": [ + "test:definitions", "test:dialects", "test:docs", "test:dts", diff --git a/packages/core/package.json b/packages/core/package.json index e4067ee3..73147548 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "name": "@tanstack/cms-core", "version": "0.1.0", - "description": "Framework-agnostic CMS engine for TanStack — schema-as-code, pluggable storage and media, drafts and review workflow, roles and access control, agent operations.", + "description": "Framework-agnostic CMS engine for TanStack \u2014 schema-as-code, pluggable storage and media, drafts and review workflow, roles and access control, agent operations.", "author": "Tanner Linsley", "license": "MIT", "homepage": "https://tanstack.com/cms", @@ -21,6 +21,7 @@ "sideEffects": false, "exports": { ".": "./src/index.ts", + "./definition": "./src/definition.ts", "./server": "./src/server.ts", "./flags": "./src/flags.ts", "./storage": "./src/storage.ts", @@ -43,6 +44,10 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./definition": { + "types": "./dist/definition.d.ts", + "import": "./dist/definition.js" + }, "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" @@ -84,7 +89,7 @@ "test:coverage:watch": "vitest --coverage --watch", "test:lib": "vitest run", "test:lib:dev": "pnpm test:lib --watch", - "test:types": "tsc --noEmit", + "test:types": "tsc --noEmit && tsc --noEmit -p tests/register-definition", "build": "tsdown", "test:build": "publint --strict --pack pnpm" }, diff --git a/packages/core/src/assets.ts b/packages/core/src/assets.ts index c587f33d..0111e3f3 100644 --- a/packages/core/src/assets.ts +++ b/packages/core/src/assets.ts @@ -19,6 +19,8 @@ import { import type { AssetMediaKind, Collection, Field } from './schema' import type { CmsAssetsConfig } from './config' +export { assetField } from './lib/authoring' + export { DEFAULT_ASSET_COLLECTION, assetCollectionName, @@ -130,29 +132,6 @@ export interface AssetFieldOptions { index?: boolean } -/** - * A strongly-typed `asset` field: a specialization of `relation` that targets - * the asset collection and stores the asset id (or ids for `many`). `kinds` - * narrows the picker to specific asset classes (e.g. `['image']`). The target - * collection is resolved from `defineCms({ assets: { collection } })`. - * - * ```ts - * fields: [assetField({ name: 'hero', label: 'Hero', kinds: ['image'] })] - * ``` - */ -export function assetField(options: AssetFieldOptions): Field { - return { - name: options.name, - label: options.label, - type: 'asset', - ...(options.many ? { many: true } : {}), - ...(options.required !== undefined ? { required: options.required } : {}), - ...(options.kinds ? { kinds: [...options.kinds] } : {}), - ...(options.description ? { description: options.description } : {}), - ...(options.index ? { index: options.index } : {}), - } -} - /** * Whether a field references the asset collection: an `asset` field, or a * plain `relation` already pointed at the asset collection. An `image` field diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 96b1218d..4a2fdbaa 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -14,6 +14,13 @@ * touches `getCmsConfig()`, so the config is always registered first. */ import { DEFAULT_ASSET_COLLECTION, buildAssetCollection } from './assets' +import { + DEFINITION_KEYS, + collectionsByName, + isCmsDefinition, + normalizeAdminBasePath, +} from './lib/definition' +import type { CmsDefinition, CmsDefinitionConfig } from './lib/definition' import type { BlockType, Collection, @@ -35,6 +42,8 @@ import type { } from './ops' import type { CmsEventsConfig, EventHandlerDefinition } from './events' +export { definePlugin } from './lib/authoring' + /** The seed store an app ships so a fresh install isn't empty. */ export interface SeedStore { documents: Record> @@ -383,13 +392,6 @@ export interface CmsPlugin< onEvent?: (event: CmsEvent) => void } -/** Type-safe identity helper for a plugin (`defineCms({ plugins })`). */ -export function definePlugin< - const TCollections extends ReadonlyArray = readonly [], ->(plugin: CmsPlugin): CmsPlugin { - return plugin -} - export interface CmsAdminConfig { /** * URL prefix the admin routes are mounted under (e.g. `/admin`). Must @@ -635,18 +637,20 @@ export interface CmsUploadsConfig { } /** - * Module augmentation target for end-to-end CMS types: + * Module augmentation target for end-to-end CMS types. `cms` may be the light + * definition (`defineCmsDefinition`), the `defineCms` result, or the config + * passed to it: * * ```ts * declare module '@tanstack/cms-core' { * interface Register { - * cms: typeof cms + * cms: typeof definition * } * } * ``` */ export interface Register { - // cms: typeof cms + // cms: typeof definition } /** @@ -666,13 +670,35 @@ export type CollectionsByName = } : C +/** + * A definition's config as the resolved config would type it: collections, + * plugin collections included, keyed by name. + */ +type ResolvedDefinitionConfig = Omit< + TConfig, + 'collections' +> & { + collections: CollectionsByName & + PluginCollections +} + +/** + * The registered CMS (`Register['cms']`) as a config, a definition read + * through its `config`, or `unknown` when nothing is registered. + */ +type RegisteredCms = Register extends { cms: infer T } + ? T extends CmsDefinition + ? ResolvedDefinitionConfig + : T + : unknown + /** * Collections of the registered CMS keyed by name, or a loose record when - * none is registered. `Register['cms']` may be the `defineCms` result or the - * config passed to it. + * none is registered. `Register['cms']` may be the definition, the + * `defineCms` result, or the config passed to it. */ -export type RegisteredCollections = Register extends { - cms: { collections: infer C } +export type RegisteredCollections = RegisteredCms extends { + collections: infer C } ? CollectionsByName : Record @@ -713,7 +739,7 @@ type OpsByName = * an empty map when none is registered. The app-ops analogue of * `RegisteredCollections`. */ -export type RegisteredOps = Register extends { cms: { ops: infer O } } +export type RegisteredOps = RegisteredCms extends { ops: infer O } ? OpsByName : Record @@ -816,38 +842,6 @@ function claim( taken.add(name) } -/** - * Key `list` by collection name, throwing on a repeated name. The `collections` - * array is the only place a collection's name is written, so this is where a - * clash surfaces. - */ -function collectionsByName( - list: unknown, - owner: string, -): Record { - if (!Array.isArray(list)) { - throw new TypeError( - `${owner}: \`collections\` must be an array of collections, e.g. ` + - '`collections: [post, author]`. The object form keyed by name was ' + - 'removed; the name comes from each `defineCollection({ name })`. ' + - 'To build a new config from a resolved one (`defineCms({ ...cms })`), ' + - 'pass `collections: Object.values(cms.collections)`.', - ) - } - const out: Record = {} - for (const collection of list as ReadonlyArray) { - const name = collection?.name - if (typeof name !== 'string' || !name) { - throw new TypeError(`${owner}: every collection needs a \`name\`.`) - } - if (Object.hasOwn(out, name)) { - throw new Error(`${owner}: collection "${name}" is defined twice.`) - } - out[name] = collection - } - return out -} - /** * Resolve a config: key its collections by name, add the built-in asset * collection, and merge `config.plugins` into the collections, block types, @@ -1023,15 +1017,28 @@ export interface Cms< } /** - * Create a CMS instance from a content-model config. Applies plugins and - * validates i18n (the same construction `defineCms` does) but does NOT touch - * global state. Use `instance.run(fn)` to scope ambient engine calls to this - * instance, or `instance.register()` to opt in as the ambient global. + * Create a CMS instance from a definition and the runtime config that extends + * it, or from a single config. Applies plugins and validates i18n (the same + * construction `defineCms` does) but does NOT touch global state. Use + * `instance.run(fn)` to scope ambient engine calls to this instance, or + * `instance.register()` to opt in as the ambient global. */ +export function createCms< + const TDefinition extends CmsDefinitionConfig, + const TRuntime extends CmsRuntimeConfig, +>( + definition: CmsDefinition, + runtime: TRuntime, +): Cms>> +/** Create a CMS instance from a single config. */ export function createCms( input: TConfig, -): Cms> { - const config = buildCmsConfig(input) +): Cms> +export function createCms( + input: CmsConfig | CmsDefinition, + runtime?: CmsRuntimeConfig, +): Cms { + const config = buildCmsConfig(extendDefinition(input, runtime, 'createCms')) return { config, run: (fn) => runWithCmsConfig(config, fn), @@ -1054,27 +1061,93 @@ export function defineCmsConfig( * Register the CMS content model. Call once, at app startup. A thin convenience * layer over `createCms(...).register()`: builds the instance (apply plugins, * validate i18n) and opts it in as the ambient global. + * + * Takes a light definition (`defineCmsDefinition`) and the runtime config + * that extends it. The runtime config holds everything the definition doesn't + * (`auth`, `storage`, `ai`, `ops`, `eventHandlers`, `seed`, …) and can't + * repeat `collections`, `admin`, or `plugins`. + */ +export function defineCms< + const TDefinition extends CmsDefinitionConfig, + const TRuntime extends CmsRuntimeConfig, +>( + definition: CmsDefinition, + runtime: TRuntime, +): WithPlugins> +/** + * Register the CMS from a single config. Fine when the config is already + * light; otherwise split it with `defineCmsDefinition`. */ export function defineCms( input: TConfig, -): WithPlugins { - return createCms(input).register() +): WithPlugins +export function defineCms( + input: CmsConfig | CmsDefinition, + runtime?: CmsRuntimeConfig, +): ResolvedCmsConfig { + return createCms(extendDefinition(input, runtime, 'defineCms')).register() +} + +type DefinitionKey = (typeof DEFINITION_KEYS)[number] + +/** + * The runtime part of a CMS config, passed next to a definition to + * `defineCms(definition, runtime)`: everything but the keys the definition + * owns (`collections`, `admin`, `plugins`). + */ +export type CmsRuntimeConfig = Omit & { + [K in DefinitionKey]?: never +} + +/** The full config `defineCms(definition, runtime)` builds from its two halves. */ +export type DefinedCmsConfig< + TDefinition extends CmsDefinitionConfig, + TRuntime extends CmsRuntimeConfig, +> = Extract, CmsConfig> + +/** The single config behind `defineCms(config)` or `defineCms(definition, runtime)`. */ +function extendDefinition( + input: CmsConfig | CmsDefinition, + runtime: CmsRuntimeConfig | undefined, + owner: string, +): CmsConfig { + if (!isCmsDefinition(input)) { + if (runtime !== undefined) { + throw new TypeError( + `${owner}(definition, runtime): the first argument must come from ` + + '`defineCmsDefinition` (`@tanstack/cms-core/definition`).', + ) + } + return input as CmsConfig + } + if (typeof runtime !== 'object' || runtime === null) { + throw new TypeError( + `${owner}(definition, runtime): pass the runtime config (\`auth\`, ` + + '`storage`, `blockTypes`, …) as the second argument.', + ) + } + for (const key of DEFINITION_KEYS) { + if ((runtime as Record)[key] !== undefined) { + throw new TypeError( + `${owner}(definition, runtime): \`${key}\` belongs to the ` + + 'definition; set it in `defineCmsDefinition`, not the runtime config.', + ) + } + } + return { ...runtime, ...input.config } as CmsConfig } /** Normalized admin base path: `''` or `/segment(s)` without a trailing slash. */ export function adminBasePath(): string { - const raw = getCmsConfig().admin?.basePath ?? '' - const trimmed = raw.trim().replace(/\/+$/, '') - if (!trimmed) return '' - return trimmed.startsWith('/') ? trimmed : `/${trimmed}` + return normalizeAdminBasePath(getCmsConfig().admin?.basePath) } /** * `admin.basePath` of the registered CMS (see `Register`), so typed router * links resolve to the prefixed routes. Write it as `/segment`. */ -export type RegisteredAdminBasePath = Register extends { - cms: { admin: { basePath: infer B extends string } } +export type RegisteredAdminBasePath = RegisteredCms extends { + admin: { basePath: infer B extends string } } ? B : '' diff --git a/packages/core/src/definition.ts b/packages/core/src/definition.ts new file mode 100644 index 00000000..433e3cde --- /dev/null +++ b/packages/core/src/definition.ts @@ -0,0 +1,77 @@ +/** + * `@tanstack/cms-core/definition`: the light CMS definition entry. + * + * Safe to import from `vite.config.ts`, the browser, and plain Node: it pulls + * in no React, no server code, and no Start. A `cms.definition.ts` and its + * collection modules need nothing else from `@tanstack/cms-core`: the pure + * authoring helpers and the types collections use are exported here too. + * + * Vite's config loader leaves workspace packages to Node, which runs this + * source with type stripping and no extension resolution. Runtime imports here + * and in the modules they load must name the `.ts` file; type imports are erased. + */ +export { + CMS_ROUTE_KEYS, + defineCmsDefinition, + isCmsDefinition, +} from './lib/definition.ts' +export type { + CmsDefinition, + CmsDefinitionCollection, + CmsDefinitionConfig, + CmsPluginRoute, + CmsRouteKey, + CmsRouteSurface, +} from './lib/definition.ts' +export { + assetField, + defineBlock, + defineCollection, + defineFieldType, + definePlugin, + isBuiltInFieldType, + isSafeRedirectTarget, + redirectsCollection, + seoField, +} from './lib/authoring.ts' +export type { + AssetMediaKind, + Block, + BlockType, + BuiltInFieldType, + ChangeHookArgs, + Collection, + CollectionAdmin, + CollectionHooks, + ContentMigration, + CustomFieldTypes, + DefineCollectionInput, + Doc, + Field, + FieldCellProps, + FieldCondition, + FieldFacet, + FieldInputProps, + FieldOption, + FieldType, + FieldTypeDefinition, + FieldValidator, + FieldValidatorFn, + InferBlock, + InferDoc, + InferDocFromFields, + InferFieldValue, + JsonValue, + StandardSchemaV1, + SystemMetadata, +} from './schema.ts' +export type { AssetFieldOptions } from './assets.ts' +export type { + AccessRule, + AccessRuleContext, + CollectionAccess, + CollectionAction, + FieldAccess, + Permission, +} from './lib/access.ts' +export type { CmsAdminConfig, CmsAdminNavItem, CmsPlugin } from './config.ts' diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2b099d3e..cb074103 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -51,6 +51,8 @@ export type { CmsAdminNavItem, WithPlugins, ResolvedCmsConfig, + CmsRuntimeConfig, + DefinedCmsConfig, CollectionsByName, CmsRateLimit, RateLimitStore, diff --git a/packages/core/src/lib/authoring.ts b/packages/core/src/lib/authoring.ts new file mode 100644 index 00000000..e7b424ca --- /dev/null +++ b/packages/core/src/lib/authoring.ts @@ -0,0 +1,234 @@ +/** + * The pure authoring helpers for collections, blocks, fields, and plugins: + * identity functions and plain-data builders. + * + * No runtime imports, on purpose: `@tanstack/cms-core/definition` re-exports + * these, and Node loads that entry with type stripping alone when Vite reads + * a `cms.definition.ts` (see `src/definition.ts`). The root entry re-exports + * the same functions. + */ +import type { + BlockType, + BuiltInFieldType, + Collection, + DefineCollectionInput, + Field, + FieldTypeDefinition, +} from '../schema' +import type { AssetFieldOptions } from '../assets' +import type { CmsPlugin } from '../config' + +/** Type-safe identity helper for a custom field type. */ +export function defineFieldType( + definition: FieldTypeDefinition, +): FieldTypeDefinition { + if (BUILT_IN_FIELD_TYPES.has(definition.name)) { + throw new Error( + `defineFieldType: "${definition.name}" is a built-in field type.`, + ) + } + return definition +} + +const BUILT_IN_FIELD_TYPES: ReadonlySet = new Set([ + 'text', + 'textarea', + 'markdown', + 'number', + 'boolean', + 'image', + 'asset', + 'blocks', + 'select', + 'multiselect', + 'relation', + 'date', + 'datetime', + 'json', + 'slug', + 'email', + 'url', + 'color', + 'richtext', + 'group', + 'array', +]) + +/** Whether `type` is one of the field types the engine ships with. */ +export function isBuiltInFieldType(type: string): type is BuiltInFieldType { + return BUILT_IN_FIELD_TYPES.has(type) +} + +/** + * Type-safe identity helper for defining a collection with literal field names, + * types, and options preserved for `InferDoc`. + * + * Inside the argument, the `hooks` and `path` callbacks see the document type + * inferred from the collection's `fields` (so e.g. a `preValidate` hook's + * `args.doc` and a `path(doc, id)` callback's `doc` carry the declared fields), + * rather than the loose `Doc`. The returned value preserves the collection's + * literal types, so `InferDoc` (and the literal + * `titleField`, field names, …) continue to work unchanged. The returned type's + * `hooks`/`path` are widened back to the loose `Collection` default so the + * value stays assignable to a bare `Collection` everywhere (the `collections` + * registry, `schemaFor`, the server store, …). + * + * Two type parameters are used so inference flows in the right order: `TFields` + * is inferred first from the `fields` member and used to contextually type the + * `hooks`/`path` callbacks; `TCollection` then captures the full collection + * literal for the return type. Both are `const` so field literals survive. + */ +export function defineCollection< + const TFields extends Array, + const TCollection extends DefineCollectionInput, +>( + collection: TCollection & DefineCollectionInput, +): Omit & Pick { + // Identity at runtime; the cast only widens the `hooks`/`path` callbacks back + // to the loose `Collection` default (the inferred-doc types in the argument + // don't structurally overlap the widened result). + // oxlint-disable-next-line eslint-js/no-restricted-syntax -- intentional widening of the declared doc-typed callbacks back to the loose Collection default + return collection as unknown as Omit & + Pick +} + +/** + * Type-safe identity helper for defining a block type with literal `_type`, + * field names, and options preserved for `InferBlock`. + */ +export function defineBlock( + block: TBlock, +): TBlock { + return block +} + +/** + * A `seo` group field for collections: per-document title, description, + * social image, canonical URL, and `noindex` overrides. `cmsHead` and the + * sitemap read it when present. + */ +export function seoField(): Field { + return { + name: 'seo', + label: 'SEO', + type: 'group', + fields: [ + { + name: 'title', + label: 'Meta title', + type: 'text', + required: false, + max: 70, + }, + { + name: 'description', + label: 'Meta description', + type: 'textarea', + required: false, + max: 160, + }, + { name: 'image', label: 'Social image', type: 'image', required: false }, + { + name: 'canonical', + label: 'Canonical URL', + type: 'url', + required: false, + }, + { + name: 'noindex', + label: 'Hide from search engines', + type: 'boolean', + required: false, + }, + ], + } +} + +/** + * A redirect target the site will send: a same-site path (`/docs`, not the + * protocol-relative `//host`) or an absolute `http:` / `https:` URL. + */ +export function isSafeRedirectTarget(to: unknown): to is string { + if (typeof to !== 'string') return false + const t = to.trim() + if (t.startsWith('/')) return !/^\/[/\\]/.test(t) + try { + const { protocol } = new URL(t) + return protocol === 'https:' || protocol === 'http:' + } catch { + return false + } +} + +/** + * A collection of redirects (`from` path → `to` path or URL). Add it to + * `defineCms({ collections })`; the public catch-all route and + * `handleRedirect` consult it for unmatched paths. + */ +export function redirectsCollection(name = 'redirect'): Collection { + return { + name, + label: 'Redirects', + titleField: 'from', + fields: [ + { + name: 'from', + label: 'From path', + type: 'text', + required: true, + unique: true, + index: true, + validate: (v) => + typeof v === 'string' && v.startsWith('/') + ? undefined + : 'Must be a path starting with /', + }, + { + name: 'to', + label: 'To (path or URL)', + type: 'text', + required: true, + validate: (v) => + isSafeRedirectTarget(v) + ? undefined + : 'Must be a path starting with / or an http(s) URL', + }, + { + name: 'permanent', + label: 'Permanent (301)', + type: 'boolean', + defaultValue: true, + }, + ], + } +} + +/** + * A strongly-typed `asset` field: a specialization of `relation` that targets + * the asset collection and stores the asset id (or ids for `many`). `kinds` + * narrows the picker to specific asset classes (e.g. `['image']`). The target + * collection is resolved from `defineCms({ assets: { collection } })`. + * + * ```ts + * fields: [assetField({ name: 'hero', label: 'Hero', kinds: ['image'] })] + * ``` + */ +export function assetField(options: AssetFieldOptions): Field { + return { + name: options.name, + label: options.label, + type: 'asset', + ...(options.many ? { many: true } : {}), + ...(options.required !== undefined ? { required: options.required } : {}), + ...(options.kinds ? { kinds: [...options.kinds] } : {}), + ...(options.description ? { description: options.description } : {}), + ...(options.index ? { index: options.index } : {}), + } +} + +/** Type-safe identity helper for a plugin (`defineCms({ plugins })`). */ +export function definePlugin< + const TCollections extends ReadonlyArray = readonly [], +>(plugin: CmsPlugin): CmsPlugin { + return plugin +} diff --git a/packages/core/src/lib/definition.ts b/packages/core/src/lib/definition.ts new file mode 100644 index 00000000..502338be --- /dev/null +++ b/packages/core/src/lib/definition.ts @@ -0,0 +1,210 @@ +/** + * The light CMS definition: the part of an app's CMS that routing and build + * tooling need, and nothing else. + * + * `defineCmsDefinition({ collections, admin, plugins })` lives in its own + * `cms.definition.ts`, so `vite.config.ts` (and `createRoutes`) can import it + * without loading auth, storage, AI, ops, or event handlers. The full config + * extends it with `defineCms(definition, runtime)`. + * + * Client- and Node-safe with no dependencies: this module imports types + * only. `scripts/verify-definitions.ts` loads every `cms.definition.ts` in a + * plain Node process and fails on React, Start, the UI package root, `.tsx`, + * and `*.server.*` imports, so keep it that way. The public surface is + * re-exported from `@tanstack/cms-core/definition` (`src/definition.ts`). + */ +import type { Collection } from '../schema' +import type { CmsAdminConfig, CmsPlugin } from '../config' + +/** + * Every route the CMS UI can mount, by stable key and surface. The one source + * of the route keys: `@tanstack/cms-ui-react/virtual-routes` maps each key to + * its file and path, and its route table must cover exactly these keys. + */ +export const CMS_ROUTE_KEYS = { + public: ['index', 'page', 'post', 'preview', 'sitemap', 'robots', 'notFound'], + admin: ['content', 'edit', 'agent', 'review', 'settings'], + api: ['apiWebMcp', 'apiV1', 'apiMcp', 'apiMedia', 'apiMediaFile'], +} as const + +/** A group of CMS routes mounted together: `public`, `admin`, or `api`. */ +export type CmsRouteSurface = keyof typeof CMS_ROUTE_KEYS + +/** A CMS route, by stable key (`content`, `edit`, `review`, …). */ +export type CmsRouteKey = (typeof CMS_ROUTE_KEYS)[CmsRouteSurface][number] + +/** + * The definition part of a CMS config: the content model and what routing + * needs. Everything else (`auth`, `storage`, `ai`, `ops`, `eventHandlers`, + * `seed`, …) goes in the runtime config passed to `defineCms(definition, + * runtime)`. + */ +export interface CmsDefinitionConfig { + /** Content collections (`[post, author]`); each `name` must be unique. */ + collections: ReadonlyArray + /** Admin mount point and translations. */ + admin?: CmsAdminConfig + /** Plugins; their collections and routes are part of the definition. */ + plugins?: ReadonlyArray +} + +/** The keys a definition owns; a runtime config passed next to it can't repeat them. */ +export const DEFINITION_KEYS = ['collections', 'admin', 'plugins'] as const + +/** A collection as routing sees it. */ +export interface CmsDefinitionCollection { + name: string +} + +/** A route node a plugin contributes, tagged with the plugin's name. */ +export interface CmsPluginRoute { + plugin: string + /** A `route()` / `physical()` node from `@tanstack/virtual-file-routes`. */ + route: object +} + +/** + * A light CMS definition (see `defineCmsDefinition`). Its accessors are + * derived from `config` and return the same frozen values on every call. + */ +export interface CmsDefinition< + TConfig extends CmsDefinitionConfig = CmsDefinitionConfig, +> { + /** The definition config as written. */ + readonly config: TConfig + /** The normalized `admin.basePath`: `''` or `/segment(s)` without a trailing slash. */ + adminBasePath: () => string + /** The app's and its plugins' collections, in declaration order. */ + collections: () => ReadonlyArray + /** Plugin route nodes: `routes` keep their paths; `adminRoutes` mount under the admin base path. */ + pluginRoutes: () => { + routes: ReadonlyArray + adminRoutes: ReadonlyArray + } + /** Every CMS route key, public then admin then API. */ + routeKeys: () => ReadonlyArray +} + +const definitions = new WeakSet() + +/** Whether `value` was built by `defineCmsDefinition`. */ +export function isCmsDefinition(value: unknown): value is CmsDefinition { + return typeof value === 'object' && value !== null && definitions.has(value) +} + +/** Normalize an admin base path to `''` or `/segment(s)` without a trailing slash. */ +export function normalizeAdminBasePath(raw: string | undefined): string { + const trimmed = (raw ?? '').trim().replace(/\/+$/, '') + if (!trimmed) return '' + return trimmed.startsWith('/') ? trimmed : `/${trimmed}` +} + +/** + * Key `list` by collection name, throwing on a repeated name. The `collections` + * array is the only place a collection's name is written, so this is where a + * clash surfaces. + */ +export function collectionsByName( + list: unknown, + owner: string, +): Record { + if (!Array.isArray(list)) { + throw new TypeError( + `${owner}: \`collections\` must be an array of collections, e.g. ` + + '`collections: [post, author]`. The object form keyed by name was ' + + 'removed; the name comes from each `defineCollection({ name })`. ' + + 'To build a new config from a resolved one (`defineCms({ ...cms })`), ' + + 'pass `collections: Object.values(cms.collections)`.', + ) + } + const out: Record = {} + for (const collection of list as ReadonlyArray) { + const name = collection?.name + if (typeof name !== 'string' || !name) { + throw new TypeError(`${owner}: every collection needs a \`name\`.`) + } + if (Object.hasOwn(out, name)) { + throw new Error(`${owner}: collection "${name}" is defined twice.`) + } + out[name] = collection + } + return out +} + +/** + * Define the light part of a CMS: collections, the admin mount point, and + * plugins. Import it from `vite.config.ts` and extend it into the full config + * with `defineCms(definition, runtime)`. + * + * Throws on the same collection and plugin name clashes `defineCms` does. + * + * ```ts + * // src/cms.definition.ts + * import { defineCmsDefinition } from '@tanstack/cms-core/definition' + * import { post, author } from './collections' + * + * export const definition = defineCmsDefinition({ + * collections: [post, author], + * admin: { basePath: '/admin' }, + * }) + * ``` + */ +export function defineCmsDefinition( + config: TConfig, +): CmsDefinition { + const collections = collectionsByName( + config.collections, + 'defineCmsDefinition', + ) + const plugins = new Set() + const routes: Array = [] + const adminRoutes: Array = [] + for (const plugin of config.plugins ?? []) { + if (plugins.has(plugin.name)) { + throw new Error(`Plugin "${plugin.name}" is registered twice.`) + } + plugins.add(plugin.name) + const own = collectionsByName( + plugin.collections ?? [], + `Plugin "${plugin.name}"`, + ) + for (const [name, collection] of Object.entries(own)) { + if (Object.hasOwn(collections, name)) { + throw new Error( + `Plugin "${plugin.name}": collection "${name}" is already defined.`, + ) + } + collections[name] = collection + } + for (const route of plugin.routes ?? []) { + routes.push(Object.freeze({ plugin: plugin.name, route })) + } + for (const route of plugin.adminRoutes ?? []) { + adminRoutes.push(Object.freeze({ plugin: plugin.name, route })) + } + } + + const basePath = normalizeAdminBasePath(config.admin?.basePath) + const collectionList = Object.freeze( + Object.keys(collections).map((name) => Object.freeze({ name })), + ) + const pluginRouteNodes = Object.freeze({ + routes: Object.freeze(routes), + adminRoutes: Object.freeze(adminRoutes), + }) + const routeKeys: ReadonlyArray = Object.freeze([ + ...CMS_ROUTE_KEYS.public, + ...CMS_ROUTE_KEYS.admin, + ...CMS_ROUTE_KEYS.api, + ]) + + const definition: CmsDefinition = Object.freeze({ + config, + adminBasePath: () => basePath, + collections: () => collectionList, + pluginRoutes: () => pluginRouteNodes, + routeKeys: () => routeKeys, + }) + definitions.add(definition) + return definition +} diff --git a/packages/core/src/lib/seo.ts b/packages/core/src/lib/seo.ts index c4e44bf2..63d00bf8 100644 --- a/packages/core/src/lib/seo.ts +++ b/packages/core/src/lib/seo.ts @@ -16,108 +16,13 @@ import { isArticleSchemaType, } from '../schema' import { getTheme } from './theme' -import type { Collection, Doc, Field } from '../schema' +import type { Collection, Doc } from '../schema' -/** - * A `seo` group field for collections: per-document title, description, - * social image, canonical URL, and `noindex` overrides. `cmsHead` and the - * sitemap read it when present. - */ -export function seoField(): Field { - return { - name: 'seo', - label: 'SEO', - type: 'group', - fields: [ - { - name: 'title', - label: 'Meta title', - type: 'text', - required: false, - max: 70, - }, - { - name: 'description', - label: 'Meta description', - type: 'textarea', - required: false, - max: 160, - }, - { name: 'image', label: 'Social image', type: 'image', required: false }, - { - name: 'canonical', - label: 'Canonical URL', - type: 'url', - required: false, - }, - { - name: 'noindex', - label: 'Hide from search engines', - type: 'boolean', - required: false, - }, - ], - } -} - -/** - * A redirect target the site will send: a same-site path (`/docs`, not the - * protocol-relative `//host`) or an absolute `http:` / `https:` URL. - */ -export function isSafeRedirectTarget(to: unknown): to is string { - if (typeof to !== 'string') return false - const t = to.trim() - if (t.startsWith('/')) return !/^\/[/\\]/.test(t) - try { - const { protocol } = new URL(t) - return protocol === 'https:' || protocol === 'http:' - } catch { - return false - } -} - -/** - * A collection of redirects (`from` path → `to` path or URL). Add it to - * `defineCms({ collections })`; the public catch-all route and - * `handleRedirect` consult it for unmatched paths. - */ -export function redirectsCollection(name = 'redirect'): Collection { - return { - name, - label: 'Redirects', - titleField: 'from', - fields: [ - { - name: 'from', - label: 'From path', - type: 'text', - required: true, - unique: true, - index: true, - validate: (v) => - typeof v === 'string' && v.startsWith('/') - ? undefined - : 'Must be a path starting with /', - }, - { - name: 'to', - label: 'To (path or URL)', - type: 'text', - required: true, - validate: (v) => - isSafeRedirectTarget(v) - ? undefined - : 'Must be a path starting with / or an http(s) URL', - }, - { - name: 'permanent', - label: 'Permanent (301)', - type: 'boolean', - defaultValue: true, - }, - ], - } -} +export { + isSafeRedirectTarget, + redirectsCollection, + seoField, +} from './authoring' /** Values of a document's `seo` group, if it has one. */ export interface SeoOverrides { diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index 5933cac6..3c6339fe 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -19,6 +19,14 @@ import { z } from 'zod' import { contentLocales, getCmsConfig } from './config' import type { CollectionAccess, FieldAccess } from './lib/access' import type { StorageAdapter } from './storage/types' +import { isBuiltInFieldType } from './lib/authoring' + +export { + defineBlock, + defineCollection, + defineFieldType, + isBuiltInFieldType, +} from './lib/authoring' /** The field types the engine and admin ship with. */ export type BuiltInFieldType = @@ -102,47 +110,6 @@ export interface FieldTypeDefinition { cell?: (props: FieldCellProps) => unknown } -/** Type-safe identity helper for a custom field type. */ -export function defineFieldType( - definition: FieldTypeDefinition, -): FieldTypeDefinition { - if (BUILT_IN_FIELD_TYPES.has(definition.name)) { - throw new Error( - `defineFieldType: "${definition.name}" is a built-in field type.`, - ) - } - return definition -} - -const BUILT_IN_FIELD_TYPES: ReadonlySet = new Set([ - 'text', - 'textarea', - 'markdown', - 'number', - 'boolean', - 'image', - 'asset', - 'blocks', - 'select', - 'multiselect', - 'relation', - 'date', - 'datetime', - 'json', - 'slug', - 'email', - 'url', - 'color', - 'richtext', - 'group', - 'array', -]) - -/** Whether `type` is one of the field types the engine ships with. */ -export function isBuiltInFieldType(type: string): type is BuiltInFieldType { - return BUILT_IN_FIELD_TYPES.has(type) -} - /** Custom field types registered on the CMS, keyed by name. */ export function fieldTypeDefinitions(): Record { let defs: ReadonlyArray = [] @@ -632,49 +599,6 @@ export type DefineCollectionInput = Omit< 'fields' > & { fields: TFields } -/** - * Type-safe identity helper for defining a collection with literal field names, - * types, and options preserved for `InferDoc`. - * - * Inside the argument, the `hooks` and `path` callbacks see the document type - * inferred from the collection's `fields` (so e.g. a `preValidate` hook's - * `args.doc` and a `path(doc, id)` callback's `doc` carry the declared fields), - * rather than the loose `Doc`. The returned value preserves the collection's - * literal types, so `InferDoc` (and the literal - * `titleField`, field names, …) continue to work unchanged. The returned type's - * `hooks`/`path` are widened back to the loose `Collection` default so the - * value stays assignable to a bare `Collection` everywhere (the `collections` - * registry, `schemaFor`, the server store, …). - * - * Two type parameters are used so inference flows in the right order: `TFields` - * is inferred first from the `fields` member and used to contextually type the - * `hooks`/`path` callbacks; `TCollection` then captures the full collection - * literal for the return type. Both are `const` so field literals survive. - */ -export function defineCollection< - const TFields extends Array, - const TCollection extends DefineCollectionInput, ->( - collection: TCollection & DefineCollectionInput, -): Omit & Pick { - // Identity at runtime; the cast only widens the `hooks`/`path` callbacks back - // to the loose `Collection` default (the inferred-doc types in the argument - // don't structurally overlap the widened result). - // oxlint-disable-next-line eslint-js/no-restricted-syntax -- intentional widening of the declared doc-typed callbacks back to the loose Collection default - return collection as unknown as Omit & - Pick -} - -/** - * Type-safe identity helper for defining a block type with literal `_type`, - * field names, and options preserved for `InferBlock`. - */ -export function defineBlock( - block: TBlock, -): TBlock { - return block -} - /** Return the block-array field name for a collection, if one exists. */ export function getBlocksField(collection: Collection): string | undefined { return ( diff --git a/packages/core/tests/definition.test.ts b/packages/core/tests/definition.test.ts new file mode 100644 index 00000000..3b19283b --- /dev/null +++ b/packages/core/tests/definition.test.ts @@ -0,0 +1,299 @@ +import { spawnSync } from 'node:child_process' +import { describe, expect, expectTypeOf, it } from 'vitest' +import { z } from 'zod' +import { + createCms, + defineCms, + defineCollection, + defineOp, + definePlugin, + getCmsConfig, +} from '../src/index' +import { + CMS_ROUTE_KEYS, + defineCmsDefinition, + isCmsDefinition, +} from '../src/definition' +import type { CmsConfig, CmsRuntimeConfig } from '../src/index' +import type { CmsRouteKey } from '../src/definition' +import * as rootEntry from '../src/index' +import * as definitionEntry from '../src/definition' + +const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'views', label: 'Views', type: 'number' }, + ], +}) + +const author = defineCollection({ + name: 'author', + label: 'Authors', + titleField: 'name', + fields: [{ name: 'name', label: 'Name', type: 'text' }], +}) + +const pageview = defineCollection({ + name: 'pageview', + label: 'Page views', + titleField: 'path', + fields: [{ name: 'path', label: 'Path', type: 'text' }], +}) + +const expectedRouteKeyCount = Object.values(CMS_ROUTE_KEYS).flat().length + +const statsRoute = { type: 'route', path: '/stats', file: 'stats.tsx' } +const dashboardRoute = { + type: 'route', + path: '/analytics', + file: 'analytics.tsx', +} + +const analytics = definePlugin({ + name: 'analytics', + collections: [pageview], + routes: [statsRoute], + adminRoutes: [dashboardRoute], +}) + +describe('defineCmsDefinition', () => { + it('derives the accessors from the config', () => { + const definition = defineCmsDefinition({ + collections: [post, author], + admin: { basePath: 'admin/' }, + plugins: [analytics], + }) + expect(isCmsDefinition(definition)).toBe(true) + expect(definition.adminBasePath()).toBe('/admin') + expect(definition.collections()).toEqual([ + { name: 'post' }, + { name: 'author' }, + { name: 'pageview' }, + ]) + expect(definition.pluginRoutes()).toEqual({ + routes: [{ plugin: 'analytics', route: statsRoute }], + adminRoutes: [{ plugin: 'analytics', route: dashboardRoute }], + }) + expect(definition.routeKeys()).toEqual([ + ...CMS_ROUTE_KEYS.public, + ...CMS_ROUTE_KEYS.admin, + ...CMS_ROUTE_KEYS.api, + ]) + expect(definition.routeKeys()).toContain('review') + }) + + it('returns stable, frozen values', () => { + const definition = defineCmsDefinition({ collections: [post] }) + expect(definition.adminBasePath()).toBe('') + expect(definition.collections()).toBe(definition.collections()) + expect(Object.isFrozen(definition.collections())).toBe(true) + expect(Object.isFrozen(definition.routeKeys())).toBe(true) + expect(definition.pluginRoutes()).toEqual({ routes: [], adminRoutes: [] }) + }) + + it('throws on the same name clashes as defineCms', () => { + expect(() => + defineCmsDefinition({ collections: [post, { ...author, name: 'post' }] }), + ).toThrow('defineCmsDefinition: collection "post" is defined twice.') + expect(() => + defineCmsDefinition({ + collections: [post], + plugins: [definePlugin({ name: 'clash', collections: [post] })], + }), + ).toThrow('Plugin "clash": collection "post" is already defined.') + expect(() => + defineCmsDefinition({ + collections: [], + plugins: [analytics, analytics], + }), + ).toThrow('Plugin "analytics" is registered twice.') + }) + + it('is not a definition unless built by defineCmsDefinition', () => { + expect(isCmsDefinition({ collections: [post] })).toBe(false) + expect(isCmsDefinition(null)).toBe(false) + }) +}) + +describe('the definition entry source', { timeout: 30_000 }, () => { + it('loads in Node with type stripping alone, as Vite config loading does', () => { + const entry = new URL('../src/definition.ts', import.meta.url).href + const child = spawnSync( + process.execPath, + [ + '--experimental-strip-types', + '--no-warnings', + '--input-type=module', + '-e', + `const m = await import(${JSON.stringify(entry)}) + const page = m.defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + m.seoField(), + m.assetField({ name: 'hero', label: 'Hero', kinds: ['image'] }), + ], + }) + const d = m.defineCmsDefinition({ + collections: [page, m.redirectsCollection()], + admin: { basePath: '/cms' }, + plugins: [m.definePlugin({ name: 'p' })], + }) + process.stdout.write([d.adminBasePath(), d.routeKeys().length, d.collections().map((c) => c.name).join()].join(' '))`, + ], + { encoding: 'utf8' }, + ) + expect(child.stderr).toBe('') + expect(child.stdout.trim()).toBe( + `/cms ${expectedRouteKeyCount} page,redirect`, + ) + }) + + it('exports the same authoring helpers as the root', () => { + for (const name of [ + 'assetField', + 'defineBlock', + 'defineCollection', + 'defineFieldType', + 'definePlugin', + 'isBuiltInFieldType', + 'isSafeRedirectTarget', + 'redirectsCollection', + 'seoField', + ] as const) { + expect(definitionEntry[name], name).toBeTypeOf('function') + expect(definitionEntry[name], name).toBe(rootEntry[name]) + } + }) +}) + +describe('defineCms(definition, runtime)', () => { + it('resolves the same config as the single-argument form', () => { + const single = defineCms({ + collections: [post, author], + blockTypes: [], + admin: { basePath: '/admin' }, + plugins: [analytics], + dataDir: '/tmp/single', + }) + const definition = defineCmsDefinition({ + collections: [post, author], + admin: { basePath: '/admin' }, + plugins: [analytics], + }) + const split = defineCms(definition, { + blockTypes: [], + dataDir: '/tmp/single', + }) + expect(split).toEqual(single) + expect(Object.keys(split.collections)).toEqual([ + 'post', + 'author', + 'asset', + 'pageview', + ]) + expect(getCmsConfig()).toBe(split) + }) + + it('applies plugins and validates names the same way', () => { + const op = defineOp({ + name: 'ping', + access: 'public', + description: 'Ping.', + input: z.object({}), + run: async () => 'pong', + }) + const withOp = definePlugin({ name: 'ops', ops: [op] }) + const definition = defineCmsDefinition({ + collections: [post], + plugins: [withOp], + }) + defineCms(definition, { blockTypes: [] }) + expect(getCmsConfig().ops?.map((o) => o.name)).toEqual(['ping']) + expect(() => defineCms(definition, { blockTypes: [], ops: [op] })).toThrow( + 'Plugin "ops": op "ping" is already defined.', + ) + }) + + it('validates i18n like the single-argument form', () => { + const definition = defineCmsDefinition({ collections: [post] }) + expect(() => + defineCms(definition, { + blockTypes: [], + i18n: { locales: [{ code: 'en' }], defaultLocale: 'fr' }, + }), + ).toThrow(/i18n.defaultLocale "fr" is not one of i18n.locales/) + }) + + it('rejects a runtime config that repeats a definition key', () => { + const definition = defineCmsDefinition({ collections: [post] }) + expect(() => + // @ts-expect-error `collections` belongs to the definition + defineCms(definition, { blockTypes: [], collections: [author] }), + ).toThrow(/`collections` belongs to the definition/) + expect(() => + // @ts-expect-error `admin` belongs to the definition + defineCms(definition, { blockTypes: [], admin: { basePath: '/x' } }), + ).toThrow(/`admin` belongs to the definition/) + }) + + it('rejects a definition without a runtime config, and a runtime without a definition', () => { + const definition = defineCmsDefinition({ collections: [post] }) + // @ts-expect-error the runtime config is required next to a definition + expect(() => defineCms(definition)).toThrow(/pass the runtime config/) + expect(() => + // @ts-expect-error a plain config takes no second argument + defineCms({ collections: [post], blockTypes: [] }, { blockTypes: [] }), + ).toThrow(/must come from `defineCmsDefinition`/) + }) + + it('builds an instance without registering it', () => { + const before = defineCms({ collections: [author], blockTypes: [] }) + const definition = defineCmsDefinition({ collections: [post] }) + const instance = createCms(definition, { blockTypes: [] }) + expect(Object.keys(instance.config.collections)).toEqual(['post', 'asset']) + expect(getCmsConfig()).toBe(before) + }) +}) + +describe('definition types', () => { + it('keeps the config literal and types the split result by name', () => { + expectTypeOf(() => { + const definition = defineCmsDefinition({ + collections: [post, author], + admin: { basePath: '/admin' }, + plugins: [analytics], + }) + expectTypeOf(definition.config.admin.basePath).toEqualTypeOf<'/admin'>() + const cms = defineCms(definition, { blockTypes: [], dataDir: '.data' }) + expectTypeOf(cms.collections.post).toEqualTypeOf() + expectTypeOf(cms.collections.pageview).toEqualTypeOf() + expectTypeOf(cms.dataDir).toEqualTypeOf<'.data'>() + // @ts-expect-error not a collection of this config + void cms.collections.nope + }).toBeFunction() + }) + + it('derives the route key union from CMS_ROUTE_KEYS', () => { + expectTypeOf<'review'>().toExtend() + expectTypeOf<'apiV1'>().toExtend() + expectTypeOf<'nope'>().not.toExtend() + }) + + it('keeps the single-config overload last, so Parameters<> still sees it', () => { + expectTypeOf[0]>().toEqualTypeOf() + expectTypeOf[0]>().toEqualTypeOf() + }) + + it('keeps definition keys out of the runtime config', () => { + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf< + CmsConfig['blockTypes'] + >() + }) +}) diff --git a/packages/core/tests/register-definition/register.ts b/packages/core/tests/register-definition/register.ts new file mode 100644 index 00000000..12ca03a0 --- /dev/null +++ b/packages/core/tests/register-definition/register.ts @@ -0,0 +1,58 @@ +/** + * `Register` augmented with a light definition. Type-checked on its own + * (`tsc -p tests/register-definition`), since the augmentation is global to a + * program and the other core tests run unregistered. + */ +import { expectTypeOf } from 'vitest' +import { adminPath, defineCollection, definePlugin } from '../../src/index' +import { defineCmsDefinition } from '../../src/definition' +import type { + RegisteredAdminBasePath, + RegisteredCollectionName, + RegisteredCollections, + RegisteredDoc, + RegisteredOpName, +} from '../../src/index' + +const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'views', label: 'Views', type: 'number' }, + ], +}) + +const analytics = definePlugin({ + name: 'analytics', + collections: [ + defineCollection({ + name: 'pageview', + label: 'Page views', + titleField: 'path', + fields: [{ name: 'path', label: 'Path', type: 'text' }], + }), + ], +}) + +export const definition = defineCmsDefinition({ + collections: [post], + admin: { basePath: '/admin' }, + plugins: [analytics], +}) + +declare module '../../src/index' { + interface Register { + cms: typeof definition + } +} + +expectTypeOf().toEqualTypeOf<'post' | 'pageview'>() +expectTypeOf().toEqualTypeOf() +expectTypeOf['title']>().toEqualTypeOf() +expectTypeOf['views']>().toEqualTypeOf() +expectTypeOf['path']>().toEqualTypeOf() +expectTypeOf().toEqualTypeOf<'/admin'>() +expectTypeOf(adminPath('/content')).toEqualTypeOf<'/admin/content'>() +expectTypeOf().toEqualTypeOf() diff --git a/packages/core/tests/register-definition/tsconfig.json b/packages/core/tests/register-definition/tsconfig.json new file mode 100644 index 00000000..4aea3b83 --- /dev/null +++ b/packages/core/tests/register-definition/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../../../tsconfig.base.json", + "include": ["./*.ts"] +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index 9a656fb5..79710890 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -11,5 +11,5 @@ // the route tree generated in the *consuming* app (e.g. examples/blog). In // isolation that augmentation is absent, so routes are type-checked by each // example app, not here. - "exclude": ["src/routes"] + "exclude": ["src/routes", "tests/register-definition"] } diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.ts index ab7f169a..84d72217 100644 --- a/packages/core/tsdown.config.ts +++ b/packages/core/tsdown.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'tsdown' export default defineConfig({ entry: [ 'src/index.ts', + 'src/definition.ts', 'src/server.ts', 'src/flags.ts', 'src/storage.ts', diff --git a/packages/ui-react/src/virtual-routes.ts b/packages/ui-react/src/virtual-routes.ts index a6ca5d18..7f925e2b 100644 --- a/packages/ui-react/src/virtual-routes.ts +++ b/packages/ui-react/src/virtual-routes.ts @@ -3,89 +3,50 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import os from 'node:os' import { fileURLToPath } from 'node:url' import path from 'node:path' +import { CMS_ROUTE_KEYS } from '@tanstack/cms-core/definition' +import type { + CmsRouteKey, + CmsRouteSurface, +} from '@tanstack/cms-core/definition' import { rootRoute, index, route } from '@tanstack/virtual-file-routes' import type { VirtualRouteNode, VirtualRootRoute, } from '@tanstack/virtual-file-routes' -/** Every route the CMS UI can mount, by stable key. */ -export type CmsRouteKey = - | 'index' - | 'page' - | 'post' - | 'preview' - | 'sitemap' - | 'robots' - | 'notFound' - | 'content' - | 'edit' - | 'agent' - | 'review' - | 'settings' - | 'apiWebMcp' - | 'apiV1' - | 'apiMcp' - | 'apiMedia' - | 'apiMediaFile' - -type RouteGroup = 'public' | 'admin' | 'api' +/** Every route the CMS UI can mount, by stable key (defined in `@tanstack/cms-core/definition`). */ +export type { CmsRouteKey } -const ROUTES: ReadonlyArray<{ - key: CmsRouteKey - group: RouteGroup - /** URL path; `null` for the index route. Admin paths get `adminBasePath`. */ - path: string | null - file: string -}> = [ - { key: 'index', group: 'public', path: null, file: 'index.tsx' }, - { key: 'page', group: 'public', path: '/p/$id', file: 'p.$id.tsx' }, - { key: 'post', group: 'public', path: '/post/$id', file: 'post.$id.tsx' }, +/** Each route key's file and path; the keys and their surfaces come from core's `CMS_ROUTE_KEYS`. */ +const ROUTES: Record< + CmsRouteKey, { - key: 'preview', - group: 'public', + /** URL path; `null` for the index route. Admin paths get `adminBasePath`. */ + path: string | null + file: string + } +> = { + index: { path: null, file: 'index.tsx' }, + page: { path: '/p/$id', file: 'p.$id.tsx' }, + post: { path: '/post/$id', file: 'post.$id.tsx' }, + preview: { path: '/preview/$collection/$id', file: 'preview.$collection.$id.tsx', }, - { - key: 'sitemap', - group: 'public', - path: '/sitemap.xml', - file: 'sitemap.xml.ts', - }, - { - key: 'robots', - group: 'public', - path: '/robots.txt', - file: 'robots.txt.ts', - }, - { key: 'notFound', group: 'public', path: '/$', file: '$.tsx' }, - { key: 'content', group: 'admin', path: '/content', file: 'content.tsx' }, - { - key: 'edit', - group: 'admin', - path: '/edit/$collection/$id', - file: 'edit.$collection.$id.tsx', - }, - { key: 'agent', group: 'admin', path: '/agent', file: 'agent.tsx' }, - { key: 'review', group: 'admin', path: '/review', file: 'review.tsx' }, - { key: 'settings', group: 'admin', path: '/settings', file: 'settings.tsx' }, - { key: 'apiWebMcp', group: 'api', path: '/api/cms', file: 'api.cms.ts' }, - { - key: 'apiV1', - group: 'api', - path: '/api/cms/v1/$', - file: 'api.cms.v1.$.ts', - }, - { key: 'apiMcp', group: 'api', path: '/api/mcp', file: 'api.mcp.ts' }, - { key: 'apiMedia', group: 'api', path: '/api/media', file: 'api.media.ts' }, - { - key: 'apiMediaFile', - group: 'api', - path: '/api/media/$name', - file: 'api.media.$name.ts', - }, -] + sitemap: { path: '/sitemap.xml', file: 'sitemap.xml.ts' }, + robots: { path: '/robots.txt', file: 'robots.txt.ts' }, + notFound: { path: '/$', file: '$.tsx' }, + content: { path: '/content', file: 'content.tsx' }, + edit: { path: '/edit/$collection/$id', file: 'edit.$collection.$id.tsx' }, + agent: { path: '/agent', file: 'agent.tsx' }, + review: { path: '/review', file: 'review.tsx' }, + settings: { path: '/settings', file: 'settings.tsx' }, + apiWebMcp: { path: '/api/cms', file: 'api.cms.ts' }, + apiV1: { path: '/api/cms/v1/$', file: 'api.cms.v1.$.ts' }, + apiMcp: { path: '/api/mcp', file: 'api.mcp.ts' }, + apiMedia: { path: '/api/media', file: 'api.media.ts' }, + apiMediaFile: { path: '/api/media/$name', file: 'api.media.$name.ts' }, +} export interface CmsVirtualRoutesOptions { /** @@ -279,27 +240,30 @@ export function cmsVirtualRoutes( : rel(packageFile('__root.tsx')) const include = options.include ?? {} - const enabled: Record = { + const enabled: Record = { public: include.public ?? true, admin: include.admin ?? true, api: include.api ?? true, } const uiChildren: Array = [] - for (const def of ROUTES) { - if (!enabled[def.group]) continue - const override = options.routes?.[def.key] - if (override === false) continue - const urlPath = - def.group === 'admin' && def.path ? `${adminBase}${def.path}` : def.path - let file: string - if (override) file = userFile(override) - else if (def.group === 'admin' && adminBase && urlPath) { - file = rel( - writePrefixedRouteFile(packageFile(def.file), urlPath, generatedDir), - ) - } else file = rel(packageFile(def.file)) - uiChildren.push(urlPath === null ? index(file) : route(urlPath, file)) + for (const surface of ['public', 'admin', 'api'] as const) { + if (!enabled[surface]) continue + for (const key of CMS_ROUTE_KEYS[surface]) { + const def = ROUTES[key] + const override = options.routes?.[key] + if (override === false) continue + const urlPath = + surface === 'admin' && def.path ? `${adminBase}${def.path}` : def.path + let file: string + if (override) file = userFile(override) + else if (surface === 'admin' && adminBase && urlPath) { + file = rel( + writePrefixedRouteFile(packageFile(def.file), urlPath, generatedDir), + ) + } else file = rel(packageFile(def.file)) + uiChildren.push(urlPath === null ? index(file) : route(urlPath, file)) + } } const underAdmin = ( diff --git a/scripts/__fixtures__/definitions/clean/cms.definition.ts b/scripts/__fixtures__/definitions/clean/cms.definition.ts new file mode 100644 index 00000000..509f264f --- /dev/null +++ b/scripts/__fixtures__/definitions/clean/cms.definition.ts @@ -0,0 +1,15 @@ +// Apps import `@tanstack/cms-core/definition`; the fixture reaches the same +// module by path because the repo root doesn't depend on the package. +import { defineCmsDefinition } from '../../../../packages/core/src/definition' +import { post } from './collections' + +export const definition = defineCmsDefinition({ + collections: [post], + admin: { basePath: '/admin' }, + plugins: [ + { + name: 'analytics', + adminRoutes: [{ type: 'route', path: '/analytics', file: 'a.tsx' }], + }, + ], +}) diff --git a/scripts/__fixtures__/definitions/clean/collections.ts b/scripts/__fixtures__/definitions/clean/collections.ts new file mode 100644 index 00000000..3f1536ac --- /dev/null +++ b/scripts/__fixtures__/definitions/clean/collections.ts @@ -0,0 +1,8 @@ +import { defineCollection } from '../../../../packages/core/src/index' + +export const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text', required: true }], +}) diff --git a/scripts/__fixtures__/definitions/definition-only/cms.definition.ts b/scripts/__fixtures__/definitions/definition-only/cms.definition.ts new file mode 100644 index 00000000..70c24390 --- /dev/null +++ b/scripts/__fixtures__/definitions/definition-only/cms.definition.ts @@ -0,0 +1,11 @@ +import { + defineCmsDefinition, + definePlugin, +} from '../../../../packages/core/src/definition.ts' +import { page, redirect } from './collections.ts' + +export const definition = defineCmsDefinition({ + collections: [page, redirect], + admin: { basePath: '/admin' }, + plugins: [definePlugin({ name: 'empty' })], +}) diff --git a/scripts/__fixtures__/definitions/definition-only/collections.ts b/scripts/__fixtures__/definitions/definition-only/collections.ts new file mode 100644 index 00000000..95cdad1a --- /dev/null +++ b/scripts/__fixtures__/definitions/definition-only/collections.ts @@ -0,0 +1,38 @@ +// Everything a collection module needs comes from the definition entry +// (`@tanstack/cms-core/definition` in an app), never the package root. +import { + assetField, + defineBlock, + defineCollection, + redirectsCollection, + seoField, +} from '../../../../packages/core/src/definition.ts' +import type { + CollectionAccess, + InferDoc, +} from '../../../../packages/core/src/definition.ts' + +const editorsWrite: CollectionAccess = { update: ['editor', 'admin'] } + +export const hero = defineBlock({ + type: 'hero', + label: 'Hero', + fields: [{ name: 'heading', label: 'Heading', type: 'text' }], +}) + +export const page = defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + access: editorsWrite, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'body', label: 'Body', type: 'blocks' }, + assetField({ name: 'cover', label: 'Cover', kinds: ['image'] }), + seoField(), + ], +}) + +export type PageDoc = InferDoc + +export const redirect = redirectsCollection() diff --git a/scripts/__fixtures__/definitions/no-export/cms.definition.ts b/scripts/__fixtures__/definitions/no-export/cms.definition.ts new file mode 100644 index 00000000..817673f5 --- /dev/null +++ b/scripts/__fixtures__/definitions/no-export/cms.definition.ts @@ -0,0 +1 @@ +export const notADefinition = { collections: [] } diff --git a/scripts/__fixtures__/definitions/react/cms.definition.ts b/scripts/__fixtures__/definitions/react/cms.definition.ts new file mode 100644 index 00000000..eab7fdaf --- /dev/null +++ b/scripts/__fixtures__/definitions/react/cms.definition.ts @@ -0,0 +1,13 @@ +import { createElement } from 'react' +import { defineCmsDefinition } from '../../../../packages/core/src/definition' + +export const definition = defineCmsDefinition({ + collections: [ + { + name: 'post', + label: String(createElement), + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + }, + ], +}) diff --git a/scripts/__fixtures__/definitions/server-file/access.server.ts b/scripts/__fixtures__/definitions/server-file/access.server.ts new file mode 100644 index 00000000..3aaf7f80 --- /dev/null +++ b/scripts/__fixtures__/definitions/server-file/access.server.ts @@ -0,0 +1 @@ +export const canWrite = () => true diff --git a/scripts/__fixtures__/definitions/server-file/cms.definition.ts b/scripts/__fixtures__/definitions/server-file/cms.definition.ts new file mode 100644 index 00000000..2c98cd68 --- /dev/null +++ b/scripts/__fixtures__/definitions/server-file/cms.definition.ts @@ -0,0 +1,14 @@ +import { defineCmsDefinition } from '../../../../packages/core/src/definition' +import { canWrite } from './access.server' + +export const definition = defineCmsDefinition({ + collections: [ + { + name: 'post', + label: 'Posts', + titleField: 'title', + access: { update: canWrite }, + fields: [{ name: 'title', label: 'Title', type: 'text' }], + }, + ], +}) diff --git a/scripts/__fixtures__/definitions/start/cms.definition.ts b/scripts/__fixtures__/definitions/start/cms.definition.ts new file mode 100644 index 00000000..2e71d414 --- /dev/null +++ b/scripts/__fixtures__/definitions/start/cms.definition.ts @@ -0,0 +1,6 @@ +import { createServerOnlyFn } from '@tanstack/react-start' +import { defineCmsDefinition } from '../../../../packages/core/src/definition' + +export const isAdmin = createServerOnlyFn(() => true) + +export const definition = defineCmsDefinition({ collections: [] }) diff --git a/scripts/__fixtures__/definitions/tsx-file/cms.definition.ts b/scripts/__fixtures__/definitions/tsx-file/cms.definition.ts new file mode 100644 index 00000000..4a7b8820 --- /dev/null +++ b/scripts/__fixtures__/definitions/tsx-file/cms.definition.ts @@ -0,0 +1,13 @@ +import { defineCmsDefinition } from '../../../../packages/core/src/definition' +import { Hero } from './hero' + +export const definition = defineCmsDefinition({ + collections: [ + { + name: 'page', + label: String(Hero), + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + }, + ], +}) diff --git a/scripts/__fixtures__/definitions/tsx-file/hero.tsx b/scripts/__fixtures__/definitions/tsx-file/hero.tsx new file mode 100644 index 00000000..ebb8387a --- /dev/null +++ b/scripts/__fixtures__/definitions/tsx-file/hero.tsx @@ -0,0 +1 @@ +export const Hero = () => null diff --git a/scripts/__fixtures__/definitions/ui-react-root/cms.definition.ts b/scripts/__fixtures__/definitions/ui-react-root/cms.definition.ts new file mode 100644 index 00000000..1b0667e7 --- /dev/null +++ b/scripts/__fixtures__/definitions/ui-react-root/cms.definition.ts @@ -0,0 +1,6 @@ +import { createMockAuth } from '@tanstack/cms-ui-react' +import { defineCmsDefinition } from '../../../../packages/core/src/definition' + +export const auth = createMockAuth() + +export const definition = defineCmsDefinition({ collections: [] }) diff --git a/scripts/lib/definition-guard.mjs b/scripts/lib/definition-guard.mjs new file mode 100644 index 00000000..ce439b25 --- /dev/null +++ b/scripts/lib/definition-guard.mjs @@ -0,0 +1,58 @@ +/** + * A `module.register()` resolve hook for `scripts/verify-definitions.ts`. It + * makes every import a `cms.definition.ts` must not pull in, directly or + * transitively, fail with a `ForbiddenDefinitionImport` error. + * + * Plain JavaScript: hooks run on Node's loader thread, where the TypeScript + * loader registered for the definition itself does not apply. + */ +import { fileURLToPath } from 'node:url' + +export const ERROR_NAME = 'ForbiddenDefinitionImport' + +/** Packages a definition can't import, root and subpaths alike. */ +const PACKAGES = [ + ['react', 'React'], + ['react-dom', 'React DOM'], + ['@tanstack/react-start', 'TanStack Start'], + ['@tanstack/react-router', 'TanStack Router (React)'], + ['@tanstack/cms-core/server', 'CMS server code'], +] + +/** Packages whose root a definition can't import; subpaths are allowed. */ +const ROOTS = [['@tanstack/cms-ui-react', 'the React UI package root']] + +const SERVER_FILE = /(^|[/\\])[^/\\]*\.server(\.[^/\\]*)?$/ +const JSX_FILE = /\.[jt]sx$/ + +/** The rule `specifier` (or the file it resolved to) breaks, if any. */ +export function forbiddenRule(specifier, url) { + for (const [name, label] of PACKAGES) { + if (specifier === name || specifier.startsWith(`${name}/`)) return label + } + for (const [name, label] of ROOTS) { + if (specifier === name) return label + } + const path = url?.startsWith('file:') ? fileURLToPath(url) : specifier + if (JSX_FILE.test(path)) return 'a .tsx/.jsx module' + if (SERVER_FILE.test(path) || SERVER_FILE.test(specifier)) { + return 'a *.server.* module' + } + return undefined +} + +function forbidden(specifier, parentURL, rule) { + const detail = JSON.stringify({ specifier, importer: parentURL, rule }) + const error = new Error(`${ERROR_NAME} ${detail}`) + error.name = ERROR_NAME + return error +} + +export async function resolve(specifier, context, nextResolve) { + const before = forbiddenRule(specifier) + if (before) throw forbidden(specifier, context.parentURL, before) + const resolved = await nextResolve(specifier, context) + const after = forbiddenRule(specifier, resolved.url) + if (after) throw forbidden(specifier, context.parentURL, after) + return resolved +} diff --git a/scripts/lib/load-definition.mjs b/scripts/lib/load-definition.mjs new file mode 100644 index 00000000..f53132da --- /dev/null +++ b/scripts/lib/load-definition.mjs @@ -0,0 +1,108 @@ +/** + * Child process for `scripts/verify-definitions.ts`: load one + * `cms.definition.ts` behind the definition guard, call its accessors, and + * print the result as one line of JSON. + * + * Run as `node --import tsx scripts/lib/load-definition.mjs `. The guard + * is registered after `tsx`, so it sees every specifier first. + */ +import { register } from 'node:module' +import { pathToFileURL } from 'node:url' +import { ERROR_NAME } from './definition-guard.mjs' + +register('./definition-guard.mjs', import.meta.url) + +const ACCESSORS = ['adminBasePath', 'collections', 'pluginRoutes', 'routeKeys'] + +function isDefinition(value) { + return ( + typeof value === 'object' && + value !== null && + ACCESSORS.every((name) => typeof value[name] === 'function') + ) +} + +function findDefinition(mod) { + if (isDefinition(mod.definition)) return mod.definition + if (isDefinition(mod.default)) return mod.default + return Object.values(mod).find(isDefinition) +} + +/** Call each accessor and return what's wrong with its value, if anything. */ +function checkAccessors(definition) { + const problems = [] + const values = {} + const check = (name, test, describe) => { + try { + const value = definition[name]() + values[name] = describe(value) + if (!test(value)) problems.push(`${name}() returned ${values[name]}`) + } catch (error) { + problems.push(`${name}() threw: ${error?.message ?? error}`) + } + } + const isArray = (v) => Array.isArray(v) + check( + 'adminBasePath', + (v) => typeof v === 'string', + (v) => JSON.stringify(v), + ) + check( + 'collections', + (v) => isArray(v) && v.every((c) => typeof c?.name === 'string'), + (v) => (isArray(v) ? `${v.length} collection(s)` : JSON.stringify(v)), + ) + check( + 'pluginRoutes', + (v) => isArray(v?.routes) && isArray(v?.adminRoutes), + (v) => + isArray(v?.routes) && isArray(v?.adminRoutes) + ? `${v.routes.length} route(s), ${v.adminRoutes.length} admin route(s)` + : JSON.stringify(v), + ) + check( + 'routeKeys', + (v) => isArray(v) && v.length > 0 && v.every((k) => typeof k === 'string'), + (v) => (isArray(v) ? `${v.length} key(s)` : JSON.stringify(v)), + ) + return { problems, values } +} + +const file = process.argv[2] +const result = { file, violations: [], accessors: undefined, error: undefined } +try { + const mod = await import(pathToFileURL(file).href) + const definition = findDefinition(mod) + if (!definition) { + result.violations.push({ + rule: 'no definition export', + detail: + 'export the `defineCmsDefinition(...)` result as `definition` or default', + }) + } else { + const { problems, values } = checkAccessors(definition) + result.accessors = values + for (const detail of problems) { + result.violations.push({ rule: 'accessor', detail }) + } + } +} catch (error) { + const message = String(error?.message ?? error) + const forbidden = parseForbidden(message) + if (forbidden) result.violations.push(forbidden) + else result.error = message +} + +function parseForbidden(message) { + const at = message.indexOf(`${ERROR_NAME} `) + if (at === -1) return undefined + try { + const { specifier, importer, rule } = JSON.parse( + message.slice(at + ERROR_NAME.length + 1), + ) + return { rule, specifier, importer } + } catch { + return undefined + } +} +process.stdout.write(`${JSON.stringify(result)}\n`) diff --git a/scripts/pack-consumer.mjs b/scripts/pack-consumer.mjs index 37c1121a..50f0942f 100644 --- a/scripts/pack-consumer.mjs +++ b/scripts/pack-consumer.mjs @@ -194,6 +194,7 @@ writeFileSync( join(app, 'src/types.ts'), `import './cms.config' import { adminPath, defineCollection } from '@tanstack/cms-core' +import { defineCmsDefinition } from '@tanstack/cms-core/definition' import { commitDocument } from '@tanstack/cms-core/server' import { d1Storage, markdownStorage, sqliteStorage } from '@tanstack/cms-core/storage' import { localMedia } from '@tanstack/cms-core/media' @@ -222,6 +223,7 @@ export async function typed(): Promise { export const used = [ adminPath('/content'), defineCollection, + defineCmsDefinition, commitDocument, sqliteStorage, d1Storage, @@ -254,6 +256,7 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { defineCms } from '@tanstack/cms-core' +import { defineCmsDefinition } from '@tanstack/cms-core/definition' import { closeStore, commitDocument, @@ -278,6 +281,10 @@ assert.equal(typeof markdownStorage, 'function') assert.equal(typeof loadMarkdownDir, 'function') assert.equal(typeof subscribeCmsCollectionEvents, 'function') assert.equal(typeof SiteShell, 'function') +assert.equal( + defineCmsDefinition({ collections: [], admin: { basePath: 'admin/' } }).adminBasePath(), + '/admin', +) const dataDir = mkdtempSync(join(tmpdir(), 'cms-consumer-data-')) defineCms({ diff --git a/scripts/verify-definitions.test.ts b/scripts/verify-definitions.test.ts new file mode 100644 index 00000000..c85a5d45 --- /dev/null +++ b/scripts/verify-definitions.test.ts @@ -0,0 +1,121 @@ +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterAll, describe, expect, it } from 'vitest' +import { findDefinitions, verifyDefinition } from './verify-definitions' + +const FIXTURES = 'scripts/__fixtures__/definitions' +const fixture = (name: string) => `${FIXTURES}/${name}/cms.definition.ts` + +describe('verifyDefinition', { timeout: 30_000 }, () => { + it('passes a clean definition and reports its accessors', () => { + const result = verifyDefinition(fixture('clean')) + expect(result.error).toBeUndefined() + expect(result.violations).toEqual([]) + expect(result.accessors).toEqual({ + adminBasePath: '"/admin"', + collections: '1 collection(s)', + pluginRoutes: '0 route(s), 1 admin route(s)', + routeKeys: '17 key(s)', + }) + }) + + it('passes a definition whose collections import only the definition entry', () => { + const result = verifyDefinition(fixture('definition-only')) + expect(result.error).toBeUndefined() + expect(result.violations).toEqual([]) + expect(result.accessors?.collections).toBe('2 collection(s)') + }) + + it('loads that definition with type stripping alone, as Vite config loading does', () => { + const url = pathToFileURL(resolve(fixture('definition-only'))).href + const child = spawnSync( + process.execPath, + [ + '--experimental-strip-types', + '--no-warnings', + '--input-type=module', + '-e', + `const { definition } = await import(${JSON.stringify(url)}) + process.stdout.write(definition.collections().map((c) => c.name).join())`, + ], + { encoding: 'utf8' }, + ) + expect(child.stderr).toBe('') + expect(child.stdout.trim()).toBe('page,redirect') + }) + + it.each([ + ['react', 'React', 'react'], + ['start', 'TanStack Start', '@tanstack/react-start'], + ['ui-react-root', 'the React UI package root', '@tanstack/cms-ui-react'], + ['server-file', 'a *.server.* module', 'access.server'], + ['tsx-file', 'a .tsx/.jsx module', 'hero'], + ])('reports a definition importing %s', (name, rule, specifier) => { + const result = verifyDefinition(fixture(name)) + expect(result.error).toBeUndefined() + expect(result.violations).toHaveLength(1) + expect(result.violations[0]).toMatchObject({ rule }) + expect(result.violations[0]?.specifier).toContain(specifier) + expect(result.violations[0]?.importer).toContain( + `${FIXTURES}/${name}/cms.definition.ts`, + ) + }) + + it('reports a module without a definition export', () => { + expect(verifyDefinition(fixture('no-export')).violations).toEqual([ + expect.objectContaining({ rule: 'no definition export' }), + ]) + }) +}) + +describe('verify-definitions CLI', { timeout: 30_000 }, () => { + const run = (args: Array, env: Record = {}) => + spawnSync( + process.execPath, + ['--import', 'tsx', 'scripts/verify-definitions.ts', ...args], + { encoding: 'utf8', env: { ...process.env, ...env } }, + ) + + it('reports violations but exits 0 by default', () => { + const child = run([fixture('react')]) + expect(child.status).toBe(0) + expect(child.stdout).toContain('imports React: "react"') + expect(child.stdout).toContain('Report-only') + }) + + it('fails with --strict or CMS_VERIFY_DEFINITIONS_STRICT=1', () => { + expect(run(['--strict', fixture('react')]).status).toBe(1) + expect( + run([fixture('react')], { CMS_VERIFY_DEFINITIONS_STRICT: '1' }).status, + ).toBe(1) + expect(run(['--strict', fixture('clean')]).status).toBe(0) + }) +}) + +describe('findDefinitions', () => { + const root = mkdtempSync(join(tmpdir(), 'verify-definitions-')) + afterAll(() => rmSync(root, { recursive: true, force: true })) + + it('finds cms.definition.ts under app, starters, and examples only', async () => { + for (const file of [ + 'app/prm/src/cms.definition.ts', + 'starters/blog/src/cms.definition.ts', + 'examples/blog/src/cms.definition.ts', + 'examples/blog/node_modules/x/cms.definition.ts', + 'examples/payload-before/src/cms.definition.ts', + 'packages/core/src/cms.definition.ts', + 'app/prm/src/cms.config.ts', + ]) { + mkdirSync(join(root, dirname(file)), { recursive: true }) + writeFileSync(join(root, file), '') + } + expect(await findDefinitions(root)).toEqual([ + 'app/prm/src/cms.definition.ts', + 'examples/blog/src/cms.definition.ts', + 'starters/blog/src/cms.definition.ts', + ]) + }) +}) diff --git a/scripts/verify-definitions.ts b/scripts/verify-definitions.ts new file mode 100644 index 00000000..b62f897d --- /dev/null +++ b/scripts/verify-definitions.ts @@ -0,0 +1,139 @@ +/** + * The light-definition load test. Finds every `cms.definition.ts` under + * `app/*`, `starters/*`, and `examples/*` and imports each in a plain Node + * process (TypeScript via `tsx`, no Vite, no React) behind a resolve hook + * that fails on `react`, `react-dom`, any `.tsx`/`.jsx`, + * `@tanstack/react-start`, `@tanstack/react-router`, the + * `@tanstack/cms-ui-react` root, `@tanstack/cms-core/server`, and `*.server.*` + * files (see `lib/definition-guard.mjs`). Then it checks that the accessors + * (`adminBasePath()`, `collections()`, `pluginRoutes()`, `routeKeys()`) + * return values. + * + * pnpm test:definitions report only: print, exit 0 + * pnpm test:definitions --strict exit 1 on any violation + * CMS_VERIFY_DEFINITIONS_STRICT=1 pnpm … same as --strict + * pnpm test:definitions path/to/cms.definition.ts … check these files only + */ +import { spawnSync } from 'node:child_process' +import { relative, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { glob } from 'tinyglobby' +import { IGNORE } from './lib/workspace-files' + +const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))) +const LOADER = fileURLToPath( + new URL('./lib/load-definition.mjs', import.meta.url), +) + +export const DEFINITION_GLOBS = [ + '{app,starters,examples}/*/**/cms.definition.{ts,mts,js,mjs}', +] + +export interface DefinitionViolation { + rule: string + specifier?: string + importer?: string + detail?: string +} + +export interface DefinitionResult { + file: string + violations: Array + /** What each accessor returned, summarized, when the definition loaded. */ + accessors?: Record + /** A load failure that isn't a forbidden import (syntax, missing module, …). */ + error?: string +} + +/** Repo-relative paths of every `cms.definition.ts`, sorted. */ +export async function findDefinitions(cwd = ROOT): Promise> { + const files = await glob(DEFINITION_GLOBS, { cwd, ignore: IGNORE }) + return files.sort() +} + +/** Load one definition in its own Node process and report what it broke. */ +export function verifyDefinition(file: string, cwd = ROOT): DefinitionResult { + const absolute = resolve(cwd, file) + const child = spawnSync( + process.execPath, + ['--import', 'tsx', LOADER, absolute], + { cwd: ROOT, encoding: 'utf8', timeout: 60_000 }, + ) + const line = child.stdout?.trim().split('\n').at(-1) + if (child.status === 0 && line) { + try { + return { ...(JSON.parse(line) as DefinitionResult), file } + } catch { + // Fall through: the definition printed to stdout. + } + } + return { + file, + violations: [], + error: + child.error?.message ?? + (child.stderr?.trim() || `exited with ${child.status}`), + } +} + +function failed(result: DefinitionResult): boolean { + return result.violations.length > 0 || result.error !== undefined +} + +function report(result: DefinitionResult, cwd: string): string { + const lines = [`${failed(result) ? '✗' : '✓'} ${result.file}`] + for (const v of result.violations) { + if (v.specifier) { + const from = v.importer?.startsWith('file:') + ? relative(cwd, fileURLToPath(v.importer)) + : (v.importer ?? '?') + lines.push(` imports ${v.rule}: "${v.specifier}" from ${from}`) + } else { + lines.push(` ${v.rule}: ${v.detail}`) + } + } + if (result.error) lines.push(` failed to load: ${result.error}`) + if (!failed(result) && result.accessors) { + lines.push( + ` ${Object.entries(result.accessors) + .map(([k, v]) => `${k}() → ${v}`) + .join('; ')}`, + ) + } + return lines.join('\n') +} + +async function main(): Promise { + const args = process.argv.slice(2) + const strict = + args.includes('--strict') || + ['1', 'true'].includes(process.env.CMS_VERIFY_DEFINITIONS_STRICT ?? '') + const explicit = args.filter((a) => !a.startsWith('--')) + const files = explicit.length ? explicit : await findDefinitions() + if (!files.length) { + console.log('No cms.definition.ts files found.') + return + } + const results = files.map((file) => verifyDefinition(file)) + for (const result of results) console.log(report(result, ROOT)) + const bad = results.filter(failed) + console.log( + `\n${results.length - bad.length}/${results.length} definition(s) load cleanly in plain Node.`, + ) + if (!bad.length) return + if (strict) { + console.error( + 'A cms.definition.ts must import only `@tanstack/cms-core/definition` ' + + 'and pure collection modules. Move server-bound code to the runtime ' + + 'config (`defineCms(definition, runtime)`).', + ) + process.exit(1) + } + console.log( + 'Report-only: not failing. Pass --strict (or CMS_VERIFY_DEFINITIONS_STRICT=1) to make violations fail.', + ) +} + +if (process.argv[1] && resolve(process.argv[1]) === import.meta.filename) { + await main() +} diff --git a/tsconfig.docs.json b/tsconfig.docs.json index c9dc615a..aba1b66b 100644 --- a/tsconfig.docs.json +++ b/tsconfig.docs.json @@ -4,6 +4,7 @@ "compilerOptions": { "paths": { "@tanstack/cms-core": ["./packages/core/src/index.ts"], + "@tanstack/cms-core/definition": ["./packages/core/src/definition.ts"], "@tanstack/cms-core/server": ["./packages/core/src/server.ts"], "@tanstack/cms-core/storage": ["./packages/core/src/storage.ts"], "@tanstack/cms-core/media": ["./packages/core/src/media.ts"], diff --git a/tsconfig.json b/tsconfig.json index bac3d1f3..4d244fec 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,5 +2,5 @@ "$schema": "https://json.schemastore.org/tsconfig", "extends": "./tsconfig.base.json", "include": ["scripts", "*.config.ts", "*.config.js"], - "exclude": ["scripts/codemods/__fixtures__"] + "exclude": ["scripts/codemods/__fixtures__", "scripts/__fixtures__"] }