Files
ipal-kit/test/fillEmptyLocales.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

147 lines
8.2 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.
/**
* Text written in one language fills the empty languages (cookie list, cookie
* review), never one that has its own text — through a REAL Payload (SQLite,
* pl + en + de). Plus the combined "Cookies" admin layout (config only).
*/
import type { Config, Field, GlobalConfig, Payload, Tab } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { suggestionFor } from '../src/modules/consent/scanner/merge.js'
import { addToCookieList } from '../src/modules/consent/scanner/sync.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
const i18n: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
{ code: 'de', label: 'Deutsch' },
],
}
type Row = { category?: string; duration?: null | string; id?: string; name: string; purpose?: null | string }
let payload: Payload
const list = async (locale: string) =>
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as { cookies?: Row[] }).cookies ?? []
const row = async (locale: string, name: string) => (await list(locale)).find((r) => r.name === name)
const save = async (locale: string, rows: Row[]) =>
payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: rows } as never, locale: locale as never })
beforeAll(async () => {
payload = await getPayload({
config: buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })],
secret: 'fill-locales-test-secret',
telemetry: false,
}),
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('fill empty locales — cookie list', () => {
test('a row added in Polish gets the same text in English and German', async () => {
await save('pl', [{ name: 'chat_id', category: 'functional', duration: '1 rok', purpose: 'Okno czatu' }])
expect(await row('en', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
expect(await row('de', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
})
test('a language with its own text is never overwritten; each can still be changed alone', async () => {
const en = await list('en')
await save('en', en.map((r) => (r.name === 'chat_id' ? { ...r, duration: '1 year', purpose: 'Chat window' } : r)))
expect(await row('en', 'chat_id')).toMatchObject({ duration: '1 year', purpose: 'Chat window' })
expect(await row('pl', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
expect(await row('de', 'chat_id')).toMatchObject({ purpose: 'Okno czatu' }) // already had text: kept
})
test('the source is the language just edited, not the default one', async () => {
const en = await list('en')
await save('en', [...en, { name: 'map_id', category: 'marketing', purpose: 'Embedded map' }])
expect((await row('pl', 'map_id'))?.purpose).toBe('Embedded map')
expect((await row('de', 'map_id'))?.purpose).toBe('Embedded map')
})
test('scanner writes: a language without its own text gets the default language’s text', async () => {
const s = suggestionFor({ name: 'x', purpose: { en: 'EN', pl: 'PL' }, retention: '1 day', source: 'project', storage: 'cookie' }, ['pl', 'en', 'de'])
expect(s.purpose).toEqual({ de: 'PL', en: 'EN', pl: 'PL' })
expect(s.retention).toEqual({ de: '1 day', en: '1 day', pl: '1 day' })
await addToCookieList({ entry: { name: 'only_pl', category: 'analytics', purpose: { pl: 'Tylko po polsku' } }, payload })
expect((await row('en', 'only_pl'))?.purpose).toBe('Tylko po polsku')
expect((await row('de', 'only_pl'))?.purpose).toBe('Tylko po polsku')
// The type of entry is stored once for every language.
await addToCookieList({ entry: { name: 'theme', category: 'necessary', purpose: { pl: 'Motyw' }, storage: 'localStorage' }, payload })
expect((await row('en', 'theme')) as unknown as { storage?: string }).toMatchObject({ purpose: 'Motyw', storage: 'localStorage' })
expect(((await row('pl', 'only_pl')) as unknown as { storage?: string }).storage).toBe('cookie')
})
})
describe('fill empty locales — cookie review', () => {
test('an entry described in English gets the text in the empty languages', async () => {
const created = (await payload.create({ collection: 'cookie-review' as never, data: { name: 'widget', storage: 'cookie' } as never, locale: 'pl' as never })) as { id: number }
await payload.update({ id: created.id, collection: 'cookie-review' as never, data: { purpose: 'Support widget', retention: '30 days' } as never, locale: 'en' as never })
const pl = (await payload.findByID({ id: created.id, collection: 'cookie-review' as never, fallbackLocale: false as never, locale: 'pl' as never })) as { purpose?: string; retention?: string }
expect(pl).toMatchObject({ purpose: 'Support widget', retention: '30 days' })
})
})
describe('options', () => {
const build = (extra: Record<string, unknown>) =>
iapl({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
const global = (c: Config, slug: string) => c.globals!.find((g) => g.slug === slug)!
const tabs = (g: GlobalConfig) => (g.fields.find((f) => f.type === 'tabs') as { tabs: Tab[] } & Field).tabs
test('fillEmptyLocales: false removes the hook; an object picks the fields', async () => {
expect(global(await build({}), 'cookie-settings').hooks?.afterChange).toHaveLength(1)
expect(global(await build({ fillEmptyLocales: false }), 'cookie-settings').hooks?.afterChange ?? []).toHaveLength(0)
expect(global(await build({ fillEmptyLocales: { 'cookie-settings': [] } }), 'cookie-settings').hooks?.afterChange ?? []).toHaveLength(0)
})
test('combined layout (default): one Cookies entry with Review and approve + Site check tabs', async () => {
const c = await build({ cookieScanner: { crawl: true } })
const cookies = global(c, 'cookie-settings')
expect(cookies.label).toEqual({ en: 'Cookies', pl: 'Cookies' })
const labels = tabs(cookies).map((t) => (t.label as Record<string, string>).en)
expect(labels.slice(-2)).toEqual(['Review and approve', 'Site check'])
expect(c.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toBe(false)
expect(global(c, 'cookie-crawl').admin?.group).toBe(false)
// Pages and API stay: the approval view and the endpoints are still there.
expect(c.admin?.components?.views?.ipalCookieApproval).toBeTruthy()
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-crawl')).toBe(true)
})
test('no crawl → no Site check tab; approval: false → the tab shows the scan and the list link only', async () => {
const c = await build({ cookieScanner: { approval: false } })
const review = tabs(global(c, 'cookie-settings')).at(-1)!
expect((review.label as Record<string, string>).en).toBe('Review and approve')
expect(JSON.stringify(review.fields)).toContain('"approval":false')
})
test("'separate' keeps every entry in the navigation and no extra tabs; the project's group wins", async () => {
const c = await build({ cookieScanner: { adminLayout: 'separate', crawl: true } })
expect(tabs(global(c, 'cookie-settings')).map((t) => (t.label as Record<string, string>).en)).not.toContain('Review and approve')
expect(c.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toEqual({ en: 'Privacy', pl: 'Prywatność' })
const own = await build({ cookieScanner: { collectionOverrides: { admin: { group: 'Legal' } } } })
expect(own.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toBe('Legal')
})
})