Merge claude/seeder-localized-arrays: whole localized arrays keep every language

createSeeder / writeLocales: a value seeded per language as a whole (form fields,
nested select options, page layouts, global arrays) keeps the stored row ids in
every locale instead of only the last language surviving; localized: true fields
keep rows per locale. Seed guards, the edit check and SEED_ONLY are unchanged.
Reported from vanstevpl-web.
This commit is contained in:
Radosław Smoliński
2026-11-12 15:35:38 +01:00
6 changed files with 315 additions and 12 deletions
+10
View File
@@ -8,6 +8,16 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## Unreleased
### Fixed
- **Seeding whole localized arrays** (`createSeeder`, `writeLocales`): a value written per language as a whole —
`fields: { pl: [...], en: [...], de: [...] }`, a page `layout`, a global array — now keeps the stored row ids in every
language. Before, each locale write made new shared rows and only the last language survived (form fields, nested
select options, layouts, global arrays); an editor's later save could then fail validation. Fields that are
themselves `localized: true` (a localized layout) keep rows per language, as before. Seed scripts need no change;
re-run a seed that was hit (locally first, or with `SEED_ONLY` on a live site).
## 1.15.3
### Fixed
@@ -564,7 +564,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
+4
View File
@@ -197,6 +197,10 @@ process.exit(seed.summary().errors ? 1 : 0)
**Seed values.** Write each value once, every language side by side. An object whose keys are all
locale codes is one value per locale (`{ pl: 'Kontakt', en: 'Contact' }`); anything else is the same
in every locale. A locale missing from such an object is left untouched in that locale.
This works at any level: a text (`label: { pl, en }`) or a whole array, layout or group (`fields: { pl: [...], en: [...] }`).
Rows of a field that is not localized are shared by every language — the helper reuses their ids, so give each
language the same rows in the same order (its texts differ; non-localized values such as an option's `value` come
from the last language written). A field with `localized: true` keeps its own rows per language.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`;
`{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form
is an error for that record, never an empty relation. Ready pages made of library blocks:
@@ -564,7 +564,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
+87 -10
View File
@@ -25,19 +25,81 @@ export function isLocalizedValue(v: unknown, codes: string[]): v is Record<strin
return isPlainObject(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
}
/** The schema of the value being localized: its fields, or its block types (`blocks` field rows). */
export type SeedSchema = { blocks?: Record<string, readonly SeedField[]>; fields?: readonly SeedField[] }
/** The slice of a Payload field config the seed helper reads. */
export type SeedField = {
blocks?: readonly ({ fields: readonly SeedField[]; slug: string } | string)[]
fields?: readonly SeedField[]
localized?: boolean
name?: string
tabs?: readonly { fields: readonly SeedField[]; name?: string }[]
type: string
}
/** Named fields at one level: rows, collapsibles and unnamed tabs add no path segment. */
function namedFields(fields: readonly SeedField[] = []): Map<string, SeedField> {
const out = new Map<string, SeedField>()
for (const f of fields) {
if (f.type === 'tabs') {
for (const tab of f.tabs ?? []) {
if (tab.name) {out.set(tab.name, { name: tab.name, type: 'group', fields: tab.fields })}
else {for (const [k, v] of namedFields(tab.fields)) {out.set(k, v)}}
}
} else if (f.name) {out.set(f.name, f)}
else if (f.fields) {for (const [k, v] of namedFields(f.fields)) {out.set(k, v)}}
}
return out
}
/** The schema below a field: a group's or array's fields, or a blocks field's block types. */
function schemaOf(field: SeedField | undefined, blockConfigs?: (slug: string) => readonly SeedField[] | undefined): SeedSchema | undefined {
if (!field) {return undefined}
if (field.type === 'blocks') {
const blocks: Record<string, readonly SeedField[]> = {}
for (const b of field.blocks ?? []) {
if (typeof b === 'string') {
const fields = blockConfigs?.(b)
if (fields) {blocks[b] = fields}
} else {blocks[b.slug] = b.fields}
}
return { blocks }
}
return field.fields ? { fields: field.fields } : undefined
}
/**
* The value for one locale. Arrays (array fields, blocks) keep the ids of the
* rows already stored at the same index — new ids would wipe the other
* locales' texts. A block row keeps its id only when its blockType matches.
* The value for one locale. Rows of arrays and blocks keep the ids of the rows
* already stored at the same index — new ids would wipe the other locales' texts.
* A block row keeps its id only when its blockType matches. A whole localized
* value (`fields: { pl: [...], en: [...] }`) is localized again after its locale
* is picked, so its rows keep the stored ids too.
*
* With `schema` (writeLocales passes the collection's or global's fields), a field
* that is itself localized (`localized: true` array, blocks or group) gets no
* stored ids: its rows belong to one locale and are never shared.
* undefined = leave the field out.
*/
export function localize(value: unknown, locale: string | undefined, existing: unknown, codes: string[]): unknown {
if (isLocalizedValue(value, codes)) {return locale ? value[locale] : undefined}
export function localize(
value: unknown,
locale: string | undefined,
existing: unknown,
codes: string[],
schema?: SeedSchema,
blockConfigs?: (slug: string) => readonly SeedField[] | undefined,
): unknown {
if (isLocalizedValue(value, codes)) {
const picked = locale ? value[locale] : undefined
return picked === undefined ? undefined : localize(picked, locale, existing, codes, schema, blockConfigs)
}
if (Array.isArray(value)) {
const rows = Array.isArray(existing) ? (existing as unknown[]) : []
return value.map((item, i) => {
const row = rows[i] as Record<string, unknown> | undefined
const out = localize(item, locale, row, codes)
const type = isPlainObject(item) && typeof item.blockType === 'string' ? item.blockType : undefined
const rowSchema = schema?.blocks ? (type && schema.blocks[type] ? { fields: schema.blocks[type] } : undefined) : schema
const out = localize(item, locale, row, codes, rowSchema, blockConfigs)
if (!isPlainObject(out) || !row?.id) {return out ?? null}
if (out.blockType !== undefined && row.blockType !== undefined && out.blockType !== row.blockType) {return out}
return { ...out, id: row.id }
@@ -45,9 +107,12 @@ export function localize(value: unknown, locale: string | undefined, existing: u
}
if (isPlainObject(value)) {
const ex = isPlainObject(existing) ? existing : {}
const fields = schema?.fields ? namedFields(schema.fields) : undefined
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(value)) {
const r = localize(v, locale, ex[k], codes)
const field = fields?.get(k)
// A localized field's stored rows belong to another locale — never reuse their ids.
const r = localize(v, locale, field?.localized ? undefined : ex[k], codes, schemaOf(field, blockConfigs), blockConfigs)
if (r !== undefined) {out[k] = r}
}
return out
@@ -132,6 +197,16 @@ export function editedSinceSeed({
export type SeedTarget = { collection: string; id: number | string } | { global: string }
/** The fields of a seed target (collection or global) and the config's shared blocks, for localize. */
export function seedSchemaOf(payload: BasePayload, target: SeedTarget): { blockConfigs: (slug: string) => readonly SeedField[] | undefined; schema?: SeedSchema } {
const config = payload.config as { blocks?: { fields: SeedField[]; slug: string }[]; collections?: { fields: SeedField[]; slug: string }[]; globals?: { fields: SeedField[]; slug: string }[] }
const owner = 'global' in target ? config.globals?.find((g) => g.slug === target.global) : config.collections?.find((c) => c.slug === target.collection)
return {
blockConfigs: (slug) => config.blocks?.find((b) => b.slug === slug)?.fields,
...(owner ? { schema: { fields: owner.fields } } : {}),
}
}
export type WriteLocalesOptions = {
/** Passed to every write — see docs/seeding.md § Context flags. */
context?: Record<string, unknown>
@@ -161,20 +236,21 @@ export async function writeLocales(
{ context = {}, draft = false }: WriteLocalesOptions = {},
): Promise<void> {
const { codes, defaultLocale } = localesOf(payload)
const { blockConfigs, schema } = seedSchemaOf(payload, target)
const local = (locale: string | undefined, rows: unknown) => localize(data, locale, rows, codes, schema, blockConfigs)
const write = (value: unknown, locale: string | undefined) => {
const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {}
return 'global' in target
? payload.updateGlobal({ slug: target.global as never, context, data: value as never, depth: 0, ...loc })
: payload.update({ id: target.id, collection: target.collection as never, context, data: value as never, depth: 0, ...loc })
}
await write(localize(data, defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft), codes), defaultLocale)
await write(local(defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft)), defaultLocale)
const others = codes.filter((c) => c !== defaultLocale)
if (!others.length) {return}
const rows = await readSeedTarget(payload, target, defaultLocale, draft)
for (const locale of others) {await write(localize(data, locale, rows, codes), locale)}
for (const locale of others) {await write(local(locale, rows), locale)}
}
/** True when a value has content (non-empty text, a number, true, or a nested one). */
/** Field types whose stored value is a choice, not text an editor wrote. */
const CHOICE_TYPES = new Set(['checkbox', 'date', 'number', 'point', 'radio', 'select'])
@@ -189,6 +265,7 @@ export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; t
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
}
/** True when a value has content (non-empty text, a number, true, or a nested one). */
export function hasContent(v: unknown): boolean {
if (typeof v === 'string') {return v.trim() !== ''}
if (typeof v === 'number' || v === true) {return true}
+212
View File
@@ -0,0 +1,212 @@
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 { ipalKit } 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: [
ipalKit({
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' }] })
})
})