Files
ipal-kit/test/seed.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 3645e61f7d Fixes from the reference site: 404 page unlisted, own-origin media, fillGlobal defaults, switcher docs
- sitemap, llms.txt and the site index leave out the page assigned as the 404
  page (unlistedPageIds, exported); it stays when it is also the homepage
- buildImagesConfig: in production with R2_PUBLIC_URL empty, allow the site's
  own /api/media/file/** so next/image no longer answers 400
- fillGlobal: a choice field (select, radio, checkbox, number, date) still at its
  defaultValue counts as empty; text is never overwritten
- docs: LanguageSwitcher renderLabel needs a 'use client' wrapper (i18n.md,
  ipal-site, ipal-setup, api.md)

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

350 lines
17 KiB
TypeScript

import type { 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, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { createSeeder, editedSinceSeed, isLocalDatabase, seedHash } from '../src/exports/seed.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
const flush = () => new Promise((r) => setTimeout(r, 0))
describe('isLocalDatabase', () => {
test.each([
['file:./dev.db', true],
['file::memory:', true],
['./payload.sqlite', true],
['postgres://u:p@localhost:5432/app', true],
['postgres://u:[email protected]/app', true],
['postgres://u:p@[::1]:5432/app', true],
['postgres:///app', true],
['postgres://u:p@x/app?host=/var/run/postgresql', true],
['postgres://u:p@db:5432/app', false],
['mongodb+srv://u:[email protected]/app', false],
['mongodb://a:1,b:2/app', false],
['', false],
[undefined, false],
])('%s → %s', (url, local) => {
expect(isLocalDatabase(url, { localHosts: [] })).toBe(local)
})
test('extra local hosts (option or SEED_LOCAL_HOSTS)', () => {
expect(isLocalDatabase('postgres://u:p@db:5432/app', { localHosts: ['db'] })).toBe(true)
vi.stubEnv('SEED_LOCAL_HOSTS', 'db, postgres')
expect(isLocalDatabase('postgres://u:p@postgres:5432/app')).toBe(true)
vi.unstubAllEnvs()
})
})
describe('editedSinceSeed / seedHash', () => {
const at = (s: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, s)).toISOString()
test('timestamps: inside the window = untouched, later = edited', () => {
expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(5) }, hashField: false })).toBeNull()
expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(500) }, hashField: false })).toMatch(/updated 500s after creation/)
expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(500) }, hashField: false, untouchedSeconds: 600 })).toBeNull()
expect(editedSinceSeed({ doc: {}, hashField: false })).toBe('no createdAt/updatedAt')
})
test('a stored hash decides over timestamps', () => {
const doc = { createdAt: at(0), seedHash: seedHash({ a: 1 }), updatedAt: at(9000) }
expect(editedSinceSeed({ currentHash: seedHash({ a: 1 }), doc })).toBeNull()
expect(editedSinceSeed({ currentHash: seedHash({ a: 2 }), doc })).toBe('seedHash differs')
})
test('seedHash ignores key order, row ids and nulls', () => {
// eslint-disable-next-line perfectionist/sort-objects -- key order is what this checks
expect(seedHash({ a: 1, b: [{ id: 'x', t: 'q' }], c: null })).toBe(seedHash({ b: [{ t: 'q' }], a: 1 }))
expect(seedHash({ a: 1 })).not.toBe(seedHash({ a: 2 }))
})
})
/** createSeeder against a real (SQLite) Payload with pl/en and localization.fallback on. */
describe('createSeeder', () => {
let payload: Payload
const lines: string[] = []
const log = (line: string) => {
lines.push(line)
}
const seeder = (opts: Parameters<typeof createSeeder>[1] = {}) => createSeeder(payload, { dryRun: false, log, update: false, ...opts })
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
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 },
{
name: 'rows',
type: 'array',
fields: [
{ name: 'text', type: 'text', localized: true },
{ name: 'page', type: 'relationship', relationTo: 'pages' },
],
},
],
versions: { drafts: true },
},
{
slug: 'posts',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', localized: true },
{ name: 'seedHash', type: 'text', admin: { hidden: true } },
],
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
globals: [
{
slug: 'look',
fields: [
{ name: 'mode', type: 'select', defaultValue: 'light', options: ['light', 'dark', 'system'] },
{ name: 'toggle', type: 'checkbox', defaultValue: true },
{ name: 'greeting', type: 'text', defaultValue: 'Hello' },
],
},
{
slug: 'header',
fields: [
{ name: 'tagline', type: 'text', localized: true },
{ name: 'phone', type: 'text' },
{ name: 'links', type: 'array', fields: [{ name: 'label', type: 'text', localized: true }] },
],
},
],
localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] },
plugins: [ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seed-test-secret',
telemetry: false,
})
payload = await getPayload({ config })
}, 60_000)
afterEach(() => {
lines.length = 0
vi.restoreAllMocks()
vi.unstubAllEnvs()
vi.stubEnv('DATABASE_URI', 'file::memory:')
})
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
const readPage = (id: number | string, locale: 'en' | 'pl') =>
payload.findByID({ id, collection: 'pages', depth: 0, draft: true, fallbackLocale: false as never, locale })
test('creates missing pages in every locale, resolves $page links, keeps row ids, then skips', async () => {
const PAGES = [
{
slug: { en: 'home', pl: 'start' },
rows: [{ page: { $page: 'kontakt' }, text: { en: 'Write to us', pl: 'Napisz do nas' } }, { text: { en: 'Second', pl: 'Drugi' } }],
title: { en: 'Home', pl: 'Strona główna' },
},
{ slug: { en: 'contact', pl: 'kontakt' }, title: { en: 'Contact', pl: 'Kontakt' } },
]
const seed = seeder()
const results = await seed.upsertBySlug('pages', PAGES)
expect(results.map((r) => r.status)).toEqual(['create', 'create'])
const [home, contact] = results
const pl = await readPage(home.id!, 'pl')
const en = await readPage(home.id!, 'en')
expect(pl.title).toBe('Strona główna')
expect(en.title).toBe('Home')
expect(en.slug).toBe('home')
expect((pl.rows as { id: string }[]).map((r) => r.id)).toEqual((en.rows as { id: string }[]).map((r) => r.id))
expect((pl.rows as { text: string }[])[0].text).toBe('Napisz do nas')
expect((en.rows as { page: unknown; text: string }[])[0]).toMatchObject({ page: contact.id, text: 'Write to us' })
const again = seeder()
expect((await again.upsertBySlug('pages', PAGES)).map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)'])
expect(again.summary()).toEqual({ created: 0, errors: 0, notListed: 0, skipped: 2, skippedEdited: 0, updated: 0 })
expect(lines.join('\n')).toMatch(/skip \(exists\)\s+pages "start"/)
})
test('fallbackLocale: false — a locale missing from the seed is not filled with the default text', async () => {
const r = await seeder().upsertBySlug('pages', { slug: { pl: 'tylko-pl' }, title: { pl: 'Tylko po polsku' } })
const en = await readPage(r.id!, 'en')
expect(en.title ?? null).toBeNull()
})
test('dry run writes nothing and reports the plan', async () => {
const seed = seeder({ dryRun: true })
const r = await seed.upsertBySlug('pages', { slug: { pl: 'nowa' }, rows: [{ page: { $page: 'nowa' } }], title: { pl: 'Nowa' } })
expect(r.status).toBe('create')
expect((await payload.find({ collection: 'pages', where: { slug: { equals: 'nowa' } } })).totalDocs).toBe(0)
expect(seed.summary().created).toBe(1)
expect(lines.join('\n')).toMatch(/DRY RUN/)
})
test('update: untouched records are updated, records edited since seeding are skipped', async () => {
const first = await seeder().upsertBySlug('pages', { slug: { pl: 'oferta' }, title: { en: 'Offer', pl: 'Oferta' } })
const edited = await seeder().upsertBySlug('pages', { slug: { pl: 'o-nas' }, title: { pl: 'O nas' } })
// An editor saves "o-nas" 10 minutes after it was created.
vi.useFakeTimers({ now: Date.now() + 600_000, toFake: ['Date'] })
await payload.update({ id: edited.id!, collection: 'pages', data: { title: 'O nas — poprawione' }, locale: 'pl' })
vi.useRealTimers()
const seed = seeder({ update: true })
const up = await seed.upsertBySlug('pages', [
{ slug: { pl: 'oferta' }, title: { en: 'Our offer', pl: 'Nasza oferta' } },
{ slug: { pl: 'o-nas' }, title: { pl: 'O nas (seed)' } },
])
expect(up.map((r) => r.status)).toEqual(['update', 'skip (edited)'])
expect(up[1].note).toMatch(/after creation/)
expect((await readPage(first.id!, 'en')).title).toBe('Our offer')
expect((await readPage(edited.id!, 'pl')).title).toBe('O nas — poprawione')
expect(seed.summary()).toMatchObject({ skippedEdited: 1, updated: 1 })
})
test('hash field: repeated updates while untouched; an editor change is detected', async () => {
const created = await seeder().upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post', pl: 'Wpis' } })
vi.useFakeTimers({ now: Date.now() + 600_000, toFake: ['Date'] })
// Timestamps alone would call this edited — the stored hash says it is untouched.
expect((await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 2', pl: 'Wpis 2' } })).status).toBe('update')
expect((await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 3', pl: 'Wpis 3' } })).status).toBe('update')
await payload.update({ id: created.id!, collection: 'posts', data: { title: 'Changed by an editor' }, locale: 'en' })
const r = await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 4', pl: 'Wpis 4' } })
vi.useRealTimers()
expect(r).toMatchObject({ note: 'seedHash differs', status: 'skip (edited)' })
expect((await payload.findByID({ id: created.id!, collection: 'posts', locale: 'en' })).title).toBe('Changed by an editor')
})
test('upsertBy matches a natural key', async () => {
expect((await seeder().upsertBy('posts', { title: 'Formularz' }, { slug: 'formularz', title: 'Formularz' })).status).toBe('create')
expect((await seeder().upsertBy('posts', { title: 'Formularz' }, { slug: 'x', title: 'Formularz' })).status).toBe('skip (exists)')
})
test('fillGlobal fills only empty fields, in every locale', async () => {
await payload.updateGlobal({ slug: 'header', data: { phone: '+48 600 000 000' } })
const seed = seeder()
const r = await seed.fillGlobal('header', {
links: [{ label: { en: 'Contact', pl: 'Kontakt' } }],
phone: '+48 111 111 111',
tagline: { en: 'Hello', pl: 'Cześć' },
})
expect(r.status).toBe('create')
expect(r.note).toBe('empty fields filled: links, tagline')
const pl = await payload.findGlobal({ slug: 'header', fallbackLocale: false as never, locale: 'pl' })
const en = await payload.findGlobal({ slug: 'header', fallbackLocale: false as never, locale: 'en' })
expect(pl.phone).toBe('+48 600 000 000')
expect(pl.tagline).toBe('Cześć')
expect(en.tagline).toBe('Hello')
expect((en.links as { id: string; label: string }[])[0]).toMatchObject({ id: (pl.links as { id: string }[])[0].id, label: 'Contact' })
expect((await seeder().fillGlobal('header', { tagline: { pl: 'Inne' } })).status).toBe('skip (exists)')
})
test('fillGlobal: a choice still at its default counts as unset; text is never overwritten', async () => {
await payload.updateGlobal({ slug: 'look' as never, data: {} as never }) // first save stores the defaults
const first = await seeder().fillGlobal('look', { greeting: 'Hi', mode: 'system', toggle: false })
expect(first).toMatchObject({ status: 'create' })
expect(first.note).toBe('empty fields filled: mode, toggle')
const look = (await payload.findGlobal({ slug: 'look' as never })) as { greeting: string; mode: string; toggle: boolean }
expect(look).toMatchObject({ greeting: 'Hello', mode: 'system', toggle: false })
// An editor's choice that differs from the default stays.
await payload.updateGlobal({ slug: 'look' as never, data: { mode: 'dark' } as never })
await seeder().fillGlobal('look', { mode: 'system' })
expect(((await payload.findGlobal({ slug: 'look' as never })) as { mode: string }).mode).toBe('dark')
})
test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => {
vi.stubEnv('NODE_ENV', 'production')
const only = ['pages:kontakt']
expect(() => seeder({ only, update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/)
expect(() => seeder({ only })).not.toThrow() // create-only of listed records is always allowed
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
expect(seeder({ only, update: true }).update).toBe(true)
expect(lines.join('\n')).toMatch(/Did you back it up/)
vi.unstubAllEnvs()
vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app')
expect(() => seeder({ only, update: true })).toThrow(/update refused: the database is not local/)
expect(() => seeder({ guard: { localHosts: ['db'] }, update: true })).not.toThrow()
expect(() => seeder({ guard: false, update: true })).not.toThrow()
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
expect(() => seeder({ force: true, only, update: true })).toThrow(/force refused/)
})
test('after launch: a full seed of a live database is refused without a record list', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => seeder()).toThrow(/full seed refused: NODE_ENV=production[\s\S]*SEED_ONLY/)
expect(() => seeder({ dryRun: true })).not.toThrow() // a dry run only prints the plan
expect(() => seeder({ only: ['global:header'] })).not.toThrow()
vi.stubEnv('SEED_ONLY', 'pages:kontakt, global:header')
expect(seeder().only).toEqual(['pages:kontakt', 'global:header'])
vi.unstubAllEnvs()
vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app')
expect(() => seeder()).toThrow(/full seed refused: the database is not local/)
expect(() => seeder({ guard: { allowFull: true } })).not.toThrow()
vi.stubEnv('IPAL_SEED_ALLOW_FULL', '1')
expect(() => seeder()).not.toThrow()
expect(() => seeder({ guard: false })).not.toThrow()
})
test('only: records off the list are reported and never touched', async () => {
const seed = seeder({ only: ['posts:listed', 'global:header'] })
const [listed, other] = await seed.upsertBySlug('posts', [
{ slug: 'listed', title: 'Listed' },
{ slug: 'not-listed', title: 'Not listed' },
])
expect(listed.status).toBe('create')
expect(other.status).toBe('skip (not listed)')
expect((await seed.upsertBy('posts', { slug: 'other' }, { title: 'X' })).status).toBe('skip (not listed)')
expect((await seed.fillGlobal('header', { phone: '+48 2' })).status).not.toBe('skip (not listed)')
const { docs } = await payload.find({ collection: 'posts', where: { slug: { in: ['not-listed', 'other'] } } })
expect(docs).toHaveLength(0)
expect(seed.summary().notListed).toBe(2)
const whole = seeder({ only: ['posts:*'] })
expect((await whole.upsertBySlug('posts', { slug: 'any-post', title: 'Any' })).status).toBe('create')
expect((await whole.fillGlobal('header', { tagline: 'x' })).status).toBe('skip (not listed)')
})
test('env defaults: SEED_DRY_RUN, SEED_UPDATE', () => {
vi.stubEnv('SEED_DRY_RUN', '1')
vi.stubEnv('SEED_UPDATE', '1')
const s = createSeeder(payload, { log })
expect(s.dryRun).toBe(true)
expect(s.update).toBe(true)
})
test('seed writes skip IndexNow; a normal save still pings', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 }))
vi.stubEnv('NODE_ENV', 'production')
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl')
vi.stubEnv('INDEXNOW_KEY', 'k123')
const seed = seeder({ only: ['pages:*', 'global:header'], update: true })
await seed.upsertBySlug('pages', [
{ slug: { en: 'news', pl: 'aktualnosci' }, _status: 'published', title: { en: 'News', pl: 'Aktualności' } },
{ slug: { pl: 'oferta' }, _status: 'published', title: { pl: 'Oferta po aktualizacji' } },
])
await seed.fillGlobal('header', { phone: '+48 1' })
await flush()
await flush()
expect(fetchSpy).not.toHaveBeenCalled()
const page = await payload.create({ collection: 'pages', data: { slug: 'zwykla', _status: 'published', title: 'Zwykła' }, locale: 'pl' })
await flush()
await flush()
expect(fetchSpy).toHaveBeenCalled()
expect(page.id).toBeDefined()
})
})