fix: sanitize duplicate blocks (#12440)

This commit is contained in:
Jacob Fletcher
2025-05-17 09:20:28 -04:00
committed by GitHub
parent 529bfe149e
commit 5855f3a475
2 changed files with 81 additions and 1 deletions

View File

@@ -9,7 +9,12 @@ import type {
TextField,
} from './types.js'
import { InvalidFieldName, InvalidFieldRelationship, MissingFieldType } from '../../errors/index.js'
import {
DuplicateFieldName,
InvalidFieldName,
InvalidFieldRelationship,
MissingFieldType,
} from '../../errors/index.js'
import { sanitizeFields } from './sanitize.js'
import { CollectionConfig } from '../../index.js'
@@ -55,6 +60,68 @@ describe('sanitizeFields', () => {
}).rejects.toThrow(InvalidFieldName)
})
it('should throw on duplicate field name', async () => {
const fields: Field[] = [
{
name: 'someField',
type: 'text',
label: 'someField',
},
{
name: 'someField',
type: 'text',
label: 'someField',
},
]
await expect(async () => {
await sanitizeFields({
config,
collectionConfig,
fields,
validRelationships: [],
})
}).rejects.toThrow(DuplicateFieldName)
})
it('should throw on duplicate block slug', async () => {
const fields: Field[] = [
{
name: 'blocks',
type: 'blocks',
blocks: [
{
slug: 'block',
fields: [
{
name: 'blockField',
type: 'text',
},
],
},
{
slug: 'block',
fields: [
{
name: 'blockField',
type: 'text',
},
],
},
],
},
]
await expect(async () => {
await sanitizeFields({
config,
collectionConfig,
fields,
validRelationships: [],
})
}).rejects.toThrow(DuplicateFieldName)
})
describe('auto-labeling', () => {
it('should populate label if missing', async () => {
const fields: Field[] = [

View File

@@ -242,6 +242,7 @@ export const sanitizeFields = async ({
if (!field.hooks) {
field.hooks = {}
}
if (!field.access) {
field.access = {}
}
@@ -289,13 +290,25 @@ export const sanitizeFields = async ({
throw new Error('You cannot have both blockReferences and blocks in the same blocks field')
}
const blockSlugs: string[] = []
for (const block of field.blockReferences ?? field.blocks) {
const blockSlug = typeof block === 'string' ? block : block.slug
if (blockSlugs.includes(blockSlug)) {
throw new DuplicateFieldName(blockSlug)
}
blockSlugs.push(blockSlug)
if (typeof block === 'string') {
continue
}
if (block._sanitized === true) {
continue
}
block._sanitized = true
block.fields = block.fields.concat(baseBlockFields)
block.labels = !block.labels ? formatLabels(block.slug) : block.labels