Files
ipal-kit/test/graphqlSchema.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 2d1cc0e77d Block library: 15 blocks, registry, primitives, templates, manifest, eject
- @intecion/ipal-kit/blocks: libraryBlocks() opt-in, one builder per block, field
  builders, option merging, blockLibraryManifest, faqItemsFromLayout
- @intecion/ipal-kit/blocks/rsc: createBlockRegistry, the block components and UI
  primitives (token utilities only; next/image and next/link passed in)
- @intecion/ipal-kit/templates: 10 page templates as createSeeder data
- createSeeder: { $form: title } references
- ipal-blocks eject <block>
- tests: options, rendering and a11y per block, Payload + seeding, GraphQL, admin
  wording, schema snapshot (versioning), eject imports
- shorter admin labels: link "New tab", table of contents "Show contents"

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:05:47 +01:00

151 lines
6.2 KiB
TypeScript

import type { Config, SanitizedConfig } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { realpathSync } from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
/**
* GraphQL is built from every collection and global the plugin adds — select and
* radio option VALUES become enum names, which must match /^[_a-zA-Z][_a-zA-Z0-9]*$/.
* A bad one (e.g. '|') makes /api/graphql answer 500 for the whole site, and the
* admin never notices because it doesn't use GraphQL. This builds the schema from
* the plugin with every module on and validates it.
*
* `@payloadcms/graphql` and `graphql` are loaded next to `@payloadcms/next` — the
* same copies a project's /api/graphql route uses.
*/
async function loadGraphql() {
// pnpm: dependencies of a package sit next to it in .pnpm/<pkg>/node_modules.
const next = realpathSync(path.resolve(import.meta.dirname, '../node_modules/@payloadcms/next'))
const payloadGraphql = realpathSync(path.join(next, '..', 'graphql'))
const graphqlDir = realpathSync(path.join(payloadGraphql, '..', '..', 'graphql'))
const { configToSchema } = (await import(pathToFileURL(path.join(payloadGraphql, 'dist/index.js')).href)) as {
configToSchema: (config: SanitizedConfig) => { schema: unknown }
}
const graphql = (await import(pathToFileURL(path.join(graphqlDir, 'index.js')).href)) as {
validateSchema: (schema: unknown) => readonly { message: string }[]
}
const { formatName } = (await import(pathToFileURL(path.join(payloadGraphql, 'dist/utilities/formatName.js')).href)) as {
formatName: (value: string) => string
}
return { configToSchema, formatName, validateSchema: graphql.validateSchema }
}
const i18n: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const project = (): Omit<Config, 'plugins'> =>
({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', localized: true },
// Every library block — their select values become enum names too.
{ name: 'layout', type: 'blocks', blocks: libraryBlocks({ ...Object.fromEntries(LIBRARY_BLOCK_SLUGS.map((s) => [s, true])), featureGrid: { icons: ['phone', 'mail'] }, testimonials: { collection: 'posts' } }) },
],
versions: { drafts: true },
},
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: true },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
secret: 'graphql-schema-test',
telemetry: false,
}) as unknown as Config
const fullConfig = () =>
buildTestConfig({
...project(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
consentLog: true,
content: { collections: [{ slug: 'posts' }] },
cookieScanner: { crawl: { serviceUrl: 'http://crawler.test', siteUrl: 'http://site.test', token: 'x' } },
forms: { emailLayout: true },
i18n,
indexNow: true,
lightbox: true,
pages: { slug: 'pages' },
seo: { collections: ['pages', 'posts'] },
stats: true,
twoFactor: false,
whiteLabel: true,
} as never),
],
})
type AnyField = { blocks?: { fields: AnyField[]; slug: string }[]; fields?: AnyField[]; name?: string; options?: unknown[]; tabs?: { fields: AnyField[] }[]; type: string }
/** Every select/radio in a field tree, with a readable path. */
function* optionFields(fields: AnyField[], where: string): Generator<{ field: AnyField; where: string }> {
for (const f of fields) {
const here = f.name ? `${where}.${f.name}` : where
if ((f.type === 'select' || f.type === 'radio') && f.options) {yield { field: f, where: here }}
if (f.fields) {yield* optionFields(f.fields, here)}
for (const tab of f.tabs ?? []) {yield* optionFields(tab.fields, here)}
for (const block of f.blocks ?? []) {yield* optionFields(block.fields, `${here}[${block.slug}]`)}
}
}
const VALID_NAME = /^[_a-z]\w*$/i
describe('GraphQL schema of the full plugin config', () => {
let payload: Awaited<ReturnType<typeof getPayload>>
beforeAll(async () => {
payload = await getPayload({ config: fullConfig() })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
test('no select/radio value becomes an invalid or duplicate enum name', async () => {
const { formatName } = await loadGraphql()
const problems: string[] = []
const roots = [
...payload.config.collections.map((c) => ({ fields: c.fields as AnyField[], where: c.slug })),
...payload.config.globals.map((g) => ({ fields: g.fields as AnyField[], where: g.slug })),
]
for (const root of roots) {
for (const { field, where } of optionFields(root.fields, root.where)) {
const seen = new Map<string, string>()
for (const option of field.options ?? []) {
const value = typeof option === 'string' ? option : String((option as { value: unknown }).value)
const name = formatName(value)
if (!VALID_NAME.test(name)) {problems.push(`${where}: '${value}' → '${name}'`)}
else if (seen.has(name)) {problems.push(`${where}: '${value}' and '${seen.get(name)}' → '${name}'`)}
seen.set(name, value)
}
}
}
expect(problems).toEqual([])
})
test('/api/graphql schema builds and validates', async () => {
const { configToSchema, validateSchema } = await loadGraphql()
const { schema } = configToSchema(payload.config)
expect(validateSchema(schema).map((e) => e.message)).toEqual([])
})
})