|
1 | 1 | import type { Collection } from '@nuxt/content' |
2 | 2 | import { z } from 'zod' |
3 | 3 |
|
| 4 | +const robotsFieldSchema = z.union([z.string(), z.boolean()]).optional() |
| 5 | + |
| 6 | +function withEditorHidden<T extends z.ZodTypeAny>(s: T): T { |
| 7 | + // .editor() is patched onto ZodType by @nuxt/content at runtime |
| 8 | + if (typeof (s as any).editor === 'function') |
| 9 | + return (s as any).editor({ hidden: true }) |
| 10 | + return s |
| 11 | +} |
| 12 | + |
| 13 | +export interface DefineRobotsSchemaOptions { |
| 14 | + /** |
| 15 | + * Pass the `z` instance from `@nuxt/content` to ensure `.editor({ hidden: true })` works |
| 16 | + * across Zod versions. When omitted, the bundled `z` is used (`.editor()` applied if available). |
| 17 | + */ |
| 18 | + z?: typeof z |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Define the robots schema field for a Nuxt Content collection. |
| 23 | + * |
| 24 | + * @example |
| 25 | + * defineCollection({ |
| 26 | + * type: 'page', |
| 27 | + * source: '**', |
| 28 | + * schema: z.object({ |
| 29 | + * robots: defineRobotsSchema() |
| 30 | + * }) |
| 31 | + * }) |
| 32 | + */ |
| 33 | +export function defineRobotsSchema(options?: DefineRobotsSchemaOptions) { |
| 34 | + const _z = options?.z ?? z |
| 35 | + const s = _z.union([_z.string(), _z.boolean()]).optional() |
| 36 | + return withEditorHidden(s) |
| 37 | +} |
| 38 | + |
| 39 | +// Legacy schema export (wraps entire collection) |
4 | 40 | export const schema = z.object({ |
5 | | - robots: z.union([z.string(), z.boolean()]).optional(), |
| 41 | + robots: withEditorHidden(robotsFieldSchema), |
6 | 42 | }) |
7 | 43 |
|
| 44 | +/** @deprecated Use `defineRobotsSchema()` in your collection schema instead. See https://nuxtseo.com/robots/advanced/content */ |
8 | 45 | export function asRobotsCollection<T>(collection: Collection<T>): Collection<T> { |
| 46 | + console.warn('[robots] `asRobotsCollection()` is deprecated. Use `defineRobotsSchema()` in your collection schema instead. See https://nuxtseo.com/robots/advanced/content') |
9 | 47 | if (collection.type === 'page') { |
10 | 48 | // @ts-expect-error untyped |
11 | 49 | collection.schema = collection.schema ? schema.extend(collection.schema.shape) : schema |
|
0 commit comments