Files
ipal-kit/test/seedLocalizedArrays.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

213 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Block, Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { createSeeder } from '../src/exports/seed.js'
import { localize } from '../src/modules/seed/values.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
/**
* Regression (vanstevpl-web, 1.15.3): a whole localized value — `fields: { pl: [...], en: [...], de: [...] }` —
* must keep the stored row ids in every locale. Before the fix each locale write made new shared rows and only
* the last language survived (forms, nested select options, page layouts, global arrays).
*/
const LOCALES = ['pl', 'en', 'de'] as const
const confirmation = (text: string) => ({
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
})
/** One form, written per locale as whole localized arrays — shared blocks with nested options. */
const formFields = (lang: { name: string; topic: string; topics: [string, string] }) => [
{ name: 'name', blockType: 'text', label: lang.name, required: true },
{
name: 'topic',
blockType: 'select',
label: lang.topic,
options: [
{ label: lang.topics[0], value: 'offer' },
{ label: lang.topics[1], value: 'other' },
],
},
]
const FORM = {
confirmationMessage: { de: confirmation('Danke'), en: confirmation('Thanks'), pl: confirmation('Dziękujemy') },
confirmationType: 'message',
fields: {
de: formFields({ name: 'Vorname', topic: 'Thema', topics: ['Angebot', 'Sonstiges'] }),
en: formFields({ name: 'First name', topic: 'Topic', topics: ['Offer', 'Other'] }),
pl: formFields({ name: 'Imię', topic: 'Temat', topics: ['Oferta', 'Inne'] }),
},
submitButtonLabel: { de: 'Senden', en: 'Send', pl: 'Wyślij' },
title: 'Contact form',
}
const section = (heading: string, items: string[]) => ({ blockType: 'section', heading, items: items.map((text) => ({ text })) })
describe('createSeeder: whole localized arrays keep every language', () => {
let payload: Payload
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
const sectionBlock: Block = {
slug: 'section',
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'items', type: 'array', fields: [{ name: 'text', type: 'text', localized: true }] },
],
}
const config = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
// Shared rows, text per locale (the block library's default).
{ name: 'layout', type: 'blocks', blocks: [sectionBlock] },
// Rows per locale (the block library's `localization: 'layout'`).
{ name: 'localizedLayout', type: 'blocks', blocks: [sectionBlock], localized: true },
],
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-arrays') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
globals: [
{
slug: 'footer',
fields: [{ name: 'links', type: 'array', fields: [{ name: 'label', type: 'text', localized: true }, { name: 'url', type: 'text' }] }],
},
],
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
plugins: [
iapl({
forms: {},
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
pages: { slug: 'pages' },
twoFactor: false,
} as never),
],
secret: 'seed-localized-arrays',
telemetry: false,
})
payload = await getPayload({ config })
}, 60_000)
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
const seeder = () => createSeeder(payload, { dryRun: false, log: () => {}, update: false })
const readAll = (collection: string, id: number | string) =>
payload.findByID({ id, collection: collection as never, depth: 0, fallbackLocale: false as never, locale: 'all' as never }) as Promise<Record<string, unknown>>
test('a form: blocks and nested select options keep every language and one set of row ids', async () => {
const result = await seeder().upsertBy('forms', { title: 'Contact form' }, FORM)
expect(result).toMatchObject({ status: 'create' })
const all = await readAll('forms', result.id!)
const fields = all.fields as { id: string; label: Record<string, string>; options?: { id: string; label: Record<string, string> }[] }[]
expect(fields).toHaveLength(2)
expect(fields[0].label).toEqual({ de: 'Vorname', en: 'First name', pl: 'Imię' })
expect(fields[1].label).toEqual({ de: 'Thema', en: 'Topic', pl: 'Temat' })
expect(fields[1].options?.map((o) => o.label)).toEqual([
{ de: 'Angebot', en: 'Offer', pl: 'Oferta' },
{ de: 'Sonstiges', en: 'Other', pl: 'Inne' },
])
expect(all.submitButtonLabel).toEqual({ de: 'Senden', en: 'Send', pl: 'Wyślij' })
// Every locale reads the same rows.
const ids = async (locale: string) => {
const doc = (await payload.findByID({ id: result.id!, collection: 'forms', depth: 0, fallbackLocale: false, locale: locale as never })) as unknown as { fields: { id: string; options?: { id: string }[] }[] }
return doc.fields.flatMap((f) => [f.id, ...(f.options ?? []).map((o) => o.id)])
}
const pl = await ids('pl')
expect(await ids('en')).toEqual(pl)
expect(await ids('de')).toEqual(pl)
// An editor's later save in Polish validates (no missing option labels).
const plDoc = await payload.findByID({ id: result.id!, collection: 'forms', depth: 0, fallbackLocale: false, locale: 'pl' })
await expect(payload.update({ id: result.id!, collection: 'forms', data: { ...plDoc, submitButtonLabel: 'Wyślij teraz' } as never, locale: 'pl' })).resolves.toBeTruthy()
const after = await readAll('forms', result.id!)
expect((after.fields as { label: Record<string, string> }[])[0].label).toEqual({ de: 'Vorname', en: 'First name', pl: 'Imię' })
})
test('a page: a shared layout keeps one set of rows; a localized layout keeps rows per locale', async () => {
const page = {
slug: { de: 'ueber-uns', en: 'about', pl: 'o-nas' },
layout: {
de: [section('Leistungen', ['Planung', 'Bau'])],
en: [section('Services', ['Design', 'Build'])],
pl: [section('Usługi', ['Projekt', 'Budowa'])],
},
localizedLayout: {
de: [section('Nur Deutsch', ['Eins'])],
en: [section('English only', ['One', 'Two', 'Three'])],
pl: [section('Tylko polski', ['Jeden', 'Dwa'])],
},
title: { de: 'Über uns', en: 'About', pl: 'O nas' },
}
const [result] = await seeder().upsertBySlug('pages', [page])
expect(result).toMatchObject({ status: 'create' })
const all = await readAll('pages', result.id!)
const layout = all.layout as { heading: Record<string, string>; id: string; items: { text: Record<string, string> }[] }[]
expect(layout).toHaveLength(1)
expect(layout[0].heading).toEqual({ de: 'Leistungen', en: 'Services', pl: 'Usługi' })
expect(layout[0].items.map((i) => i.text)).toEqual([
{ de: 'Planung', en: 'Design', pl: 'Projekt' },
{ de: 'Bau', en: 'Build', pl: 'Budowa' },
])
// Localized layout: each language has its own rows, with its own length.
for (const [locale, heading, count] of [['pl', 'Tylko polski', 2], ['en', 'English only', 3], ['de', 'Nur Deutsch', 1]] as const) {
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { localizedLayout: { heading: string; items: unknown[] }[] }
expect(doc.localizedLayout[0]).toMatchObject({ heading })
expect(doc.localizedLayout[0].items).toHaveLength(count)
}
})
test('a global array (fillGlobal) keeps every language', async () => {
const links = (labels: [string, string]) => [
{ label: labels[0], url: '/kontakt' },
{ label: labels[1], url: '/blog' },
]
const result = await seeder().fillGlobal('footer', {
links: { de: links(['Kontakt', 'Blog']), en: links(['Contact', 'Blog']), pl: links(['Kontakt', 'Wpisy']) },
})
expect(result).toMatchObject({ status: 'create' })
const all = (await payload.findGlobal({ slug: 'footer' as never, depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as { links: { label: Record<string, string>; url: string }[] }
expect(all.links.map((l) => l.label)).toEqual([
{ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' },
{ de: 'Blog', en: 'Blog', pl: 'Wpisy' },
])
expect(all.links.map((l) => l.url)).toEqual(['/kontakt', '/blog'])
})
})
describe('localize', () => {
test('a whole localized value keeps the stored row ids, nested arrays included', () => {
const stored = [{ id: 'a', options: [{ id: 'o1', label: 'Oferta' }] }]
const value = { en: [{ options: [{ label: 'Offer' }] }], pl: [{ options: [{ label: 'Oferta' }] }] }
expect(localize(value, 'en', stored, ['pl', 'en'])).toEqual([{ id: 'a', options: [{ id: 'o1', label: 'Offer' }] }])
expect(localize(value, 'de', stored, ['pl', 'en', 'de'])).toBeUndefined()
})
test('with a schema, a localized field never reuses another locale’s rows', () => {
const schema = { fields: [{ name: 'layout', type: 'array', fields: [{ name: 'text', type: 'text' }], localized: true }] }
const stored = { layout: [{ id: 'pl-row', text: 'Polski' }] }
expect(localize({ layout: { en: [{ text: 'English' }] } }, 'en', stored, ['pl', 'en'], schema)).toEqual({ layout: [{ text: 'English' }] })
expect(localize({ layout: { en: [{ text: 'English' }] } }, 'en', stored, ['pl', 'en'])).toEqual({ layout: [{ id: 'pl-row', text: 'English' }] })
})
})