Fix /api/graphql 500: Site settings title separator values are GraphQL enum names
The titleSeparator select stored '|', '–', '-', '·', '/'. Select values become GraphQL enum names; '|', '–', '·' are invalid and '-' and '/' collide on '_', so every project's /api/graphql answered 500 since 1.0.1 (admin/REST unaffected). - Values are now pipe/endash/hyphen/middot/slash (same labels); TITLE_SEPARATORS and titleSeparatorChar map them to the character; titles accept old characters and custom project values literally - Field afterRead/beforeChange turn an old stored character into its name - MongoDB: rewritten at start (migrateTitleSeparator); Postgres: titleSeparatorSql() for the generated migration (verified up/down/up against Postgres 16) - Test builds the full plugin GraphQL schema and fails on invalid or duplicate enum names; unit tests for the mapping, hooks, SQL and Mongo rewrite - CHANGELOG Unreleased (Fixed + upgrade step 5), seo.md, ipal-upgrade, api.md Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f57d089f55
commit
bb10fb10fd
@@ -0,0 +1,140 @@
|
||||
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 { 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 }], 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([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { generalFields } from '../src/globals/SiteSettings/fields/general.js'
|
||||
import { readSiteMetaConfig } from '../src/modules/seo/readSiteMetaConfig.js'
|
||||
import {
|
||||
migrateTitleSeparator,
|
||||
TITLE_SEPARATORS,
|
||||
titleSeparatorChar,
|
||||
titleSeparatorName,
|
||||
titleSeparatorSql,
|
||||
} from '../src/modules/seo/titleSeparator.js'
|
||||
|
||||
type SelectField = {
|
||||
defaultValue: string
|
||||
hooks: { afterRead: ((a: { value: unknown }) => unknown)[]; beforeChange: ((a: { value: unknown }) => unknown)[] }
|
||||
name: string
|
||||
options: { value: string }[]
|
||||
}
|
||||
|
||||
const separatorField = (): SelectField => {
|
||||
const find = (fields: unknown[]): SelectField | undefined => {
|
||||
for (const f of fields as { fields?: unknown[]; name?: string }[]) {
|
||||
if (f.name === 'titleSeparator') {return f as unknown as SelectField}
|
||||
const inner = f.fields && find(f.fields)
|
||||
if (inner) {return inner}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
return find(generalFields)!
|
||||
}
|
||||
|
||||
describe('Site Settings → Title separator (GraphQL-safe values)', () => {
|
||||
test('stored values are names; each maps to its character', () => {
|
||||
const field = separatorField()
|
||||
expect(field.defaultValue).toBe('pipe')
|
||||
expect(field.options.map((o) => o.value)).toEqual(['pipe', 'endash', 'hyphen', 'middot', 'slash'])
|
||||
expect(field.options.map((o) => titleSeparatorChar(o.value))).toEqual(['|', '–', '-', '·', '/'])
|
||||
})
|
||||
|
||||
test('legacy characters (≤ 1.14.4) still work; unknown values are used literally', () => {
|
||||
for (const char of Object.values(TITLE_SEPARATORS)) {expect(titleSeparatorChar(char)).toBe(char)}
|
||||
expect(titleSeparatorChar('»')).toBe('»')
|
||||
expect(titleSeparatorChar('')).toBeUndefined()
|
||||
expect(titleSeparatorChar(null)).toBeUndefined()
|
||||
expect(titleSeparatorName('|')).toBe('pipe')
|
||||
expect(titleSeparatorName('endash')).toBe('endash')
|
||||
expect(titleSeparatorName('»')).toBe('»')
|
||||
})
|
||||
|
||||
test('the field reads and saves a legacy character as its name (no "invalid selection")', () => {
|
||||
const { hooks } = separatorField()
|
||||
expect(hooks.afterRead[0]({ value: '·' })).toBe('middot')
|
||||
expect(hooks.beforeChange[0]({ value: '/' })).toBe('slash')
|
||||
expect(hooks.beforeChange[0]({ value: 'hyphen' })).toBe('hyphen')
|
||||
})
|
||||
|
||||
test('titles use the character, for names and legacy values', async () => {
|
||||
const read = (titleSeparator: string) =>
|
||||
readSiteMetaConfig({ locale: 'pl', payload: {} as never, settings: { homepage: null, siteName: 'Acme', titleSeparator } })
|
||||
expect((await read('endash')).separator).toBe(' – ')
|
||||
expect((await read('|')).separator).toBe(' | ')
|
||||
})
|
||||
|
||||
test('migration SQL maps both ways and leaves other values alone', () => {
|
||||
expect(titleSeparatorSql()).toBe(
|
||||
`UPDATE "site_settings" SET "title_separator" = CASE "title_separator" WHEN '–' THEN 'endash' WHEN '-' THEN 'hyphen' WHEN '·' THEN 'middot' WHEN '|' THEN 'pipe' WHEN '/' THEN 'slash' ELSE "title_separator" END WHERE "title_separator" IN ('–', '-', '·', '|', '/');`,
|
||||
)
|
||||
expect(titleSeparatorSql({ direction: 'down', table: 'settings' })).toContain(`UPDATE "settings" SET "title_separator" = CASE "title_separator" WHEN 'endash' THEN '–'`)
|
||||
})
|
||||
|
||||
test('MongoDB: legacy character rewritten at start; other adapters untouched', async () => {
|
||||
const updateOne = vi.fn(async (filter: { titleSeparator: string }) => ({ modifiedCount: filter.titleSeparator === '|' ? 1 : 0 }))
|
||||
const logger = { error: vi.fn(), info: vi.fn() }
|
||||
await migrateTitleSeparator({ db: { name: 'mongoose', globals: { collection: { updateOne } } }, logger } as never)
|
||||
expect(updateOne).toHaveBeenCalledWith({ globalType: 'site-settings', titleSeparator: '|' }, { $set: { titleSeparator: 'pipe' } })
|
||||
expect(logger.info).toHaveBeenCalledOnce()
|
||||
|
||||
const sql = vi.fn()
|
||||
await migrateTitleSeparator({ db: { name: 'postgres', globals: { collection: { updateOne: sql } } }, logger } as never)
|
||||
expect(sql).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user