Compare commits

...
8 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 179d5b0d79 1.15.4 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.4" section (repair with SEED_UPDATE, live site with SEED_ONLY,
edited records and global arrays by hand). PROGRAMISTA §6: item 59. Reference site:
skills and the AGENTS.md pointer on 1.15.4; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f00fe3ad6 1.15.4
Version bump; the Unreleased section becomes 1.15.4: seeding whole localized arrays
keeps every language. What projects must update: nothing required; repairing records
an earlier seed wrote needs SEED_UPDATE=1 (locally first; on production with SEED_ONLY
and IPAL_SEED_ALLOW_PROD_UPDATE=1 after a backup), edited records and global arrays
by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:26 +01:00
Radosław Smoliński a79740cd44 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.
2026-11-12 15:35:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 00e814e3ca Seeder: whole localized arrays keep every language (1.15.4)
createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:33:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 4d1de4c66a 1.15.3 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.3" section. PROGRAMISTA §6: item 58. Reference site: skills
and the AGENTS.md pointer on 1.15.3; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 3edf8865ed 1.15.3
Version bump; the Unreleased section becomes 1.15.3: ipal-audit and ipal-doctor no
longer report the panel's bilingual labels (adminText(), { en, pl }) as hardcoded
text; public text is still reported. What projects must update: nothing required;
pnpm ipal:skills for the updated audit scripts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław Smoliński 594b958bb2 Merge claude/audit-admin-labels: the panel's bilingual labels are not hardcoded text
ipal-audit and the doctor's i18n-literals read the syntax tree (polish-literals.mjs,
a plain grep without TypeScript): adminText(), { en, pl } as label, singular, plural,
description, placeholder or group, a rowLabel() fallback and const x: AdminText in a
schema file are accepted. Still reported: every .tsx file, Polish-only labels, other
keys, anything under defaultValue. Reported from the Niezly Dandys project.
2026-11-05 12:59:28 +01:00
Radosław SmolińskiandClaude Opus 5.5 f73465c3bb ipal-audit, ipal-doctor: the panel's bilingual labels are not hardcoded text
"Hardcoded Polish text in code" (i18n-literals) grepped every string, so adminText() and { en, pl }
labels in schema files were reported, though AGENT.md 6.5a asks for them. polish-literals.mjs reads
the syntax tree with the project's TypeScript (a plain grep without it) and spares those forms in
schema files only; every .tsx file, Polish-only labels, other keys and defaultValue still fail.
Reported by Niezly Dandys (1.15.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:55:44 +01:00
21 changed files with 777 additions and 21 deletions
+36
View File
@@ -8,6 +8,42 @@ 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.
## 1.15.4
### 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;
repairing records an earlier seed already wrote: "What projects must update".
### What projects must update
- Nothing is required: seed scripts need no change.
- A project that seeded whole localized arrays (form fields with options, a page `layout`, a global array written as
`{ pl: [...], en: [...] }`) and lost languages: a plain re-run skips existing records (create-only), so rewrite them
with `SEED_UPDATE=1` — **locally first**, then check every language in the panel. On a live site only for the named
records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1 IPAL_SEED_ALLOW_PROD_UPDATE=1`, `SEED_DRY_RUN=1` first,
after a backup (Coolify). Records an editor changed since seeding are skipped — fix those in the panel. A global
array: `fillGlobal` fills empty fields only, so clear the field in the panel before the run, or fix it by hand.
## 1.15.3
### Fixed
- **ipal-audit and ipal-doctor no longer report the panel's own bilingual labels as hardcoded text.** "Hardcoded Polish
text in code" (`i18n-literals` in the doctor) flagged `adminText('Title', 'Tytuł')` and `{ en: 'Title', pl: 'Tytuł' }`,
the labels AGENT.md §6.5a asks for. The check now reads the syntax tree (`polish-literals.mjs`, with the project's
TypeScript; a plain grep without it). In a schema file — a `.ts` file under `collections/`, `globals/`, `fields/` or
`blocks/`, or one importing Payload's schema types — it accepts `adminText()`, `{ en, pl }` as `label`, `singular`,
`plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback and a `const x: AdminText`, also over several
lines. Still reported: every `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
### What projects must update
- Nothing is required.
- Run `pnpm ipal:skills` after upgrading, so the updated audit scripts reach the project: the **ipal-audit** skill runs
the project's own copy in `.agents/skills/ipal-audit/scripts` (`audit.sh`, `polish-literals.mjs`); `ipal-doctor` already
uses the plugin's.
## 1.15.2
### Fixed
+2 -1
View File
@@ -748,7 +748,8 @@ empty fields, without guessing, without numbered slots. You design the schema fo
(`ctaUrl` → "Cta Url"). Label 1–3 words, ≤ 30 characters.
- Texts are `{ en: '…', pl: '…' }` (one key per admin language of the project):
`label`, `admin.description`, option `label`, tab `label`, `labels.singular/plural`,
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`.
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`; shorthand `adminText('Title', 'Tytuł')` from
`@intecion/ipal-kit/blocks`. In a schema file `ipal-audit` accepts both; the same words in a component are an error.
- `admin.description` only when the label is not enough — one sentence ≤ 120 characters:
what it does / where it shows, with a format example (`'Section id for #links, e.g. "pricing".'`),
never how the code works (no component, function, env-var or package names).
+1 -1
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.15.2 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.15.4 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
+6
View File
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
## Design tokens (AGENT.md §6.11)
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
@@ -238,8 +238,10 @@ fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
// node polish-literals.mjs <dir> [<dir> …]
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'
const load = (from) => {
try {
return createRequire(from)('typescript')
} catch {
return null
}
}
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
if (!ts) process.exit(3)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
for (const file of files) {
const text = readFileSync(file, 'utf8')
if (!POLISH.test(text)) continue
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
const name = (el.propertyName ?? el.name).text
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
}
}
const isBilingual = (node) =>
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
// Is this literal one of the panel's own labels? Walks up from the literal.
const isAdminLabel = (literal) => {
let inside = false
for (let node = literal; node.parent; node = node.parent) {
const parent = node.parent
if (keyName(parent) === 'defaultValue') return false
if (inside) continue
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
const helper = helpers.get(parent.expression.text)
if (helper === 'adminText') inside = true
// rowLabel(fields, fallback): the fallback only, as { en, pl }
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
}
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
}
return inside
}
const seen = new Set()
const visit = (node) => {
if (ts.isImportDeclaration(node)) return
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
if (!seen.has(line)) {
seen.add(line)
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
}
}
ts.forEachChild(node, visit)
}
visit(source)
}
@@ -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`). |
+16
View File
@@ -230,6 +230,22 @@ and the browser tab shows the same separator.
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
text in a `.tsx` component is still reported.
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+2
View File
@@ -665,6 +665,8 @@ Do one item at a time, build, check. Order by importance:
| 55 | **1.15.0** — a production seed runs everything; no design tokens / block library; no site check | `SEED_ONLY` for production seeds (full seed refused, `IPAL_SEED_ALLOW_FULL=1` with the owner's OK); optional tokens.css + the block library (block by block, `migrate:create`); CookieButton above the footer (`avoid={false}`); `pnpm ipal:skills`; `pnpm exec ipal-doctor` (`--url`); new sites with `ipal-kit create` | CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md |
| 56 | **1.15.1** — a seed in Coolify's Terminal ends with exit 0 and no output (it stopped before Payload started) | `guardSeedExit()` first in every seed script, `seed.summary()` at the end; check `echo $?` after a seed; `pnpm ipal:skills` | CHANGELOG 1.15.1, seeding.md |
| 57 | **1.15.2** — ipal-doctor reports missing routes for a site whose pages live in `app/(site)` (not `(frontend)`), or a `notFoundView.tsx` | nothing to change; remove the temporary `layout-required` silence; two candidates → `layout.frontend` in `ipal-doctor.json`; `pnpm ipal:skills` | CHANGELOG 1.15.2, doctor.md |
| 58 | **1.15.3** — ipal-audit / ipal-doctor report `adminText()` or `{ en, pl }` panel labels as hardcoded Polish text | `pnpm ipal:skills`; remove a temporary `i18n-literals` silence added for such labels; public text is still reported | CHANGELOG 1.15.3, ipal-audit skill |
| 59 | **1.15.4** — a seeded form / layout / global array shows only the last language (whole localized arrays) | nothing to change in the seed; repair: `SEED_UPDATE=1` locally, on production `SEED_ONLY` + `SEED_UPDATE=1` + `IPAL_SEED_ALLOW_PROD_UPDATE=1` after a backup; edited records and global arrays by hand | CHANGELOG 1.15.4, seeding.md |
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`.
+1 -1
View File
@@ -110,7 +110,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` |
| | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` |
| | `blocks-tokens` | error / warning | from `ipal-audit`: hex colours, the token standard not wired, `ipal-tokens --check` |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `ipal-audit` skill) |
| | `audit:<title>` | as reported | every other `ipal-audit --quick` finding, one per file |
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `ipal-seo-check` error and warning |
| deep | `deep-status` | error | the deep check could not finish |
+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:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.15.2",
"version": "1.15.4",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
## Design tokens (AGENT.md §6.11)
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
@@ -238,8 +238,10 @@ fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
// node polish-literals.mjs <dir> [<dir> …]
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'
const load = (from) => {
try {
return createRequire(from)('typescript')
} catch {
return null
}
}
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
if (!ts) process.exit(3)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
for (const file of files) {
const text = readFileSync(file, 'utf8')
if (!POLISH.test(text)) continue
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
const name = (el.propertyName ?? el.name).text
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
}
}
const isBilingual = (node) =>
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
// Is this literal one of the panel's own labels? Walks up from the literal.
const isAdminLabel = (literal) => {
let inside = false
for (let node = literal; node.parent; node = node.parent) {
const parent = node.parent
if (keyName(parent) === 'defaultValue') return false
if (inside) continue
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
const helper = helpers.get(parent.expression.text)
if (helper === 'adminText') inside = true
// rowLabel(fields, fallback): the fallback only, as { en, pl }
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
}
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
}
return inside
}
const seen = new Set()
const visit = (node) => {
if (ts.isImportDeclaration(node)) return
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
if (!seen.has(line)) {
seen.add(line)
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
}
}
ts.forEachChild(node, visit)
}
visit(source)
}
@@ -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`). |
@@ -230,6 +230,22 @@ and the browser tab shows the same separator.
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
text in a `.tsx` component is still reported.
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.15.2 — agent guide
## ipal-kit 1.15.4 — agent guide
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
+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}
+180
View File
@@ -0,0 +1,180 @@
import { execFileSync, spawnSync } from 'node:child_process'
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, test } from 'vitest'
import { parseToolOutput } from '../src/modules/doctor/rules/tooling.js'
import { runDoctor } from '../src/modules/doctor/run.js'
const packageRoot = path.resolve(import.meta.dirname, '..')
const scripts = path.join(packageRoot, 'docs/agent/skills/ipal-audit/scripts')
let dirs: string[] = []
function project(files: Record<string, string>): string {
const root = mkdtempSync(path.join(tmpdir(), 'ipal-polish-'))
dirs.push(root)
for (const [rel, content] of Object.entries(files)) {
const file = path.join(root, rel)
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, content)
}
return root
}
/** `file:line` of every finding of the check. */
function polish(files: Record<string, string>): string[] {
const root = project(files)
const out = execFileSync(process.execPath, [path.join(scripts, 'polish-literals.mjs'), 'src'], { cwd: root, encoding: 'utf8' })
return out.split('\n').filter(Boolean).map((l) => l.match(/^(.+?:\d+):/)?.[1] ?? l)
}
const HELPER = "import { adminText, rowLabel } from '@intecion/ipal-kit/blocks'\n"
afterEach(() => {
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
dirs = []
})
describe('hardcoded Polish text: the panel labels are not public text', () => {
test('adminText() in a schema file, on one line and over several', () => {
expect(polish({
'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [
{ name: 'title', type: 'text', label: adminText('Title', 'Tytuł') },
{ name: 'heading', type: 'text', label: adminText(
'Heading',
'Nagłówek',
) },
] }\n`,
'src/globals/Header.ts': `${HELPER}export const Header = { slug: 'header', label: adminText('Header', 'Nagłówek') }\n`,
})).toEqual([])
})
test('{ en, pl } as label, singular, plural, description, placeholder, group, option label — one line and several', () => {
expect(polish({
'src/globals/Company.ts': `export const Company = { slug: 'company', admin: { group: { en: 'Company', pl: 'Dane firmy żółć' } }, fields: [
{ name: 'areas', type: 'array', labels: { singular: { en: 'Area', pl: 'Obszar działania' }, plural: {
en: 'Areas',
pl: 'Obszary działania',
} }, fields: [] },
{ name: 'kind', type: 'select', label: {
en: 'Social profiles',
pl: 'Profile społecznościowe',
}, admin: { description: { en: 'Where it shows', pl: 'Gdzie się wyświetla' }, placeholder: { en: 'Pick', pl: 'Wybierz coś ładnego ł' } }, options: [{ label: { en: 'Title', pl: 'Tytuł' }, value: 't' }] },
] }\n`,
})).toEqual([])
})
test('an aliased import, rowLabel fallback, a typed AdminText constant, a file importing Payload types', () => {
expect(polish({
'src/fields/title.ts': `import { adminText as t, rowLabel } from '@intecion/ipal-kit/blocks'
export const a = { label: t('Title', 'Tytuł'), admin: { components: rowLabel('x', { en: 'Item', pl: 'Pozycja ż' }) } }\n`,
'src/lib/schema.ts': `import type { AdminText } from '@intecion/ipal-kit'
import type { Field } from 'payload'
const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
export const f: Field = { name: 'title', type: 'text', label: { en: 'Title', pl: 'Tytuł' } }
export const g = TITLE\n`,
})).toEqual([])
})
test('comments never count', () => {
expect(polish({ 'src/components/A.tsx': "// 'Nagłówek'\n/* \"Tytuł\" */\nexport const A = () => null\n" })).toEqual([])
})
})
describe('hardcoded Polish text: public strings are still reported', () => {
test('a public component with the same words, whichever form it uses', () => {
expect(polish({
'src/components/Hero.tsx': `${HELPER}export const Hero = () => (
<section aria-label="Nagłówek">
<Title text={'Tytuł'} label={adminText('Title', 'Tytuł')} other={{ label: { en: 'Heading', pl: 'Nagłówek' } }} />
<Multi
caption={{
en: 'Social profiles',
pl: 'Profile społecznościowe',
}}
/>
</section>
)\n`,
})).toEqual(['src/components/Hero.tsx:3', 'src/components/Hero.tsx:4', 'src/components/Hero.tsx:8'])
})
test('a block component next to its schema; a helper in lib without schema types', () => {
expect(polish({
'src/blocks/Hero/Component.tsx': "export const Hero = () => <h1 title=\"Nagłówek\" />\n",
'src/blocks/Hero/config.ts': `${HELPER}export const Hero = { slug: 'hero', label: adminText('Heading', 'Nagłówek') }\n`,
'src/lib/texts.ts': "export const labels = { label: { en: 'Title', pl: 'Tytuł' } }\n",
})).toEqual(['src/blocks/Hero/Component.tsx:1', 'src/lib/texts.ts:1'])
})
test('in a schema file: Polish only, another key, defaultValue, a lookalike helper, a client file', () => {
expect(polish({
'src/collections/Bad.ts': `${HELPER}export const Bad = { slug: 'bad', fields: [
{ name: 'a', label: 'Tytuł' },
{ name: 'b', label: { pl: 'Tytuł' } },
{ name: 'c', heading: { en: 'Title', pl: 'Tytuł' } },
{ name: 'd', defaultValue: 'Nagłówek' },
{ name: 'e', defaultValue: adminText('Heading', 'Nagłówek') },
{ name: 'f', defaultValue: {
en: 'Heading',
pl: 'Nagłówek',
} },
] }\n`,
'src/globals/Client.ts': `'use client'\n${HELPER}export const x = { label: adminText('Title', 'Tytuł') }\n`,
'src/globals/Lookalike.ts': "const adminText = (a: string, b: string) => b\nexport const x = { label: adminText('Title', 'Tytuł') }\n",
})).toEqual([
'src/collections/Bad.ts:3', 'src/collections/Bad.ts:4', 'src/collections/Bad.ts:5', 'src/collections/Bad.ts:6', 'src/collections/Bad.ts:7', 'src/collections/Bad.ts:10',
'src/globals/Client.ts:3',
'src/globals/Lookalike.ts:2',
])
})
test('adminText outside a schema file is reported; rowLabel only spares its { en, pl } fallback', () => {
expect(polish({
'src/fields/row.ts': `${HELPER}export const a = rowLabel('x', 'Pozycja ż')\nexport const b = rowLabel('Żółć', { en: 'Item', pl: 'Pozycja ż' })\n`,
'src/lib/text.ts': `${HELPER}export const t = adminText('Title', 'Tytuł')\n`,
})).toEqual(['src/fields/row.ts:2', 'src/fields/row.ts:3', 'src/lib/text.ts:2'])
})
})
describe('ipal-audit and ipal-doctor agree', () => {
const files = {
'package.json': JSON.stringify({ name: 'examplepl-web' }),
'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [
{ name: 'title', label: adminText('Title', 'Tytuł') },
{ name: 'heading', label: {
en: 'Heading',
pl: 'Nagłówek',
} },
] }\n`,
'src/components/Public.tsx': `${HELPER}export const Public = () => <p title="Nagłówek">{adminText('Title', 'Tytuł')}</p>\n`,
}
test('audit.sh and the i18n-literals rule report the public component only', async () => {
const root = project(files)
const audit = spawnSync('bash', [path.join(scripts, 'audit.sh'), '--quick'], { cwd: root, encoding: 'utf8' })
const line = parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')
expect(line?.level).toBe('error')
expect(line?.items).toEqual([`src/components/Public.tsx:2:export const Public = () => <p title="Nagłówek">{adminText('Title', 'Tytuł')}</p>`])
const report = await runDoctor({ offline: true, only: ['audit'], packageRoot, root, writeSeen: false })
const polishFindings = report.findings.filter((f) => f.rule === 'i18n-literals' && f.message.startsWith('hardcoded Polish'))
expect(polishFindings.map((f) => f.file)).toEqual(['src/components/Public.tsx'])
})
test('without TypeScript in reach the check still runs, as a plain grep', () => {
const copy = project({ 'x.txt': '' })
cpSync(scripts, path.join(copy, 'scripts'), { recursive: true })
const root = project(files)
const env = { ...process.env, NODE_PATH: '' } // pnpm's bin shims put its store on NODE_PATH
const alone = spawnSync(process.execPath, [path.join(copy, 'scripts/polish-literals.mjs'), 'src'], { cwd: root, encoding: 'utf8', env })
expect(alone.status).toBe(3)
const audit = spawnSync('bash', [path.join(copy, 'scripts/audit.sh'), '--quick'], { cwd: root, encoding: 'utf8', env })
expect(parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')?.items.join('\n')).toContain('src/components/Public.tsx')
})
test('audit.sh passes when only schema labels hold Polish', () => {
const { 'src/components/Public.tsx': _, ...schemaOnly } = files
const audit = spawnSync('bash', [path.join(scripts, 'audit.sh'), '--quick'], { cwd: project(schemaOnly), encoding: 'utf8' })
expect(parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')).toBeUndefined()
})
})
+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' }] })
})
})