Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
755f510c9f | ||
|
|
970307f3ab | ||
|
|
c7e198fd92 | ||
|
|
748ef9286f | ||
|
|
179d5b0d79 | ||
|
|
2f00fe3ad6 | ||
|
|
a79740cd44 | ||
|
|
00e814e3ca | ||
|
|
4d1de4c66a | ||
|
|
3edf8865ed | ||
|
|
594b958bb2 | ||
|
|
f73465c3bb |
@@ -8,6 +8,65 @@ 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.5
|
||||
|
||||
### Fixed
|
||||
- **Seeding a required field with references** (`createSeeder`, `upsertBySlug` / `upsertBy`): a page whose required
|
||||
`layout` holds a `{ $page }` or `{ $form }` reference can be created. The first pass used to leave the whole field out,
|
||||
so validation rejected the record ("The following field is invalid: … > Layout") while the dry run reported a create.
|
||||
Now references to records that exist are resolved in the first pass, so the field is written complete. A link to a
|
||||
page created later in the same call is filled in the second pass, and a record whose required field needs that page
|
||||
waits until it exists. Required links in a cycle, and links to a page or form that never appears, are an error with
|
||||
nothing written. The dry run now reports the same outcome, including a missing form. Seed scripts need no change.
|
||||
|
||||
### Changed
|
||||
- **A stricter dry run:** `SEED_DRY_RUN=1` with a `{ $form }` to a form that neither exists nor is seeded earlier in the
|
||||
same run is now an error, as the real run would be (before, the dry run printed a placeholder and reported a create).
|
||||
The same holds for a `{ $page }` that never appears.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required: seed scripts need no change.
|
||||
- A seed with a required reference cycle (two new pages whose required fields link to each other) now stops with a
|
||||
clear error naming the pages, and nothing is written for them; make one of the links optional or seed one page
|
||||
first. Before, such a run could look successful in the dry run and fail on validation in the real one.
|
||||
- A dry run that now reports a missing form or page: seed that record first (or create it in the panel), then run again.
|
||||
|
||||
## 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
@@ -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).
|
||||
|
||||
@@ -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.5 ("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:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -558,13 +558,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
|
||||
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
|
||||
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
|
||||
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
|
||||
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
|
||||
| `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,30 @@ 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.
|
||||
|
||||
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
|
||||
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
|
||||
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
|
||||
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
|
||||
an error. Seed that record first or create it in the panel.
|
||||
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
|
||||
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
|
||||
|
||||
## 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):
|
||||
|
||||
@@ -665,6 +665,9 @@ 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 |
|
||||
| 60 | **1.15.5** — a seeded page with a required layout linking to a page or form fails validation ("… > Layout") | nothing to change in the seed; run it again (dry run first); a missing `$form` / `$page` is now an error in the dry run too; a required link cycle: make one link optional | CHANGELOG 1.15.5, 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
@@ -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 |
|
||||
|
||||
+18
-2
@@ -197,14 +197,30 @@ 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:
|
||||
is an error for that record, never an empty relation.
|
||||
|
||||
**References and required fields.** A new record is created complete, so a required field (a `layout` whose block
|
||||
links to a page or form) passes validation:
|
||||
- a reference to a record that exists — or was created earlier in the run — becomes its ID in the first write;
|
||||
- a `{ $page }` to a page created later **in the same `upsertBySlug` call** is filled in the second pass; when the
|
||||
field that holds it is required, the record waits until that page exists. Pages that link to each other belong in
|
||||
one call (an array);
|
||||
- required links in a cycle (A needs B, B needs A) and a reference to a page or form that does not exist and is not
|
||||
planned are an **error** for those records, and nothing is written for them. Make one of the links optional, or seed
|
||||
one of the pages first;
|
||||
- the dry run reports the same outcome. A form planned earlier in the same dry run counts as existing. Only a required
|
||||
cycle shows up first in the real run, because the dry run does not validate fields. Ready pages made of library blocks:
|
||||
`pageTemplates` in [block-library.md](./block-library.md#page-templates).
|
||||
|
||||
| Method | What it does |
|
||||
|---|---|
|
||||
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
|
||||
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (references to existing records resolved, links to pages later in the call filled in pass 2; a required one waits for its page), then every record gets its full content, so pages can link to each other in any order. Unknown targets and required cycles: error, nothing written |
|
||||
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
|
||||
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. A field that already holds exactly the seeded value is not written (`skip (exists)`), so re-running a seed of defaults changes nothing. With `update` and an untouched global: every seeded field |
|
||||
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.15.2",
|
||||
"version": "1.15.5",
|
||||
"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)
|
||||
}
|
||||
@@ -558,13 +558,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
|
||||
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
|
||||
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
|
||||
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
|
||||
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
|
||||
| `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,30 @@ 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.
|
||||
|
||||
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
|
||||
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
|
||||
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
|
||||
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
|
||||
an error. Seed that record first or create it in the panel.
|
||||
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
|
||||
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
|
||||
|
||||
## 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
@@ -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.5 — 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:
|
||||
|
||||
+107
-26
@@ -172,11 +172,22 @@ const formRef = (v: object): string | undefined => {
|
||||
return typeof ref === 'string' ? ref : undefined
|
||||
}
|
||||
|
||||
/** True when the value holds a { $page } or { $form } reference — such fields are written once refs resolve. */
|
||||
const hasRef = (v: unknown): boolean =>
|
||||
Array.isArray(v)
|
||||
? v.some(hasRef)
|
||||
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
|
||||
const pageRef = (v: object): string | undefined => {
|
||||
const ref = (v as { $page?: unknown }).$page
|
||||
return typeof ref === 'string' ? ref : undefined
|
||||
}
|
||||
|
||||
/** The default-locale slugs of the { $page } references a value holds. */
|
||||
const pageRefsIn = (v: unknown, out = new Set<string>()): Set<string> => {
|
||||
if (Array.isArray(v)) {v.forEach((x) => pageRefsIn(x, out))}
|
||||
else if (v && typeof v === 'object') {
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {out.add(ref)}
|
||||
else {Object.values(v).forEach((x) => pageRefsIn(x, out))}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder {
|
||||
// Payload is up (the caller passed it in) — the run's exit guard, if any, now waits for summary()
|
||||
@@ -229,6 +240,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
const localeKeys = codes.length ? codes : [undefined]
|
||||
const counts: Record<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, 'skip (not listed)': 0, update: 0 }
|
||||
const pageIds = new Map<string, number | string>()
|
||||
/** Forms planned for creation in a dry run, by title — a later { $form } to them is not an error. */
|
||||
const plannedForms = new Set<string>()
|
||||
|
||||
log(
|
||||
`${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'} · ${only ? `only: ${only.join(', ')}` : 'all records'}\n`,
|
||||
@@ -278,11 +291,12 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
if (form !== undefined) {
|
||||
const id = await findId(formsCollection, { title: form })
|
||||
if (id !== undefined) {return id}
|
||||
if (lenient || dryRun) {return `(form:${form})`}
|
||||
// A dry run reports what the real run would do: a form planned earlier in this run will exist.
|
||||
if (lenient || (dryRun && plannedForms.has(form))) {return `(form:${form})`}
|
||||
throw new Error(`$form "${form}" not found — seed that form first or create it in the panel`)
|
||||
}
|
||||
const ref = (v as { $page?: unknown }).$page
|
||||
if (typeof ref === 'string') {
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {
|
||||
let id = pageIds.get(ref)
|
||||
if (id === undefined) {
|
||||
id = await findId(pagesCollection, { slug: ref })
|
||||
@@ -299,6 +313,34 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* The first-pass value of a record being created: references to records that exist now become their ids,
|
||||
* so a required field (a layout whose block links to a page) is written complete. A { $page } to a page
|
||||
* planned in the same call and not created yet (`forward`) becomes null and is collected; pass 2 writes it.
|
||||
* Any other unknown target throws — nothing is written for that record.
|
||||
*/
|
||||
const resolveForCreate = async (v: unknown, forward: Set<string>, planned: Set<string>): Promise<unknown> => {
|
||||
if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveForCreate(x, forward, planned)))}
|
||||
if (!v || typeof v !== 'object') {return v}
|
||||
if (formRef(v) !== undefined) {return resolveRefs(v)}
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {
|
||||
const known = pageIds.get(ref) ?? (await findId(pagesCollection, { slug: ref }))
|
||||
if (known !== undefined) {
|
||||
pageIds.set(ref, known)
|
||||
return known
|
||||
}
|
||||
if (planned.has(ref)) {
|
||||
forward.add(ref)
|
||||
return null
|
||||
}
|
||||
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
|
||||
}
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [k, x] of Object.entries(v)) {out[k] = await resolveForCreate(x, forward, planned)}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Per-locale seed values (refs resolved) — what the hash describes. */
|
||||
const perLocale = (data: unknown) => Object.fromEntries(localeKeys.map((l) => [l ?? '-', localize(data, l, undefined, codes)]))
|
||||
|
||||
@@ -325,6 +367,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
|
||||
// Plan: one status per record, decided before anything is written.
|
||||
const plan: Planned[] = []
|
||||
const plannedHere = new Set(trackPages ? items.map((i) => i.key.slug).filter((s): s is string => typeof s === 'string') : [])
|
||||
for (const item of items) {
|
||||
const p: Planned = { ...item }
|
||||
plan.push(p)
|
||||
@@ -332,8 +375,14 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
p.id = await findId(collection, item.key)
|
||||
const slug = typeof item.key.slug === 'string' ? item.key.slug : undefined
|
||||
if (p.id === undefined) {
|
||||
// Every { $page } must exist already or be planned in this call — otherwise nothing is written (dry run too).
|
||||
for (const ref of pageRefsIn(item.data)) {
|
||||
if (plannedHere.has(ref) || pageIds.has(ref) || (await findId(pagesCollection, { slug: ref })) !== undefined) {continue}
|
||||
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
|
||||
}
|
||||
p.action = 'create'
|
||||
if (dryRun && trackPages && slug) {pageIds.set(slug, `(new:${slug})`)}
|
||||
if (dryRun && collection === formsCollection && typeof item.key.title === 'string') {plannedForms.add(item.key.title)}
|
||||
continue
|
||||
}
|
||||
if (trackPages && slug) {pageIds.set(slug, p.id)}
|
||||
@@ -352,27 +401,59 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 1: create missing records without fields that reference other pages (they may not exist yet).
|
||||
// Pass 1: create missing records complete — references to existing records resolved. A forward { $page }
|
||||
// (a page created later in this call) is null for now; a record whose required field needs it is retried
|
||||
// once that page exists. Required references in a cycle, or to a page that never appears, are an error
|
||||
// and nothing is written for those records.
|
||||
if (!dryRun) {
|
||||
for (const p of plan) {
|
||||
if (p.action !== 'create') {continue}
|
||||
try {
|
||||
const first = Object.fromEntries(Object.entries(p.data).filter(([, v]) => !hasRef(v)))
|
||||
const created = await payload.create({
|
||||
collection: collection as never,
|
||||
context,
|
||||
data: localize(first, defaultLocale, undefined, codes) as never,
|
||||
depth: 0,
|
||||
...(defaultLocale ? { locale: defaultLocale as never } : {}),
|
||||
})
|
||||
p.id = (created as { id: number | string }).id
|
||||
const slug = p.key.slug
|
||||
if (trackPages && typeof slug === 'string') {pageIds.set(slug, p.id)}
|
||||
} catch (e) {
|
||||
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
|
||||
p.action = undefined
|
||||
const waiting = plan.filter((p) => p.action === 'create' && !p.result)
|
||||
const planned = new Set(trackPages ? waiting.map((p) => p.key.slug).filter((s): s is string => typeof s === 'string') : [])
|
||||
const blocked = new Map<Planned, { error: string; forward: Set<string> }>()
|
||||
let progress = true
|
||||
while (waiting.length && progress) {
|
||||
progress = false
|
||||
for (const p of [...waiting]) {
|
||||
const forward = new Set<string>()
|
||||
try {
|
||||
const first = (await resolveForCreate(p.data, forward, planned)) as Record<string, unknown>
|
||||
const created = await payload.create({
|
||||
collection: collection as never,
|
||||
context,
|
||||
data: localize(first, defaultLocale, undefined, codes) as never,
|
||||
depth: 0,
|
||||
...(defaultLocale ? { locale: defaultLocale as never } : {}),
|
||||
})
|
||||
p.id = (created as { id: number | string }).id
|
||||
const slug = p.key.slug
|
||||
if (trackPages && typeof slug === 'string') {
|
||||
pageIds.set(slug, p.id)
|
||||
planned.delete(slug)
|
||||
}
|
||||
waiting.splice(waiting.indexOf(p), 1)
|
||||
blocked.delete(p)
|
||||
progress = true
|
||||
} catch (e) {
|
||||
if (forward.size) {
|
||||
// Valid only once the pages it links to exist — try again after the others.
|
||||
blocked.set(p, { error: (e as Error).message, forward })
|
||||
continue
|
||||
}
|
||||
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
|
||||
p.action = undefined
|
||||
waiting.splice(waiting.indexOf(p), 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const p of waiting) {
|
||||
const why = blocked.get(p)
|
||||
const targets = [...(why?.forward ?? [])].map((s) => `"${s}"`).join(', ')
|
||||
p.result = {
|
||||
label: p.label,
|
||||
note: `required references to pages not created yet (${targets}) — a cycle of required links; make one link optional or seed that page first${why ? ` (${why.error})` : ''}`,
|
||||
status: 'error',
|
||||
}
|
||||
p.action = undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: full content in every locale (dry run: resolve refs to report broken ones).
|
||||
|
||||
+87
-10
@@ -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}
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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' }] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,188 @@
|
||||
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 type { SeedResult } from '../src/exports/seed.js'
|
||||
|
||||
import { createSeeder } from '../src/exports/seed.js'
|
||||
import { buildLinksField, buildSectionHeaderField } from '../src/index.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
/**
|
||||
* Regression (vanstevpl-web, 1.15.4): a page whose REQUIRED layout holds a { $page } / { $form } reference
|
||||
* could not be created — pass 1 left the whole field out and validation rejected the record, while the dry
|
||||
* run reported a create. Now pass 1 resolves references to existing records, retries records whose required
|
||||
* fields wait for pages created later in the same call, and reports cycles and unknown targets as errors
|
||||
* with nothing written. The dry run reports the same outcome.
|
||||
*/
|
||||
const LOCALES = ['pl', 'en', 'de'] as const
|
||||
|
||||
const callToAction: Block = { slug: 'callToAction', fields: [buildSectionHeaderField(), buildLinksField()] }
|
||||
const formBlock: Block = { slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms', required: true }] }
|
||||
// A block whose link to another page is required — forward references to it must wait.
|
||||
const teaser: Block = { slug: 'teaser', fields: [{ name: 'target', type: 'relationship', relationTo: 'pages', required: true }] }
|
||||
|
||||
const confirmation = {
|
||||
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
|
||||
}
|
||||
|
||||
/** A page with a required layout of one block. */
|
||||
const page = (slug: string, title: string, layout: Record<string, unknown>[]) => ({
|
||||
slug: { de: `${slug}-de`, en: `${slug}-en`, pl: slug },
|
||||
layout,
|
||||
title: { de: `${title} DE`, en: `${title} EN`, pl: title },
|
||||
})
|
||||
const teaserTo = (slug: string) => ({ blockType: 'teaser', target: { $page: slug } })
|
||||
|
||||
describe('createSeeder: required fields with references', () => {
|
||||
let payload: Payload
|
||||
|
||||
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, required: true },
|
||||
{ name: 'slug', type: 'text', index: true, localized: true },
|
||||
{ name: 'layout', type: 'blocks', blocks: [callToAction, formBlock, teaser], required: true },
|
||||
],
|
||||
},
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-refs') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
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-required-refs',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
// The existing records the references point at.
|
||||
const seed = createSeeder(payload, { log: () => {} })
|
||||
await seed.upsertBySlug('pages', page('kontakt', 'Kontakt', [{ blockType: 'callToAction', header: { heading: { de: 'Hallo', en: 'Hello', pl: 'Cześć' } } }]))
|
||||
await seed.upsertBy('forms', { title: 'Contact form' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'Contact form' })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
vi.unstubAllEnvs()
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
const seeder = (dryRun = false) => createSeeder(payload, { dryRun, log: () => {}, update: false })
|
||||
const idOf = async (slug: string) => (await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: slug } } })).docs[0]?.id
|
||||
const count = async () => (await payload.count({ collection: 'pages' })).totalDocs
|
||||
|
||||
/** Runs the same seed as a dry run, then for real: both must report the same statuses. */
|
||||
const both = async (run: (seed: ReturnType<typeof seeder>) => Promise<SeedResult | SeedResult[]>) => {
|
||||
const planned = [await run(seeder(true))].flat().map((r) => r.status)
|
||||
const done = [await run(seeder())].flat()
|
||||
expect(done.map((r) => r.status)).toEqual(planned)
|
||||
return done
|
||||
}
|
||||
|
||||
test('the report’s careers page: a required layout linking to an existing page, in pl, en and de', async () => {
|
||||
const careers = {
|
||||
slug: { de: 'karriere', en: 'careers', pl: 'kariera' },
|
||||
layout: [
|
||||
{
|
||||
blockType: 'callToAction',
|
||||
header: { heading: { de: 'Kontakt', en: 'Contact', pl: 'Kontakt' } },
|
||||
links: [{ link: { type: 'internal', page: { $page: 'kontakt' } } }],
|
||||
},
|
||||
],
|
||||
title: { de: 'Karriere', en: 'Careers', pl: 'Kariera' },
|
||||
}
|
||||
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', careers)])
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
|
||||
const all = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as unknown as {
|
||||
layout: { header: { heading: Record<string, string> }; id: string; links: { link: { page: unknown } }[] }[]
|
||||
}
|
||||
expect(all.layout).toHaveLength(1)
|
||||
expect(all.layout[0].header.heading).toEqual({ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' })
|
||||
expect(all.layout[0].links[0].link.page).toBe(await idOf('kontakt'))
|
||||
// One set of rows in every locale (1.15.4).
|
||||
for (const locale of LOCALES) {
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { layout: { id: string }[] }
|
||||
expect(doc.layout[0].id).toBe(all.layout[0].id)
|
||||
}
|
||||
|
||||
// Create-only: a second run changes nothing.
|
||||
expect(await seeder().upsertBySlug('pages', careers)).toMatchObject({ status: 'skip (exists)' })
|
||||
})
|
||||
|
||||
test('a required layout with a form block pointing at an existing form', async () => {
|
||||
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', page('formularz', 'Formularz', [{ blockType: 'formBlock', form: { $form: 'Contact form' } }]))])
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 1, locale: 'pl' })) as unknown as { layout: { form: { title: string } }[] }
|
||||
expect(doc.layout[0].form.title).toBe('Contact form')
|
||||
})
|
||||
|
||||
test('forward references in one call: an optional link is filled in pass 2, a required one waits for its page', async () => {
|
||||
const results = await both((seed) =>
|
||||
seed.upsertBySlug('pages', [
|
||||
// Optional link (CTA) to a page later in the list.
|
||||
page('o-nas', 'O nas', [{ blockType: 'callToAction', links: [{ link: { type: 'internal', page: { $page: 'oferta' } } }] }]),
|
||||
// Required link to a page later in the list: created once that page exists.
|
||||
page('start', 'Start', [teaserTo('oferta')]),
|
||||
page('oferta', 'Oferta', [{ blockType: 'callToAction', header: { heading: { de: 'Angebot', en: 'Offer', pl: 'Oferta' } } }]),
|
||||
]),
|
||||
)
|
||||
expect(results.map((r) => r.status)).toEqual(['create', 'create', 'create'])
|
||||
const oferta = await idOf('oferta')
|
||||
const about = (await payload.findByID({ id: (await idOf('o-nas')), collection: 'pages', depth: 0, locale: 'en' })) as unknown as { layout: { links: { link: { page: unknown } }[] }[] }
|
||||
expect(about.layout[0].links[0].link.page).toBe(oferta)
|
||||
const start = (await payload.findByID({ id: (await idOf('start')), collection: 'pages', depth: 0, locale: 'de' })) as unknown as { layout: { target: unknown }[] }
|
||||
expect(start.layout[0].target).toBe(oferta)
|
||||
|
||||
// Second run: everything exists, nothing written.
|
||||
const again = await seeder().upsertBySlug('pages', [page('o-nas', 'O nas', []), page('start', 'Start', []), page('oferta', 'Oferta', [])])
|
||||
expect(again.map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)', 'skip (exists)'])
|
||||
})
|
||||
|
||||
test('required references in a cycle: a clear error, nothing written', async () => {
|
||||
const before = await count()
|
||||
const results = await seeder().upsertBySlug('pages', [page('jeden', 'Jeden', [teaserTo('dwa')]), page('dwa', 'Dwa', [teaserTo('jeden')])])
|
||||
expect(results.map((r) => r.status)).toEqual(['error', 'error'])
|
||||
expect(results[0].note).toMatch(/required references to pages not created yet \("dwa"\) — a cycle of required links/)
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
|
||||
test('a reference to a page that never appears: an error in the dry run and the real run, nothing written', async () => {
|
||||
const before = await count()
|
||||
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('sierota', 'Sierota', [teaserTo('nie-ma-takiej')]))])
|
||||
expect(results[0]).toMatchObject({ status: 'error' })
|
||||
expect(results[0].note).toMatch(/\$page "nie-ma-takiej" not found/)
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
|
||||
test('a reference to a form that does not exist: an error in the dry run too', async () => {
|
||||
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('bez-formularza', 'Bez', [{ blockType: 'formBlock', form: { $form: 'Missing form' } }]))])
|
||||
expect(results[0]).toMatchObject({ status: 'error' })
|
||||
expect(results[0].note).toMatch(/\$form "Missing form" not found/)
|
||||
})
|
||||
|
||||
test('dry run: a form planned earlier in the same run counts as there', async () => {
|
||||
const seed = seeder(true)
|
||||
expect(await seed.upsertBy('forms', { title: 'Newsletter' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [], title: 'Newsletter' })).toMatchObject({ status: 'create' })
|
||||
expect(await seed.upsertBySlug('pages', page('newsletter', 'Newsletter', [{ blockType: 'formBlock', form: { $form: 'Newsletter' } }]))).toMatchObject({ status: 'create' })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user