From cff76c2a692a14bc60111ed82961fec338223be5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 18:33:34 +0200 Subject: [PATCH] Seed helper: @intecion/ipal-kit/seed (createSeeder + building blocks) createSeeder(payload, { dryRun, update, force, guard, editCheck, context, ... }) returns upsertBySlug, upsertBy, fillGlobal and summary(); building blocks isLocalDatabase, writeLocales, seedHash, projectOnto, editedSinceSeed. Behaviour follows docs/seeding.md: create-only by default, natural keys, never deletes, globals get empty fields only, every locale written with fallbackLocale: false onto the same row ids, records edited since seeding skipped, update refused on production / non-local DB unless IPAL_SEED_ALLOW_PROD_UPDATE=1, context.ipalSkipIndexNow on every write. Both seed templates now use the helper. Node-only entry (no 'server-only', which throws under `payload run`). SQLite integration tests cover the production guard, the edited-record skip, the hash field, row ids and the IndexNow skip. Agent guide (AGENT.md, ipal-reference, ipal-site, ipal-form) and seeding.md updated. Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 3 +- docs/agent/skills/ipal-form/SKILL.md | 2 + .../ipal-form/resources/seed-form.template.ts | 254 ++--------- docs/agent/skills/ipal-reference/SKILL.md | 19 +- .../skills/ipal-reference/resources/api.md | 24 +- docs/agent/skills/ipal-site/SKILL.md | 2 + .../resources/seed-content.template.ts | 291 +----------- docs/seeding.md | 98 ++++- package.json | 5 + src/exports/seed.ts | 39 ++ src/modules/seed/guard.ts | 45 ++ src/modules/seed/index.ts | 5 + src/modules/seed/seeder.ts | 413 ++++++++++++++++++ src/modules/seed/values.ts | 184 ++++++++ test/docsConsistency.test.ts | 1 + test/seed.test.ts | 291 ++++++++++++ 16 files changed, 1155 insertions(+), 521 deletions(-) create mode 100644 src/exports/seed.ts create mode 100644 src/modules/seed/guard.ts create mode 100644 src/modules/seed/index.ts create mode 100644 src/modules/seed/seeder.ts create mode 100644 src/modules/seed/values.ts create mode 100644 test/seed.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 4e9eb5b..9163eb3 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -36,7 +36,8 @@ the option or the exported builder (module docs §12, types in `dist/**/*.d.ts`) **Docs language:** all ipal-kit docs, this guide and the skills are written in English. Write new rules, AGENTS.md entries and plugin-gap reports in English. -**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`): +**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Write seeds with +`createSeeder` from `@intecion/ipal-kit/seed` (the templates do) — it enforces every rule below: - Seeds are create-only and idempotent: match by the default-locale slug / form title / the global, skip what exists. - Never delete; never seed users, passwords or secrets; globals: fill only empty fields; no media uploads. - Every locale written separately with `fallbackLocale: false`; `context: { disableRevalidate: true, ipalSkipIndexNow: true }`. diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/ipal-form/SKILL.md index f5d5e37..e3f7bbf 100644 --- a/docs/agent/skills/ipal-form/SKILL.md +++ b/docs/agent/skills/ipal-form/SKILL.md @@ -101,6 +101,8 @@ cp .agents/skills/ipal-form/resources/seed-form.template.ts scripts/seed-form-co # fill FORM from the brief (fields, labels, messages, email subjects — every language), NOTIFY = global/field with the company address pnpm payload run scripts/seed-form-contact.ts ``` +The template writes the form with `createSeeder(...).upsertBy('forms', { title }, data)` from +`@intecion/ipal-kit/seed` (every language, row ids kept, edited forms skipped). Without a notification address the script **stops** — ask the client which inbox should receive submissions (a question from the list in ipal-site), enter it in the panel and run again. Never put the address in code. Commit the script — in production run it after the migration: `SEED_DRY_RUN=1` first, back up the database, then diff --git a/docs/agent/skills/ipal-form/resources/seed-form.template.ts b/docs/agent/skills/ipal-form/resources/seed-form.template.ts index 96ff39c..2998ca4 100644 --- a/docs/agent/skills/ipal-form/resources/seed-form.template.ts +++ b/docs/agent/skills/ipal-form/resources/seed-form.template.ts @@ -9,10 +9,12 @@ * SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also updates it if nobody edited it since seeding * (`--dry-run` after the script path works too.) * - * Safety: the form is matched by its title; nothing is ever deleted. SEED_UPDATE=1 is - * refused when NODE_ENV=production or the database is not local, unless - * IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set — back up the database first. A form an - * editor changed is skipped and reported ("skip (edited)"); see SAFETY below. + * Safety (createSeeder from @intecion/ipal-kit/seed): the form is matched by its + * title; nothing is ever deleted. SEED_UPDATE=1 is refused when NODE_ENV=production + * or the database is not local, unless IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set — + * back up the database first. A form an editor changed is skipped and reported + * ("skip (edited)"). Every language is written with `fallbackLocale: false` onto the + * same row ids (fields, options, e-mails). * * Nothing about the company lives in this file. The notification address comes * from the panel — NOTIFY.global / NOTIFY.field below (the project's company @@ -21,13 +23,9 @@ * * Safe to send to {{email}}: submitForm accepts exactly one address in an * `email` field (no extra recipients, no header injection). - * - * GOTCHA (Payload, localization.fallback: true): a read or update in locale X without - * `fallbackLocale: false` merges the FALLBACK values into X — the default-locale - * text gets saved as the X translation. Every non-default read and write below sets it. */ -import { createHash } from 'node:crypto' import config from '@payload-config' +import { createSeeder } from '@intecion/ipal-kit/seed' import { getPayload } from 'payload' // ─── fill from the brief ──────────────────────────────────────────────────── @@ -82,65 +80,6 @@ const FORM = { const NOTIFY = { global: 'company', field: 'email' } // ──────────────────────────────────────────────────────────────────────────── -// ─── SAFETY — defaults the project may change here or through env (docs/seeding.md) ─── -/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */ -const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI' -/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */ -const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)] -/** - * "Untouched since seeding", primary method: updatedAt is at most this many seconds - * after createdAt. After one seeded update the form counts as edited — add a hidden - * SEED_HASH_FIELD (formOverrides) for repeated updates. - */ -const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120) -/** Optional: hidden text field with a hash of the seeded values; used only if the forms collection has it. */ -const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash' -/** SEED_FORCE=1 also overwrites an edited form — refused outside a local database. */ -const FORCE_ONLY_LOCAL = true -// ──────────────────────────────────────────────────────────────────────────── - -const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1' -const UPDATE = process.env.SEED_UPDATE === '1' -const FORCE = UPDATE && process.env.SEED_FORCE === '1' - -function dbIsLocal(): boolean { - const url = (process.env[DB_URL_ENV] ?? '').trim() - if (!url) return false - if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file - try { - const u = new URL(url) - if (u.protocol === 'mongodb+srv:') return false - if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql - const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '') - if (!host || host.startsWith('/')) return true // postgres:///db = unix socket - return LOCAL_HOSTS.includes(host) - } catch { - return false // unparsable (e.g. several Mongo hosts) = not local - } -} - -const local = dbIsLocal() -const prodLike = process.env.NODE_ENV === 'production' || !local -if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') { - console.error( - `[seed-form] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` + - ' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' + - ' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' + - ' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. An edited form is still skipped.', - ) - process.exit(1) -} -if (FORCE && FORCE_ONLY_LOCAL && prodLike) { - console.error('[seed-form] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.') - process.exit(1) -} -if (UPDATE && prodLike) console.warn('[seed-form] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?') - -// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip revalidation and IndexNow. ipalSeed: for project hooks. -const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true } - -type Localized = Readonly> - /** Plain text (with blank-line paragraphs) → Lexical rich text, as form-builder messages expect. */ function richText(text: string) { return { @@ -166,9 +105,8 @@ function richText(text: string) { } const payload = await getPayload({ config }) -const locales = (payload.config.localization ? payload.config.localization.localeCodes : ['pl']) as string[] -const defaultLocale = (payload.config.localization ? payload.config.localization.defaultLocale : locales[0]) as string -const pick = (value: Localized, locale: string) => value[locale] ?? value[defaultLocale] ?? Object.values(value)[0] +// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file. +const seed = createSeeder(payload, { label: '[seed-form]' }) // Notification address — from the panel, never from this file. let notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() ?? '' @@ -188,157 +126,25 @@ if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) { process.exit(1) } -/** A field with every per-language text ({ pl, en }) resolved: label, step title/description, option labels. */ -function localizeField(field: Record, locale: string): Record { - const text = (v: unknown) => (v && typeof v === 'object' ? pick(v as Localized, locale) : v) - return { - ...field, - ...('label' in field ? { label: text(field.label) } : {}), - ...('title' in field ? { title: text(field.title) } : {}), - ...('description' in field ? { description: text(field.description) } : {}), - ...(Array.isArray(field.options) - ? { options: (field.options as Record[]).map((o) => ({ ...o, label: text(o.label) })) } - : {}), - } +type Localized = Readonly> +/** { pl: 'text', en: 'text' } → { pl: , en: } — still one value per locale. */ +const rich = (v: Localized) => Object.fromEntries(Object.entries(v).map(([l, text]) => [l, richText(text)])) + +const result = await seed.upsertBy('forms', { title: FORM.title }, { + title: FORM.title, + fields: FORM.fields, + submitButtonLabel: FORM.submitButtonLabel, + confirmationType: 'message', + confirmationMessage: rich(FORM.confirmation), + emails: [ + { emailTo: notifyTo, replyTo: '{{email}}', subject: FORM.notification.subject, message: rich(FORM.notification.message) }, + { emailTo: '{{email}}', replyTo: notifyTo, subject: FORM.confirmationEmail.subject, message: rich(FORM.confirmationEmail.message) }, + ], +}) + +const { errors } = seed.summary() +if (result.status === 'create' || result.status === 'update') { + console.log(`Notifications to ${notifyTo}, confirmation to the sender.`) + console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.') } - -/** Form data in one locale (localized fields resolved for it). */ -function dataFor(locale: string) { - return { - confirmationMessage: richText(pick(FORM.confirmation, locale)), - confirmationType: 'message', - emails: [ - { - emailTo: notifyTo, - replyTo: '{{email}}', - message: richText(pick(FORM.notification.message, locale)), - subject: pick(FORM.notification.subject, locale), - }, - { - emailTo: '{{email}}', - replyTo: notifyTo, - message: richText(pick(FORM.confirmationEmail.message, locale)), - subject: pick(FORM.confirmationEmail.subject, locale), - }, - ], - fields: FORM.fields.map((field) => localizeField(field as Record, locale)), - submitButtonLabel: pick(FORM.submitButtonLabel, locale), - title: FORM.title, - } -} - -/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */ -const stable = (v: unknown): string => - Array.isArray(v) ? `[${v.map(stable).join(',')}]` - : v && typeof v === 'object' - ? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record)[k] != null).sort() - .map((k) => `${JSON.stringify(k)}:${stable((v as Record)[k])}`).join(',')}}` - : JSON.stringify(v ?? null) -const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32) -/** The current values at the keys the seed writes (everything else in the form is ignored). */ -function project(seed: unknown, cur: unknown): unknown { - if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((x, i) => project(x, cur[i])) : cur - if (seed && typeof seed === 'object') { - if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur - return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record)[k], (cur as Record)[k])])) - } - return cur -} -const seedHash = () => hashOf(Object.fromEntries(locales.map((l) => [l, dataFor(l)]))) -const hasHashField = !!HASH_FIELD && !!(payload.collections['forms' as never]?.config.fields as { name?: string }[] | undefined)?.some((f) => f.name === HASH_FIELD) - -type FormDoc = Record & { emails?: { id?: string }[]; fields?: { id?: string; options?: { id?: string }[] }[] } -const readForm = async (formId: number | string, locale: string) => - (await payload.findByID({ collection: 'forms' as never, depth: 0, id: formId, locale: locale as never, fallbackLocale: false as never })) as FormDoc - -/** null = untouched since seeding; a string = why it counts as edited. */ -async function editedReason(formId: number | string): Promise { - const doc = await readForm(formId, defaultLocale) - const stored = hasHashField ? doc[HASH_FIELD] : undefined - if (typeof stored === 'string' && stored) { - const current: Record = {} - for (const l of locales) current[l] = project(dataFor(l), l === defaultLocale ? doc : await readForm(formId, l)) - return hashOf(current) === stored ? null : `${HASH_FIELD} differs` - } - const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt)) - if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt' - const sec = Math.round((u - c) / 1000) - return sec <= UNTOUCHED_SECONDS ? null : `updated ${sec}s after creation` -} - -/** Locale data onto the existing row ids (fields, their options, e-mails) — new ids would wipe the other languages' texts. */ -function withRowIds(d: ReturnType, doc: FormDoc | undefined) { - if (!doc) return d - return { - ...d, - emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })), - fields: d.fields.map((f, i) => ({ - ...f, - id: doc.fields?.[i]?.id, - ...(Array.isArray(f.options) - ? { options: (f.options as Record[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) } - : {}), - })), - } -} - -const summary = (status: string, errors = 0) => { - console.log(`\n[seed-form] summary${DRY ? ' (dry run — nothing written)' : ''}`) - console.table({ - created: status === 'create' ? 1 : 0, - skipped: status === 'skip (exists)' ? 1 : 0, - updated: status === 'update' ? 1 : 0, - 'skipped-edited': status === 'skip (edited)' ? 1 : 0, - errors, - }) -} - -console.log(`[seed-form] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}`) -const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } }) -let id = existing.docs[0]?.id as number | string | undefined -let status: 'create' | 'skip (exists)' | 'update' | 'skip (edited)' = id ? 'update' : 'create' -let note = '' -if (id && !UPDATE) { status = 'skip (exists)'; note = 'SEED_UPDATE=1 updates it if nobody edited it' } -if (id && UPDATE) { - const why = await editedReason(id) - if (why && !FORCE) { status = 'skip (edited)'; note = why } -} -if (DRY || status === 'skip (exists)' || status === 'skip (edited)') { - console.log(`${status.padEnd(14)} form "${FORM.title}"${id ? ` (id ${id})` : ''}${note ? ` — ${note}` : ''}`) - summary(status) - process.exit(0) -} - -try { - const hash = hasHashField ? { [HASH_FIELD]: seedHash() } : {} - if (!id) { - const created = await payload.create({ collection: 'forms' as never, data: { ...dataFor(defaultLocale), ...hash } as never, locale: defaultLocale as never, context: CTX }) - id = created.id - } else { - const doc = await readForm(id, defaultLocale) - await payload.update({ collection: 'forms' as never, data: { ...withRowIds(dataFor(defaultLocale), doc), ...hash } as never, id, locale: defaultLocale as never, context: CTX }) - } - const formId = id - - // Other languages: same rows (ids kept), localized texts per locale. - for (const locale of locales.filter((l) => l !== defaultLocale)) { - const doc = await readForm(formId, locale) - await payload.update({ - collection: 'forms' as never, - data: withRowIds(dataFor(locale), doc) as never, - id: formId, - locale: locale as never, - fallbackLocale: false as never, - context: CTX, - }) - } -} catch (e) { - console.error(`error form "${FORM.title}" — ${(e as Error).message}`) - summary('', 1) - process.exit(1) -} - -console.log(`${status.padEnd(14)} form "${FORM.title}" (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`) -summary(status) -console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.') -process.exit(0) +process.exit(errors ? 1 : 0) diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 49b2205..3aff430 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -22,7 +22,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `i18n.defaultLocale` | — | `localization.defaultLocale`, `/` redirect in the proxy | must be in `locales` | | `i18n.fallback` | `true` | `localization.fallback` | `false` | | `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** | -| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: nobody is admin for Site Integrations, the e-mail test, stats, consent-records; `form-submissions` readable by editor+ only | +| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every logged-in account passes the plugin's admin/editor checks (`userMeetsRole`): Site Integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides | | `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins | | `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` | | `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) | @@ -48,6 +48,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `seo.autoFill` | `{ title: 'title', content: 'layout', descriptionLength: 155 }` | `beforeChange`: empty `meta.title/description` filled from document fields | `false`; object `{ title, description, content, descriptionLength }` | | `seo.descriptionCheck` | on (`settingsSlug: 'site-settings'`, `siteDescriptionField: 'siteDescription'`) | UI field `MetaDescriptionCheck` below the description (empty / duplicated) | `false`; object overrides slug/field | | `seo.fields` | `[]` | extra fields in the SEO group | — | +| `seo.uploadsCollection` | `'media'` | upload collection `meta.image` relates to | any upload collection slug | | `seo.generateTitle` / `generateDescription` | plugin-seo | preview / generation in the panel | your own function `({ doc }) => string` | | `seo.searchSettings` | on (also without `seo`) | Site Settings → **Search & AI** tab: `searchVerification.google/bing/yandex` (→ `` via `generatePageMetadata`), `aiCrawlers.policy` + `aiCrawlers.rules[]` (→ robots.txt via `getRobots`), localized `llmsIntro` (→ top of `/llms.txt`); empty fields change nothing. Postgres: `migrate:create` after upgrading | `false` = no tab (without `seo`: `globalOverrides['site-settings']` function); `(fields) => fields` = your own set (keep the names `searchVerification`, `aiCrawlers`, `llmsIntro` or read your own fields in your routes) | | — (no option) | `uploadsCollection: 'media'` | meta image from the `media` collection | currently always `media` (gap) | @@ -189,7 +190,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba | `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) | | `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting | | `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env | -| `R2_PUBLIC_URL` | as above; absolute URL in prod | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`; with `ipalEnvRules({ storage: true })` make the rule optional, env.md); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env | +| `R2_PUBLIC_URL` | optional; required only with `ipalEnvRules({ storage: { requirePublicUrl: true } })` (then like the other `R2_*`); absolute URL in prod when set | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env | | `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | `emailGraph: true` / Graph transport in the panel | `mailAdapter` falls back to SMTP from the panel (logged) | env (agency Exchange) | | `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site Integrations → Turnstile; neither set → Turnstile off | panel (takes precedence) or env | | `INDEXNOW_KEY` | no | key from Site Integrations → IndexNow (generated) | env or panel | @@ -202,4 +203,16 @@ Details: env.md, deployment.md, PROGRAMISTA §3. **DNS** (A/AAAA, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From domain, R2 domain): the plugin sets nothing — list of records to check with `dig`: `deployment.md` §6, summary in **ipal-setup** stage 11. -**Seeding** (content in pages, forms, globals): create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`. +**Seeding** (content in pages, forms, globals): create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`. + +| Seed env var (run time) | Effect | +|---|---| +| `SEED_DRY_RUN=1` (or `--dry-run`) | no writes, print the plan | +| `SEED_UPDATE=1` | also update records nobody edited since seeding | +| `IPAL_SEED_ALLOW_PROD_UPDATE=1` | allow `SEED_UPDATE=1` on production / a non-local database (back up first) | +| `SEED_FORCE=1` | with `SEED_UPDATE=1`: overwrite edited records too — local database only | +| `SEED_LOCAL_HOSTS` | extra hosts that count as a local database (comma-separated) | +| `SEED_DB_URL_ENV` | name of the env var holding the database URL (default `DATABASE_URI`) | +| `SEED_UNTOUCHED_SECONDS` | "untouched" window for the timestamp check (default 120) | +| `SEED_HASH_FIELD` | hash field name (default `seedHash`; empty = timestamps only) | +| `SEED_NOTIFY_EMAIL` | form seed: notification address on a first run | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 27c164f..ffc5290 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -1,7 +1,7 @@ # ipal-kit — export index Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`, -`/server`, `/next/middleware`, `/admin`, `/env`), grouped by module. Search with grep +`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`), grouped by module. Search with grep (`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself. "Import from" column — the first entry is preferred. Plugin options, env, routes and what the project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/.md`. @@ -50,6 +50,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `hasMinimumRole(user, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. | | `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. | | `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. | +| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any logged-in user when the user's auth collection has no `roles` field (the project omitted `access`). The plugin's staff features use it (Site Integrations, settings globals, test e-mail, stats, consent records, form submissions). Use it in your own access when the project may run without roles. | | `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). | | `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. | | `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. | @@ -180,7 +181,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | Export | Import from | What it does / when | |---|---|---| | `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error | -| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv` | +| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }` | **Types:** `EnvRule`, `EnvKind` — variable rule (`name`, `required`, `kind`, `oneOf`, `validate`); `AssertEnvOptions` — `assertEnv` options; `IpalEnvFeatures` — `ipalEnvRules` argument (all from `/env` and root). @@ -416,6 +417,25 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr **Types:** `ExtractHeadingsOptions`, `HeadingItem`, `HeadingLevel` (root) — heading extraction options and result; `RenderRichTextProps` (`/rsc`) — renderer props; `TableOfContentsProps`, `TableOfContentsClassNames` (`/client`) — table of contents props and classes. +## Seeding (`seed`) — details: `node_modules/@intecion/ipal-kit/docs/seeding.md` + +Server only (`pnpm payload run`); never import it from client code, the Payload config or a route. + +| Export | Import from | What it does / when | +|---|---|---| +| `createSeeder(payload, { dryRun?, update?, force?, guard?, editCheck?, context?, pagesCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local }`. 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. | +| `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 (all seeded fields with `update` when untouched). | +| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. | +| `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. | +| `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`). | + +**Types:** `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`). + ## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md` | Export | Import from | What it does / when | diff --git a/docs/agent/skills/ipal-site/SKILL.md b/docs/agent/skills/ipal-site/SKILL.md index c06be37..cd0daf9 100644 --- a/docs/agent/skills/ipal-site/SKILL.md +++ b/docs/agent/skills/ipal-site/SKILL.md @@ -66,6 +66,8 @@ form with fields in JSX, an `api/contact` route, `nodemailer`, reCAPTCHA (AGENT. enter content from the brief: pages, blocks, links (`{ $page: 'slug' }`), globals — all languages side by side (`{ pl, en }`). Missing data → `[TO FILL: …]`. Never invent company data, prices, reviews, numbers, certificates, names. + The template is a thin script over `createSeeder` (`@intecion/ipal-kit/seed`): keep the calls + (`upsertBySlug`, `fillGlobal`, `summary`), change only CONTENT; options in docs/seeding.md. 2. `pnpm payload run scripts/seed-content.ts` → the placeholder list goes into the report. On production (rules: `node_modules/@intecion/ipal-kit/docs/seeding.md`): `SEED_DRY_RUN=1` first, back up the database, then the real run. It only creates what is missing; `SEED_UPDATE=1` there is refused without diff --git a/docs/agent/skills/ipal-site/resources/seed-content.template.ts b/docs/agent/skills/ipal-site/resources/seed-content.template.ts index 23ef7e4..5f58ede 100644 --- a/docs/agent/skills/ipal-site/resources/seed-content.template.ts +++ b/docs/agent/skills/ipal-site/resources/seed-content.template.ts @@ -6,13 +6,15 @@ * SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates records nobody edited since seeding * (`--dry-run` after the script path works too, e.g. `pnpm seed:content --dry-run`.) * - * Safety (docs/seeding.md): + * The rules live in createSeeder (@intecion/ipal-kit/seed), so fixes arrive with a + * plugin upgrade: * - Create-only and idempotent. Pages match by their DEFAULT-locale slug; globals * get only the fields that are still empty. Nothing is ever deleted. * - SEED_UPDATE=1 is refused when NODE_ENV=production or the database is not local, * unless IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set. Back up the database first. - * - An update skips every record an editor changed since seeding and reports it - * ("skip (edited)"). How a record counts as untouched: see SAFETY below. + * - An update skips every record an editor changed since seeding ("skip (edited)"). + * - Every locale is written with `fallbackLocale: false` onto the same row ids. + * - Writes carry ipalSkipIndexNow, disableRevalidate and ipalSeed in `context`. * - Never seed users, passwords or secrets (SMTP, Turnstile, API keys) — panel / env. * * Write content ONCE, all languages side by side: @@ -20,23 +22,14 @@ * heading: 'Nasze usługi' → same in every locale / non-localized field * page: { $page: 'kontakt' } → ID of the page whose DEFAULT-locale slug is 'kontakt' * Missing data: '[TO FILL: tax ID (NIP)]' — never invent company data, prices, reviews, numbers. - * - * The default locale creates the structure (blocks, array rows); other locales are - * written onto the SAME row ids, so nothing is duplicated. Media: leave empty or - * reference existing uploads by ID — the editor adds images. Never upload here. - * - * GOTCHA (Payload, localization.fallback: true): an update in locale X without - * `fallbackLocale: false` merges the FALLBACK values into X — the default-locale - * text gets saved as the X translation. Every non-default read and write below sets it. + * Media: leave empty or reference existing uploads by ID — the editor adds images. Never upload here. */ -import { createHash } from 'node:crypto' -import { getPayload } from 'payload' import config from '@payload-config' - -type Json = string | number | boolean | null | Json[] | { [k: string]: Json } +import { createSeeder } from '@intecion/ipal-kit/seed' +import { getPayload } from 'payload' // ------------------------------------------------------------------ CONTENT -- -const PAGES: { [k: string]: Json }[] = [ +const PAGES: Record[] = [ { title: { pl: 'Strona główna', en: 'Home' }, slug: { pl: 'home', en: 'home' }, @@ -50,269 +43,21 @@ const PAGES: { [k: string]: Json }[] = [ }, { title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' }, layout: [] }, ] -const GLOBALS: { slug: string; data: { [k: string]: Json } }[] = [ +const GLOBALS: { slug: string; data: Record }[] = [ // { slug: 'header', data: { links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' } } }] } }, ] const COLLECTION = 'pages' // ----------------------------------------------------------------- /CONTENT -- -// ------------------------------------------------------------------- SAFETY -- -// Defaults — the project may change them here or through env (docs/seeding.md). -/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */ -const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI' -/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */ -const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)] -/** - * "Untouched since seeding", primary method: updatedAt is at most this many seconds - * after createdAt (the seed's own writes in one run). After one seeded update the - * record counts as edited — use SEED_HASH_FIELD for repeated updates. - */ -const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120) -/** - * Optional method: a hidden text field with a hash of the seeded values. Used only - * when the collection/global has a top-level field with this name; it then decides - * instead of the timestamps and allows repeated updates. - */ -const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash' -/** SEED_FORCE=1 also overwrites edited records — refused outside a local database. */ -const FORCE_ONLY_LOCAL = true -// ------------------------------------------------------------------ /SAFETY -- +// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file: +// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } }) +const seed = createSeeder(await getPayload({ config }), { pagesCollection: COLLECTION }) -const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1' -const UPDATE = process.env.SEED_UPDATE === '1' -const FORCE = UPDATE && process.env.SEED_FORCE === '1' +// One call for all pages: missing ones are created first, so $page links work in any order. +await seed.upsertBySlug(COLLECTION, PAGES) +for (const g of GLOBALS) await seed.fillGlobal(g.slug, g.data) -function dbIsLocal(): boolean { - const url = (process.env[DB_URL_ENV] ?? '').trim() - if (!url) return false - if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file - try { - const u = new URL(url) - if (u.protocol === 'mongodb+srv:') return false - if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql - const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '') - if (!host || host.startsWith('/')) return true // postgres:///db = unix socket - return LOCAL_HOSTS.includes(host) - } catch { - return false // unparsable (e.g. several Mongo hosts) = not local - } -} - -const local = dbIsLocal() -const prodLike = process.env.NODE_ENV === 'production' || !local -if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') { - console.error( - `[seed] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` + - ' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' + - ' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' + - ' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. Edited records are still skipped.', - ) - process.exit(1) -} -if (FORCE && FORCE_ONLY_LOCAL && prodLike) { - console.error('[seed] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.') - process.exit(1) -} -if (UPDATE && prodLike) console.warn('[seed] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?') - -// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip cache revalidation and the -// IndexNow ping for seeded (placeholder) content. ipalSeed: for the project's own hooks. -const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true } -const payload = await getPayload({ config }) -const loc = payload.config.localization -const def = loc ? loc.defaultLocale : undefined -const codes = loc ? loc.localeCodes : [] -const others = codes.filter((c) => c !== def) -const ids = new Map() - -const isLocalized = (v: Json): boolean => - !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k)) - -/** Value for one locale; arrays keep the ids of rows that already exist. undefined = omit. */ -function pick(v: Json, locale: string | undefined, existing: unknown): Json | undefined { - if (isLocalized(v)) { const m = v as { [k: string]: Json }; return locale ? m[locale] : m[def as string] } - if (Array.isArray(v)) { - const ex = Array.isArray(existing) ? existing : [] - return v.map((item, i) => { - const out = pick(item, locale, ex[i]) - const id = (ex[i] as { id?: string } | undefined)?.id - return out && typeof out === 'object' && !Array.isArray(out) && id ? { ...out, id } : (out ?? null) - }) - } - if (v && typeof v === 'object') { - if (typeof v.$page === 'string') { - const id = ids.get(v.$page) - if (id === undefined) throw new Error(`$page "${v.$page}" not found — seed that page earlier in PAGES or create it in the panel`) - return id - } - const ex = (existing && typeof existing === 'object' ? existing : {}) as Record - const out: { [k: string]: Json } = {} - for (const [k, val] of Object.entries(v) as [string, Json][]) { - const r = pick(val, locale, ex[k]) - if (r !== undefined) out[k] = r - } - return out - } - return v -} -const defSlug = (p: { [k: string]: Json }) => String(isLocalized(p.slug) ? (p.slug as { [k: string]: Json })[def as string] : p.slug) -const hasPageRef = (v: Json): boolean => - Array.isArray(v) ? v.some(hasPageRef) : !!v && typeof v === 'object' ? typeof v.$page === 'string' || Object.values(v).some(hasPageRef) : false -const hasContent = (v: unknown): boolean => - typeof v === 'string' ? v.trim() !== '' : typeof v === 'number' || v === true ? true - : Array.isArray(v) ? v.some(hasContent) : !!v && typeof v === 'object' ? Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x)) : false - -// --- "edited since seeding" ------------------------------------------------- -/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */ -const stable = (v: unknown): string => - Array.isArray(v) ? `[${v.map(stable).join(',')}]` - : v && typeof v === 'object' - ? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record)[k] != null).sort() - .map((k) => `${JSON.stringify(k)}:${stable((v as Record)[k])}`).join(',')}}` - : JSON.stringify(v ?? null) -const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32) -/** The current values at the keys the seed writes (everything else in the record is ignored). */ -function project(seed: unknown, cur: unknown): unknown { - if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((s, i) => project(s, cur[i])) : cur - if (seed && typeof seed === 'object') { - if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur - return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record)[k], (cur as Record)[k])])) - } - return cur -} -const localesOrDefault = codes.length ? codes : [undefined] -/** Seed values per locale (refs resolved). */ -const seedPerLocale = (v: Json) => Object.fromEntries(localesOrDefault.map((l) => [l ?? '-', pick(v, l, undefined)])) -const hasField = (fields: unknown[] | undefined) => !!HASH_FIELD && !!fields?.some((f) => (f as { name?: string }).name === HASH_FIELD) -const pagesHaveHash = hasField(payload.collections[COLLECTION as never]?.config.fields as unknown[] | undefined) -const globalHasHash = (slug: string) => hasField(payload.config.globals.find((g) => g.slug === slug)?.fields as unknown[] | undefined) - -/** null = untouched; a string = why it counts as edited. */ -async function editedReason( - doc: Record, - seed: Json, - withHash: boolean, - readLocale: (l: string | undefined) => Promise, -): Promise { - const stored = withHash ? doc[HASH_FIELD] : undefined - if (typeof stored === 'string' && stored) { - const seeded = seedPerLocale(seed) - const current: Record = {} - for (const l of localesOrDefault) current[l ?? '-'] = project(seeded[l ?? '-'], await readLocale(l)) - return hashOf(current) === stored ? null : `${HASH_FIELD} differs` - } - const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt)) - if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt' - const s = Math.round((u - c) / 1000) - return s <= UNTOUCHED_SECONDS ? null : `updated ${s}s after creation` -} - -// --- report ----------------------------------------------------------------- -type Status = 'create' | 'skip (exists)' | 'update' | 'skip (edited)' | 'error' -const counts: Record = { create: 0, 'skip (exists)': 0, update: 0, 'skip (edited)': 0, error: 0 } -const report = (status: Status, what: string, note = '') => { - counts[status]++ - console.log(`${status.padEnd(14)} ${what}${note ? ` — ${note}` : ''}`) -} -const readOpts = (l: string | undefined) => (l ? { locale: l as never, fallbackLocale: false as never } : {}) -console.log(`[seed] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}\n`) - -// Existing pages first, so $page works regardless of order. -const { docs: existingPages } = await payload.find({ collection: COLLECTION as never, depth: 0, limit: 0, pagination: false, ...readOpts(def) }) -const existingIds = new Set() -for (const d of existingPages as { id: string | number; slug?: string }[]) if (d.slug) { ids.set(d.slug, d.id); existingIds.add(d.id) } - -// Plan: one status per page, decided before anything is written. -const plan = new Map() -for (const p of PAGES) { - const slug = defSlug(p) - const id = ids.get(slug) - if (id === undefined) { plan.set(slug, 'create'); if (DRY) ids.set(slug, `(new:${slug})`); continue } - if (!UPDATE) { report('skip (exists)', `${COLLECTION} "${slug}"`, 'SEED_UPDATE=1 to update untouched records'); continue } - try { - const readDoc = (l: string | undefined) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, ...readOpts(l) }) - const why = await editedReason((await readDoc(def)) as Record, p, pagesHaveHash, readDoc) - if (why && !FORCE) { report('skip (edited)', `${COLLECTION}/${String(id)} "${slug}"`, why); continue } - plan.set(slug, 'update') - } catch (e) { - report('error', `${COLLECTION} "${slug}"`, (e as Error).message) - } -} - -// Pass 1: create missing pages without layout links (targets may not exist yet), pass 2: full content. -for (const pass of [1, 2] as const) { - for (const p of PAGES) { - const slug = defSlug(p) - const action = plan.get(slug) - if (!action || (pass === 1 && action !== 'create')) continue - if (DRY) { - if (pass === 1) continue - try { pick(p, def, undefined); report(action, `${COLLECTION} "${slug}"`, `[${codes.join(', ') || '-'}]`) } // resolves $page refs - catch (e) { report('error', `${COLLECTION} "${slug}"`, (e as Error).message) } - continue - } - try { - if (pass === 1) { - const data = pick(hasPageRef(p) ? { ...p, layout: [] } : p, def, undefined) as Record - const created = await payload.create({ collection: COLLECTION as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX }) - ids.set(slug, (created as { id: string | number }).id) - continue - } - const id = ids.get(slug) - if (id === undefined) continue // pass 1 failed — already reported - const readDoc = (l: string) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, locale: l as never, fallbackLocale: false as never }) - const base = pick(p, def, undefined) as Record - const data = pagesHaveHash ? { ...base, [HASH_FIELD]: hashOf(seedPerLocale(p)) } : base - await payload.update({ collection: COLLECTION as never, id: id as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX }) - for (const l of others) { - await payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, l, await readDoc(def as string)) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX }) - } - report(action, `${COLLECTION}/${String(id)} "${slug}"`, `[${codes.join(', ') || '-'}]`) - } catch (e) { - report('error', `${COLLECTION} "${slug}"`, (e as Error).message) - plan.delete(slug) - } - } -} - -// Globals: only empty fields are filled. With SEED_UPDATE=1 an untouched global gets every seeded field. -for (const g of GLOBALS) { - try { - const readG = (l: string | undefined) => payload.findGlobal({ slug: g.slug as never, depth: 0, ...readOpts(l) }) - const cur = (await readG(def)) as Record - const empty = Object.keys(g.data).filter((k) => !hasContent(cur[k])) - let keys = empty - let edited: string | null = null - if (UPDATE) { - edited = await editedReason(cur, g.data, globalHasHash(g.slug), readG) - if (!edited || FORCE) keys = Object.keys(g.data) - } - if (!keys.length) { - if (edited) report('skip (edited)', `global ${g.slug}`, edited) - else report('skip (exists)', `global ${g.slug}`, 'every seeded field has content') - continue - } - const all = keys.length === Object.keys(g.data).length - const status: Status = keys !== empty ? 'update' : edited ? 'skip (edited)' : 'create' - const note = keys !== empty ? `[${codes.join(', ') || '-'}]` : `${edited ? `${edited}; ` : ''}empty fields filled: ${keys.join(', ')}` - if (!DRY) { - const part = Object.fromEntries(keys.map((k) => [k, g.data[k]])) as { [k: string]: Json } - const base = pick(part, def, cur) as Record - // The hash describes the whole seeded set — store it only when every seeded field was written. - const data = all && globalHasHash(g.slug) ? { ...base, [HASH_FIELD]: hashOf(seedPerLocale(g.data)) } : base - await payload.updateGlobal({ slug: g.slug as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX }) - for (const l of others) { - await payload.updateGlobal({ slug: g.slug as never, data: pick(part, l, await readG(def)) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX }) - } - } - report(status, `global ${g.slug}`, note) - } catch (e) { - report('error', `global ${g.slug}`, (e as Error).message) - } -} - -console.log(`\n[seed] summary${DRY ? ' (dry run — nothing written)' : ''}`) -console.table({ created: counts.create, skipped: counts['skip (exists)'], updated: counts.update, 'skipped-edited': counts['skip (edited)'], errors: counts.error }) +const { errors } = seed.summary() const todo = JSON.stringify({ PAGES, GLOBALS }).match(/\[TO FILL:[^\]]*\]/g) ?? [] if (todo.length) console.log(`\n${todo.length} placeholder(s) for the final report:\n ${[...new Set(todo)].join('\n ')}`) -process.exit(counts.error ? 1 : 0) +process.exit(errors ? 1 : 0) diff --git a/docs/seeding.md b/docs/seeding.md index 149c0c3..eece364 100644 --- a/docs/seeding.md +++ b/docs/seeding.md @@ -8,7 +8,9 @@ templates. Copy them into the project and fill them from the brief: | `docs/agent/skills/ipal-site/resources/seed-content.template.ts` | `scripts/seed-content.ts` | pages (or another collection with a slug) and globals, every language | | `docs/agent/skills/ipal-form/resources/seed-form.template.ts` | `scripts/seed-form-.ts` | one form: fields, confirmation, both e-mails, every language | -Both follow the rules below. A seed you write yourself must follow them too. +Both are thin scripts over the seed helper `createSeeder` from `@intecion/ipal-kit/seed` +([The seed helper](#the-seed-helper)), which implements every rule below. A seed you write yourself +should use it too; if it does not, it must follow the rules by hand. ## Rules @@ -97,7 +99,7 @@ host is `localhost`, `127.0.0.1` or `::1`. Everything else is not local, includi Timestamps are simple and safe, but they allow **one** update per record: after a seeded update `updatedAt` moves on, so the next run reports `skip (edited)`. When you need repeated updates, add the -hash field. The templates use it automatically when the collection or global has a top-level field with +hash field. The seed helper uses it automatically when the collection or global has a top-level field with that name; the stored hash then decides instead of the timestamps. ```ts @@ -122,7 +124,7 @@ English version. See also [i18n.md](./i18n.md). ## Context flags -Pass them in `context` on every `create`, `update` and `updateGlobal`: +Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSeeder` does it on every write): | Flag | Read by | Effect | |---|---|---| @@ -152,22 +154,82 @@ must be available at runtime, not only at build time. The container already has A seed never changes the schema. A migration never fills editorial content from a brief. +## The seed helper + +`@intecion/ipal-kit/seed` is a server-only entry for seed scripts (plain Node via `pnpm payload run`). +Never import it from client code, the Payload config or a route. It does not import `server-only`, +because that package throws outside a bundled server. + +```ts +// scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts +import config from '@payload-config' +import { createSeeder } from '@intecion/ipal-kit/seed' +import { getPayload } from 'payload' + +const seed = createSeeder(await getPayload({ config })) +await seed.upsertBySlug('pages', [ + { title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] }, + { title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }, +]) +await seed.upsertBy('forms', { title: 'Contact form' }, { title: 'Contact form', fields: [/* … */] }) +await seed.fillGlobal('header', { phone: '[TO FILL: phone]' }) +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. +`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`. + +| 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` links), then every record gets its full content, so pages can link to each other in any order | +| `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). With `update` and an untouched global: every seeded field | +| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` | + +Each method prints one line per record (see [Running a seed](#running-a-seed)) and returns +`{ status, label, id, note }`. A failed write is reported as `error` and the run goes on; exit +with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production +guard refuses the run. + +On a collection with drafts the helper reads the latest draft, both to match records and to tell +whether an editor changed them. + +### Building blocks + +| Export | Use | +|---|---| +| `isLocalDatabase(url, { localHosts })` | the "local database" test of [Updates on production](#updates-on-production) | +| `writeLocales(payload, target, data, { context, draft })` | writes seed values to an existing record (`{ collection, id }` or `{ global }`) in every locale: the default locale first, then the others with `fallbackLocale: false` onto the same row ids | +| `seedHash(value)` | the hash stored in the hash field: key order, row ids and `null`s don't change it | +| `projectOnto(seed, current)` | the current values at the keys the seed writes, the input for `seedHash` on a re-run | +| `editedSinceSeed({ doc, currentHash, hashField, untouchedSeconds })` | `null` when untouched, otherwise why the record counts as edited | + +Types: `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`, +`UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`. + ## Turn off, override, extend -The guards are defaults in the templates. The project can change them — at the top of each template -(`SAFETY` block) or through env: +Every guard is a default. Change it with an env var at run time or with a `createSeeder` option in +the script: -| Env var / constant | Default | What it does | -|---|---|---| -| `SEED_DRY_RUN=1` / `--dry-run` | off | no writes, print the plan | -| `SEED_UPDATE=1` | off | update records nobody edited since seeding | -| `IPAL_SEED_ALLOW_PROD_UPDATE=1` | off | allow `SEED_UPDATE=1` on production or a non-local database | -| `SEED_FORCE=1` | off | with `SEED_UPDATE=1`: overwrite edited records too. Local database only (`FORCE_ONLY_LOCAL`) | -| `SEED_LOCAL_HOSTS` | — | extra hosts that count as local, comma-separated (e.g. a Docker Compose `db` service) | -| `SEED_DB_URL_ENV` | `DATABASE_URI` | the env var that holds the database URL | -| `SEED_UNTOUCHED_SECONDS` | `120` | the timestamp window for "untouched since creation" | -| `SEED_HASH_FIELD` | `seedHash` | the hash field name; empty = timestamps only | -| `SEED_NOTIFY_EMAIL` | — | form seed: notification address for a first run when the company global is still empty | +| Env var | `createSeeder` option | Default | What it does | +|---|---|---|---| +| `SEED_DRY_RUN=1` / `--dry-run` | `dryRun` | off | no writes, print the plan | +| `SEED_UPDATE=1` | `update` | off | update records nobody edited since seeding | +| `IPAL_SEED_ALLOW_PROD_UPDATE=1` | `guard.allowProdUpdate` | off | allow `update` on production or a non-local database | +| `SEED_FORCE=1` | `force` | off | with `update`: overwrite edited records too. Local database only (`guard.forceOnlyLocal: false` lifts that) | +| `SEED_LOCAL_HOSTS` | `guard.localHosts` | — | extra hosts that count as local, comma-separated (e.g. a Docker Compose `db` service) | +| `SEED_DB_URL_ENV` | `guard.databaseUrl` | `DATABASE_URI` | the env var that holds the database URL / the URL itself | +| `NODE_ENV` | `guard.production` | `NODE_ENV === 'production'` | whether this run counts as production | +| — | `guard: false` | on | turn the production guard off (the project takes the risk) | +| `SEED_UNTOUCHED_SECONDS` | `editCheck.untouchedSeconds` | `120` | the timestamp window for "untouched since creation" | +| `SEED_HASH_FIELD` | `editCheck.hashField` | `seedHash` | the hash field name; empty / `false` = timestamps only | +| — | `context` | `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }` all `true` | merged over the defaults; set a key to `false` to drop it | +| — | `pagesCollection` | `pages` | the collection `{ $page }` links resolve in | +| — | `label`, `log` | `[seed]`, stdout | line prefix and where lines go | +| `SEED_NOTIFY_EMAIL` | — | — | form seed: notification address for a first run when the company global is still empty | -The plugin itself has no seed option and no seed code. The templates are plain project scripts: edit -them freely, but keep the rules above. +The plugin has no seed option and runs no seed by itself. The templates are plain project scripts: +edit them freely, but keep the rules above. diff --git a/package.json b/package.json index 6f639ea..9b27703 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,11 @@ "types": "./dist/exports/server.d.ts", "default": "./dist/exports/server.js" }, + "./seed": { + "import": "./dist/exports/seed.js", + "types": "./dist/exports/seed.d.ts", + "default": "./dist/exports/seed.js" + }, "./next/middleware": { "import": "./dist/exports/next-middleware.js", "types": "./dist/exports/next-middleware.d.ts", diff --git a/src/exports/seed.ts b/src/exports/seed.ts new file mode 100644 index 0000000..015c6f6 --- /dev/null +++ b/src/exports/seed.ts @@ -0,0 +1,39 @@ +/** + * Entry point: @intecion/ipal-kit/seed + * + * Seed helper for the project's seed scripts (docs/seeding.md): + * + * // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts + * import config from '@payload-config' + * import { getPayload } from 'payload' + * import { createSeeder } from '@intecion/ipal-kit/seed' + * + * const seed = createSeeder(await getPayload({ config })) + * await seed.upsertBySlug('pages', [{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }]) + * await seed.fillGlobal('header', { links: [] }) + * process.exit(seed.summary().errors ? 1 : 0) + * + * Server only: Node built-ins and the Local API. Never import it from client + * code, the Payload config or a route. It does not import 'server-only' — that + * package throws in plain Node, and `payload run` is plain Node. + */ +export { + createSeeder, + editedSinceSeed, + isLocalDatabase, + projectOnto, + seedHash, + writeLocales, +} from '../modules/seed/index.js' +export type { + EditedSinceSeedArgs, + Seeder, + SeederOptions, + SeedResult, + SeedStatus, + SeedSummary, + SeedTarget, + SeedValue, + UpsertOptions, + WriteLocalesOptions, +} from '../modules/seed/index.js' diff --git a/src/modules/seed/guard.ts b/src/modules/seed/guard.ts new file mode 100644 index 0000000..e860355 --- /dev/null +++ b/src/modules/seed/guard.ts @@ -0,0 +1,45 @@ +/** + * Where a seed runs — the production guard of docs/seeding.md. + * + * A database counts as local when its URL is a SQLite file (`file:…`, `*.db`), + * a Unix socket, or a URL whose host is localhost / 127.0.0.1 / ::1 (plus + * `localHosts`). Everything else is not local: Docker service names (Coolify), + * `mongodb+srv://`, URLs that don't parse (several Mongo hosts), an empty URL. + */ + +const DEFAULT_LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1'] + +/** Extra local hosts from SEED_LOCAL_HOSTS (comma-separated, e.g. a Compose `db` service). */ +function envLocalHosts(): string[] { + return (process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean) +} + +/** + * True when `url` points at a database on this machine. + * + * isLocalDatabase(process.env.DATABASE_URI) // env-driven default + * isLocalDatabase('postgres://db:5432/app', { localHosts: ['db'] }) + */ +export function isLocalDatabase( + url: null | string | undefined, + { localHosts = envLocalHosts() }: { localHosts?: string[] } = {}, +): boolean { + const value = (url ?? '').trim() + if (!value) {return false} + if (/^file:/i.test(value) || /\.(?:db|sqlite3?)$/i.test(value)) {return true} + try { + const u = new URL(value) + if (u.protocol === 'mongodb+srv:') {return false} + if (u.searchParams.get('host')?.startsWith('/')) {return true} // ?host=/var/run/postgresql + const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '') + if (!host || host.startsWith('/')) {return true} // postgres:///db = Unix socket + return [...DEFAULT_LOCAL_HOSTS, ...localHosts].includes(host) + } catch { + return false + } +} + +/** The database URL the guard checks: SEED_DB_URL_ENV names the var (default DATABASE_URI). */ +export function seedDatabaseUrl(): string | undefined { + return process.env[process.env.SEED_DB_URL_ENV || 'DATABASE_URI'] +} diff --git a/src/modules/seed/index.ts b/src/modules/seed/index.ts new file mode 100644 index 0000000..7bdcebc --- /dev/null +++ b/src/modules/seed/index.ts @@ -0,0 +1,5 @@ +export { isLocalDatabase } from './guard.js' +export { createSeeder } from './seeder.js' +export type { Seeder, SeederOptions, SeedResult, SeedStatus, SeedSummary, UpsertOptions } from './seeder.js' +export { editedSinceSeed, projectOnto, seedHash, writeLocales } from './values.js' +export type { EditedSinceSeedArgs, SeedTarget, SeedValue, WriteLocalesOptions } from './values.js' diff --git a/src/modules/seed/seeder.ts b/src/modules/seed/seeder.ts new file mode 100644 index 0000000..6308e5b --- /dev/null +++ b/src/modules/seed/seeder.ts @@ -0,0 +1,413 @@ +import type { BasePayload } from 'payload' + +import type { SeedTarget } from './values.js' + +import { isLocalDatabase, seedDatabaseUrl } from './guard.js' +import { + defaultHashField, + defaultUntouchedSeconds, + editedSinceSeed, + hasContent, + isLocalizedValue, + localesOf, + localize, + projectOnto, + readSeedTarget, + seedHash, + writeLocales, +} from './values.js' + +/** + * createSeeder — the rules of docs/seeding.md in one tested place, for the + * project's seed scripts (`pnpm payload run scripts/seed-content.ts`): + * + * - create-only by default: missing records are created, existing ones skipped; + * - records match by a natural key (slug in the default locale, form title…), never by id; + * - nothing is ever deleted; + * - globals get only their empty fields; + * - every locale is written with `fallbackLocale: false` onto the same row ids; + * - `update: true` overwrites only records nobody edited since seeding; + * - `update: true` is refused on production / a non-local database unless + * IPAL_SEED_ALLOW_PROD_UPDATE=1; + * - every write carries `context` (ipalSkipIndexNow, disableRevalidate, ipalSeed); + * - one line per record and summary() with the counts. + * + * Node only (Local API, node:crypto). It does not import 'server-only': that + * package throws outside a bundled server, and `payload run` is plain Node. + */ + +export type SeedStatus = 'create' | 'error' | 'skip (edited)' | 'skip (exists)' | 'update' + +export type SeedResult = { + /** Record id; a placeholder `(new:)` for a planned create in a dry run. */ + id?: number | string + /** What the line says: `pages "kontakt"`, `global header`. */ + label: string + note?: string + status: SeedStatus +} + +export type SeedSummary = { + created: number + errors: number + skipped: number + skippedEdited: number + updated: number +} + +export type SeederOptions = { + /** + * Context passed to every create / update / updateGlobal, merged over the + * defaults `{ ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true }`. + * Set a key to false to drop that default. + */ + context?: Record + /** No writes, only the plan. Default: SEED_DRY_RUN=1 or `--dry-run` in argv. */ + dryRun?: boolean + /** How "edited since seeding" is told — docs/seeding.md. */ + editCheck?: { + /** Hidden text field holding a hash of the seeded values. Default SEED_HASH_FIELD or 'seedHash'; false = timestamps only. */ + hashField?: false | string + /** Default SEED_UNTOUCHED_SECONDS or 120. */ + untouchedSeconds?: number + } + /** + * With `update`: overwrite edited records too. Default SEED_FORCE=1. + * Refused outside a local database unless `guard.forceOnlyLocal: false`. + */ + force?: boolean + /** + * The production guard. false turns it off (the project takes the risk). + * `update` on production (NODE_ENV=production) or a non-local database is + * refused unless `allowProdUpdate`. + */ + guard?: + | { + /** Default IPAL_SEED_ALLOW_PROD_UPDATE=1. */ + allowProdUpdate?: boolean + /** Database URL checked for "local". Default the var SEED_DB_URL_ENV names (DATABASE_URI). */ + databaseUrl?: string + /** `force` only on a local database. Default true. */ + forceOnlyLocal?: boolean + /** Extra hosts that count as local. Default SEED_LOCAL_HOSTS. */ + localHosts?: string[] + /** Default NODE_ENV === 'production'. */ + production?: boolean + } + | false + /** Prefix of the header and summary lines. Default '[seed]'. */ + label?: string + /** Where lines go. Default stdout. */ + log?: (line: string) => void + /** Collection `{ $page: '' }` references resolve in. Default 'pages'. */ + pagesCollection?: string + /** Also update records nobody edited since seeding. Default SEED_UPDATE=1. */ + update?: boolean +} + +export type UpsertOptions = { + /** Field holding the slug. Default 'slug'. */ + slugField?: string +} + +export type Seeder = { + /** Effective settings after env and guard. */ + readonly dryRun: boolean + /** + * Fills a global: only its empty fields (default locale decides), or — with + * `update` and nobody edited it since seeding — every seeded field. + */ + fillGlobal: (slug: string, data: Record) => Promise + readonly force: boolean + readonly local: boolean + /** Ends the run: prints the summary and returns the counts (errors > 0 → exit 1). */ + summary: () => SeedSummary + readonly update: boolean + /** Creates or updates the record whose `key` fields equal the given values (default locale). */ + upsertBy: (collection: string, key: Record, data: Record) => Promise + /** + * Creates or updates records matched by their default-locale slug. Pass an + * array when records link to each other ({ $page }): missing ones are created + * first, then every record gets its full content. + */ + upsertBySlug: { + (collection: string, data: Record, options?: UpsertOptions): Promise + (collection: string, data: Record[], options?: UpsertOptions): Promise + } +} + +const DEFAULT_CONTEXT = { disableRevalidate: true, ipalSeed: true, ipalSkipIndexNow: true } + +const defaultLog = (line: string) => { + process.stdout.write(`${line}\n`) +} + +type Item = { data: Record; key: Record; label: string } +type Planned = { action?: 'create' | 'update'; id?: number | string; result?: SeedResult } & Item + +const hasRef = (v: unknown): boolean => + Array.isArray(v) + ? v.some(hasRef) + : !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || Object.values(v).some(hasRef)) + +export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder { + const env = process.env + const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1') + const update = options.update ?? env.SEED_UPDATE === '1' + const force = update && (options.force ?? env.SEED_FORCE === '1') + const guard = options.guard === false ? false : (options.guard ?? {}) + const label = options.label ?? '[seed]' + const log = options.log ?? defaultLog + const hashField = options.editCheck?.hashField ?? defaultHashField() + const untouchedSeconds = options.editCheck?.untouchedSeconds ?? defaultUntouchedSeconds() + const pagesCollection = options.pagesCollection ?? 'pages' + const context = { ...DEFAULT_CONTEXT, ...options.context } + + const local = isLocalDatabase(guard ? (guard.databaseUrl ?? seedDatabaseUrl()) : seedDatabaseUrl(), guard ? { ...(guard.localHosts && { localHosts: guard.localHosts }) } : {}) + if (guard) { + const production = guard.production ?? env.NODE_ENV === 'production' + const prodLike = production || !local + const allowProdUpdate = guard.allowProdUpdate ?? env.IPAL_SEED_ALLOW_PROD_UPDATE === '1' + if (update && prodLike && !allowProdUpdate) { + throw new Error( + `${label} update refused: ${production ? 'NODE_ENV=production' : 'the database is not local'}.\n` + + ' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' + + ' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' + + ' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. Edited records are still skipped.', + ) + } + if (force && guard.forceOnlyLocal !== false && prodLike) { + throw new Error(`${label} force refused: it overwrites editors' changes and works only on a local database.`) + } + if (update && prodLike) {log(`${label} Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?`)} + } + + const { codes, defaultLocale } = localesOf(payload) + const localeKeys = codes.length ? codes : [undefined] + const counts: Record = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, update: 0 } + const pageIds = new Map() + + log( + `${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}\n`, + ) + + const report = (result: SeedResult): SeedResult => { + counts[result.status]++ + log(`${result.status.padEnd(14)} ${result.label}${result.note ? ` — ${result.note}` : ''}`) + return result + } + + const collectionConfig = (slug: string) => payload.collections[slug as never]?.config + const hasHashField = (fields: undefined | unknown[]) => + !!hashField && !!fields?.some((f) => (f as { name?: string }).name === hashField) + const hasDrafts = (slug: string) => { + const versions = collectionConfig(slug)?.versions + return !!versions && typeof versions === 'object' && !!versions.drafts + } + const localeNote = `[${codes.join(', ') || '-'}]` + + const findId = async (collection: string, key: Record) => { + const { docs } = await payload.find({ + collection: collection as never, + depth: 0, + draft: hasDrafts(collection), + limit: 1, + pagination: false, + where: Object.fromEntries(Object.entries(key).map(([k, v]) => [k, { equals: v }])) as never, + ...(defaultLocale ? { locale: defaultLocale as never } : {}), + }) + return (docs[0] as { id: number | string } | undefined)?.id + } + + /** + * Replaces { $page: slug } with the page id (a placeholder for a planned create in a dry run). + * lenient: an unknown page gives a placeholder instead of an error (edit check before pass 1). + */ + const resolveRefs = async (v: unknown, lenient = false): Promise => { + if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveRefs(x, lenient)))} + if (!v || typeof v !== 'object') {return v} + const ref = (v as { $page?: unknown }).$page + if (typeof ref === 'string') { + let id = pageIds.get(ref) + if (id === undefined) { + id = await findId(pagesCollection, { slug: ref }) + if (id === undefined) { + if (lenient) {return `(new:${ref})`} + throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`) + } + pageIds.set(ref, id) + } + return id + } + const out: Record = {} + for (const [k, x] of Object.entries(v)) {out[k] = await resolveRefs(x, lenient)} + 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)])) + + const editedReason = async (target: SeedTarget, data: Record, withHash: boolean, draft: boolean) => { + const doc = await readSeedTarget(payload, target, defaultLocale, draft) + let currentHash: string | undefined + if (withHash && typeof doc[hashField as string] === 'string') { + const seeded = perLocale(await resolveRefs(data, true)) + const current: Record = {} + for (const l of localeKeys) { + const cur = l === defaultLocale ? doc : await readSeedTarget(payload, target, l, draft) + current[l ?? '-'] = projectOnto(seeded[l ?? '-'], cur) + } + currentHash = seedHash(current) + } + return editedSinceSeed({ currentHash, doc, hashField: withHash ? hashField : false, untouchedSeconds }) + } + + const upsertMany = async (collection: string, items: Item[]): Promise => { + const withHash = hasHashField(collectionConfig(collection)?.fields as undefined | unknown[]) + const draft = hasDrafts(collection) + const trackPages = collection === pagesCollection + + // Plan: one status per record, decided before anything is written. + const plan: Planned[] = [] + for (const item of items) { + const p: Planned = { ...item } + plan.push(p) + try { + p.id = await findId(collection, item.key) + const slug = typeof item.key.slug === 'string' ? item.key.slug : undefined + if (p.id === undefined) { + p.action = 'create' + if (dryRun && trackPages && slug) {pageIds.set(slug, `(new:${slug})`)} + continue + } + if (trackPages && slug) {pageIds.set(slug, p.id)} + if (!update) { + p.result = { id: p.id, label: item.label, note: 'SEED_UPDATE=1 to update untouched records', status: 'skip (exists)' } + continue + } + const why = await editedReason({ id: p.id, collection }, item.data, withHash, draft) + if (why && !force) { + p.result = { id: p.id, label: item.label, note: why, status: 'skip (edited)' } + continue + } + p.action = 'update' + } catch (e) { + p.result = { label: item.label, note: (e as Error).message, status: 'error' } + } + } + + // Pass 1: create missing records without fields that reference other pages (they may not exist yet). + 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 + } + } + } + + // Pass 2: full content in every locale (dry run: resolve refs to report broken ones). + for (const p of plan) { + if (p.action && !p.result) { + try { + const data = (await resolveRefs(p.data)) as Record + if (!dryRun) { + const full = withHash ? { ...data, [hashField as string]: seedHash(perLocale(data)) } : data + await writeLocales(payload, { id: p.id!, collection }, full, { context, draft }) + } + p.result = { id: p.id, label: `${p.label}${p.id !== undefined && !dryRun ? ` (id ${String(p.id)})` : ''}`, note: localeNote, status: p.action } + } catch (e) { + p.result = { id: p.id, label: p.label, note: (e as Error).message, status: 'error' } + } + } + } + return plan.map((p) => report(p.result!)) + } + + const slugOf = (data: Record, slugField: string) => { + const v = data[slugField] + const slug = isLocalizedValue(v, codes) ? v[defaultLocale as string] : v + if (typeof slug !== 'string' || !slug) {throw new Error(`upsertBySlug: no "${slugField}" in the default locale`)} + return slug + } + + function upsertBySlug(collection: string, data: Record, options?: UpsertOptions): Promise + function upsertBySlug(collection: string, data: Record[], options?: UpsertOptions): Promise + async function upsertBySlug( + collection: string, + data: Record | Record[], + { slugField = 'slug' }: UpsertOptions = {}, + ): Promise { + const list = Array.isArray(data) ? data : [data] + const items = list.map((d) => { + const slug = slugOf(d, slugField) + return { data: d, key: { [slugField]: slug }, label: `${collection} "${slug}"` } + }) + const results = await upsertMany(collection, items) + return Array.isArray(data) ? results : results[0] + } + + const upsertBy: Seeder['upsertBy'] = async (collection, key, data) => + (await upsertMany(collection, [{ data, key, label: `${collection} ${Object.values(key).map((v) => `"${String(v)}"`).join(' ')}` }]))[0] + + const fillGlobal: Seeder['fillGlobal'] = async (slug, data) => { + const label = `global ${slug}` + try { + const target = { global: slug } + const withHash = hasHashField(payload.config.globals.find((g) => g.slug === slug)?.fields as undefined | unknown[]) + const cur = await readSeedTarget(payload, target, defaultLocale) + const empty = Object.keys(data).filter((k) => !hasContent(cur[k])) + let keys = empty + let edited: null | string = null + if (update) { + edited = await editedReason(target, data, withHash, false) + if (!edited || force) {keys = Object.keys(data)} + } + if (!keys.length) { + return report(edited ? { label, note: edited, status: 'skip (edited)' } : { label, note: 'every seeded field has content', status: 'skip (exists)' }) + } + const all = keys.length === Object.keys(data).length + const status: SeedStatus = keys !== empty ? 'update' : edited ? 'skip (edited)' : 'create' + const note = keys !== empty ? localeNote : `${edited ? `${edited}; ` : ''}empty fields filled: ${keys.join(', ')}` + const part = (await resolveRefs(Object.fromEntries(keys.map((k) => [k, data[k]])))) as Record + if (!dryRun) { + // The hash describes the whole seeded set — store it only when every seeded field is written. + const full = all && withHash ? { ...part, [hashField as string]: seedHash(perLocale(part)) } : part + await writeLocales(payload, target, full, { context }) + } + return report({ label, note, status }) + } catch (e) { + return report({ label, note: (e as Error).message, status: 'error' }) + } + } + + const summary = (): SeedSummary => { + const result: SeedSummary = { + created: counts.create, + errors: counts.error, + skipped: counts['skip (exists)'], + skippedEdited: counts['skip (edited)'], + updated: counts.update, + } + log(`\n${label} summary${dryRun ? ' (dry run — nothing written)' : ''}`) + log( + ` created ${result.created} · skipped ${result.skipped} · updated ${result.updated} · skipped-edited ${result.skippedEdited} · errors ${result.errors}`, + ) + return result + } + + return { dryRun, fillGlobal, force, local, summary, update, upsertBy, upsertBySlug } +} diff --git a/src/modules/seed/values.ts b/src/modules/seed/values.ts new file mode 100644 index 0000000..b8ee52b --- /dev/null +++ b/src/modules/seed/values.ts @@ -0,0 +1,184 @@ +import type { BasePayload } from 'payload' + +import { createHash } from 'node:crypto' + +/** + * Seed values — content written once, every language side by side: + * + * heading: { pl: 'Nasze usługi', en: 'Our services' } → localized: one value per locale + * heading: 'Nasze usługi' → the same value in every locale + * + * An object counts as localized when every key is one of the config's locale + * codes. A locale missing from it is left untouched in that locale. + */ +export type SeedValue = { [key: string]: SeedValue } | boolean | null | number | SeedValue[] | string + +/** Locale codes and the default locale of a Payload config ([] / undefined without localization). */ +export function localesOf(payload: BasePayload): { codes: string[]; defaultLocale: string | undefined } { + const loc = payload.config.localization + return loc ? { codes: loc.localeCodes, defaultLocale: loc.defaultLocale } : { codes: [], defaultLocale: undefined } +} + +const isPlainObject = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) + +export function isLocalizedValue(v: unknown, codes: string[]): v is Record { + return isPlainObject(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k)) +} + +/** + * 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. + * 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} + if (Array.isArray(value)) { + const rows = Array.isArray(existing) ? (existing as unknown[]) : [] + return value.map((item, i) => { + const row = rows[i] as Record | undefined + const out = localize(item, locale, row, codes) + 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 } + }) + } + if (isPlainObject(value)) { + const ex = isPlainObject(existing) ? existing : {} + const out: Record = {} + for (const [k, v] of Object.entries(value)) { + const r = localize(v, locale, ex[k], codes) + if (r !== undefined) {out[k] = r} + } + return out + } + return value +} + +/** JSON with sorted keys, no row ids, null = missing — equal content gives equal text. */ +function stable(v: unknown): string { + if (Array.isArray(v)) {return `[${v.map(stable).join(',')}]`} + if (isPlainObject(v)) { + return `{${Object.keys(v) + .filter((k) => k !== 'id' && v[k] != null) + .sort() + .map((k) => `${JSON.stringify(k)}:${stable(v[k])}`) + .join(',')}}` + } + return JSON.stringify(v ?? null) +} + +/** Hash of seeded values: key order, row ids and nulls don't change it. */ +export function seedHash(value: unknown): string { + return createHash('sha256').update(stable(value)).digest('hex').slice(0, 32) +} + +/** The current values at the keys the seed writes — everything else in the record is ignored. */ +export function projectOnto(seed: unknown, current: unknown): unknown { + if (Array.isArray(seed)) { + return Array.isArray(current) && current.length === seed.length ? seed.map((s, i) => projectOnto(s, current[i])) : current + } + if (isPlainObject(seed)) { + if (!isPlainObject(current)) {return current} + return Object.fromEntries(Object.keys(seed).map((k) => [k, projectOnto(seed[k], current[k])])) + } + return current +} + +export type EditedSinceSeedArgs = { + /** + * Hash of the record's CURRENT values at the seeded keys (seedHash of + * projectOnto per locale). Needed only when the record stores a hash. + */ + currentHash?: string + /** The stored record (default locale) — reads createdAt, updatedAt and the hash field. */ + doc: Record + /** Hash field name. Default SEED_HASH_FIELD or 'seedHash'; false = timestamps only. */ + hashField?: false | string + /** "Untouched" window for the timestamp method. Default SEED_UNTOUCHED_SECONDS or 120. */ + untouchedSeconds?: number +} + +export const defaultHashField = (): false | string => { + const v = process.env.SEED_HASH_FIELD + return v === undefined ? 'seedHash' : v || false +} +export const defaultUntouchedSeconds = (): number => { + const n = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120) + return Number.isFinite(n) ? n : 120 +} + +/** + * null when nobody edited the record since seeding; otherwise why it counts + * as edited. A stored hash decides when present; else updatedAt must be at + * most `untouchedSeconds` after createdAt. + */ +export function editedSinceSeed({ + currentHash, + doc, + hashField = defaultHashField(), + untouchedSeconds = defaultUntouchedSeconds(), +}: EditedSinceSeedArgs): null | string { + const stored = hashField ? doc[hashField] : undefined + if (typeof stored === 'string' && stored) { + return currentHash === stored ? null : `${hashField as string} differs` + } + const c = Date.parse(String(doc.createdAt)) + const u = Date.parse(String(doc.updatedAt)) + if (!Number.isFinite(c) || !Number.isFinite(u)) {return 'no createdAt/updatedAt'} + const s = Math.round((u - c) / 1000) + return s <= untouchedSeconds ? null : `updated ${s}s after creation` +} + +export type SeedTarget = { collection: string; id: number | string } | { global: string } + +export type WriteLocalesOptions = { + /** Passed to every write — see docs/seeding.md § Context flags. */ + context?: Record + /** Read the latest draft for row ids (collections with drafts). */ + draft?: boolean +} + +/** Reads a record in one locale, never filling gaps from the fallback locale. */ +export function readSeedTarget(payload: BasePayload, target: SeedTarget, locale: string | undefined, draft = false) { + const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {} + return ('global' in target + ? payload.findGlobal({ slug: target.global as never, depth: 0, ...loc }) + : payload.findByID({ id: target.id, collection: target.collection as never, depth: 0, ...(draft ? { draft } : {}), ...loc })) as Promise< + Record + > +} + +/** + * Writes seed values to an existing record in every locale: the default locale + * first (it creates the rows), then each other locale with + * `fallbackLocale: false` onto the same row ids. + */ +export async function writeLocales( + payload: BasePayload, + target: SeedTarget, + data: Record, + { context = {}, draft = false }: WriteLocalesOptions = {}, +): Promise { + const { codes, defaultLocale } = localesOf(payload) + 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) + 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)} +} + +/** 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} + if (Array.isArray(v)) {return v.some(hasContent)} + if (isPlainObject(v)) {return Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x))} + return false +} diff --git a/test/docsConsistency.test.ts b/test/docsConsistency.test.ts index c9f05e3..93199af 100644 --- a/test/docsConsistency.test.ts +++ b/test/docsConsistency.test.ts @@ -20,6 +20,7 @@ const ENTRIES: Record = { '/env': 'src/exports/env.ts', '/next/middleware': 'src/exports/next-middleware.ts', '/rsc': 'src/exports/rsc.ts', + '/seed': 'src/exports/seed.ts', '/server': 'src/exports/server.ts', } diff --git a/test/seed.test.ts b/test/seed.test.ts new file mode 100644 index 0000000..cb25586 --- /dev/null +++ b/test/seed.test.ts @@ -0,0 +1,291 @@ +import type { Payload } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'node:os' +import path from 'node:path' +import { buildConfig, getPayload } from 'payload' +import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' + +import { createSeeder, editedSinceSeed, isLocalDatabase, seedHash } from '../src/exports/seed.js' +import { ipalKit } from '../src/plugin.js' + +vi.mock('server-only', () => ({})) + +const flush = () => new Promise((r) => setTimeout(r, 0)) + +describe('isLocalDatabase', () => { + test.each([ + ['file:./dev.db', true], + ['file::memory:', true], + ['./payload.sqlite', true], + ['postgres://u:p@localhost:5432/app', true], + ['postgres://u:p@127.0.0.1/app', true], + ['postgres://u:p@[::1]:5432/app', true], + ['postgres:///app', true], + ['postgres://u:p@x/app?host=/var/run/postgresql', true], + ['postgres://u:p@db:5432/app', false], + ['mongodb+srv://u:p@cluster.mongodb.net/app', false], + ['mongodb://a:1,b:2/app', false], + ['', false], + [undefined, false], + ])('%s → %s', (url, local) => { + expect(isLocalDatabase(url, { localHosts: [] })).toBe(local) + }) + + test('extra local hosts (option or SEED_LOCAL_HOSTS)', () => { + expect(isLocalDatabase('postgres://u:p@db:5432/app', { localHosts: ['db'] })).toBe(true) + vi.stubEnv('SEED_LOCAL_HOSTS', 'db, postgres') + expect(isLocalDatabase('postgres://u:p@postgres:5432/app')).toBe(true) + vi.unstubAllEnvs() + }) +}) + +describe('editedSinceSeed / seedHash', () => { + const at = (s: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, s)).toISOString() + + test('timestamps: inside the window = untouched, later = edited', () => { + expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(5) }, hashField: false })).toBeNull() + expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(500) }, hashField: false })).toMatch(/updated 500s after creation/) + expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(500) }, hashField: false, untouchedSeconds: 600 })).toBeNull() + expect(editedSinceSeed({ doc: {}, hashField: false })).toBe('no createdAt/updatedAt') + }) + + test('a stored hash decides over timestamps', () => { + const doc = { createdAt: at(0), seedHash: seedHash({ a: 1 }), updatedAt: at(9000) } + expect(editedSinceSeed({ currentHash: seedHash({ a: 1 }), doc })).toBeNull() + expect(editedSinceSeed({ currentHash: seedHash({ a: 2 }), doc })).toBe('seedHash differs') + }) + + test('seedHash ignores key order, row ids and nulls', () => { + // eslint-disable-next-line perfectionist/sort-objects -- key order is what this checks + expect(seedHash({ a: 1, b: [{ id: 'x', t: 'q' }], c: null })).toBe(seedHash({ b: [{ t: 'q' }], a: 1 })) + expect(seedHash({ a: 1 })).not.toBe(seedHash({ a: 2 })) + }) +}) + +/** createSeeder against a real (SQLite) Payload with pl/en and localization.fallback on. */ +describe('createSeeder', () => { + let payload: Payload + const lines: string[] = [] + const log = (line: string) => { + lines.push(line) + } + const seeder = (opts: Parameters[1] = {}) => createSeeder(payload, { dryRun: false, log, update: false, ...opts }) + + beforeAll(async () => { + vi.stubEnv('DATABASE_URI', 'file::memory:') + const config = buildConfig({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + { + slug: 'pages', + fields: [ + { name: 'title', type: 'text', localized: true }, + { name: 'slug', type: 'text', index: true, localized: true }, + { + name: 'rows', + type: 'array', + fields: [ + { name: 'text', type: 'text', localized: true }, + { name: 'page', type: 'relationship', relationTo: 'pages' }, + ], + }, + ], + versions: { drafts: true }, + }, + { + slug: 'posts', + fields: [ + { name: 'title', type: 'text', localized: true }, + { name: 'slug', type: 'text', localized: true }, + { name: 'seedHash', type: 'text', admin: { hidden: true } }, + ], + }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed') } }, + ], + db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), + editor: lexicalEditor(), + globals: [ + { + slug: 'header', + fields: [ + { name: 'tagline', type: 'text', localized: true }, + { name: 'phone', type: 'text' }, + { name: 'links', type: 'array', fields: [{ name: 'label', type: 'text', localized: true }] }, + ], + }, + ], + localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] }, + plugins: [ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })], + secret: 'seed-test-secret', + telemetry: false, + }) + payload = await getPayload({ config }) + }, 60_000) + + afterEach(() => { + lines.length = 0 + vi.restoreAllMocks() + vi.unstubAllEnvs() + vi.stubEnv('DATABASE_URI', 'file::memory:') + }) + + afterAll(async () => { + vi.unstubAllEnvs() + await payload?.destroy() + }) + + const readPage = (id: number | string, locale: 'en' | 'pl') => + payload.findByID({ id, collection: 'pages', depth: 0, draft: true, fallbackLocale: false as never, locale }) + + test('creates missing pages in every locale, resolves $page links, keeps row ids, then skips', async () => { + const PAGES = [ + { + slug: { en: 'home', pl: 'start' }, + rows: [{ page: { $page: 'kontakt' }, text: { en: 'Write to us', pl: 'Napisz do nas' } }, { text: { en: 'Second', pl: 'Drugi' } }], + title: { en: 'Home', pl: 'Strona główna' }, + }, + { slug: { en: 'contact', pl: 'kontakt' }, title: { en: 'Contact', pl: 'Kontakt' } }, + ] + const seed = seeder() + const results = await seed.upsertBySlug('pages', PAGES) + expect(results.map((r) => r.status)).toEqual(['create', 'create']) + + const [home, contact] = results + const pl = await readPage(home.id!, 'pl') + const en = await readPage(home.id!, 'en') + expect(pl.title).toBe('Strona główna') + expect(en.title).toBe('Home') + expect(en.slug).toBe('home') + expect((pl.rows as { id: string }[]).map((r) => r.id)).toEqual((en.rows as { id: string }[]).map((r) => r.id)) + expect((pl.rows as { text: string }[])[0].text).toBe('Napisz do nas') + expect((en.rows as { page: unknown; text: string }[])[0]).toMatchObject({ page: contact.id, text: 'Write to us' }) + + const again = seeder() + expect((await again.upsertBySlug('pages', PAGES)).map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)']) + expect(again.summary()).toEqual({ created: 0, errors: 0, skipped: 2, skippedEdited: 0, updated: 0 }) + expect(lines.join('\n')).toMatch(/skip \(exists\)\s+pages "start"/) + }) + + test('fallbackLocale: false — a locale missing from the seed is not filled with the default text', async () => { + const r = await seeder().upsertBySlug('pages', { slug: { pl: 'tylko-pl' }, title: { pl: 'Tylko po polsku' } }) + const en = await readPage(r.id!, 'en') + expect(en.title ?? null).toBeNull() + }) + + test('dry run writes nothing and reports the plan', async () => { + const seed = seeder({ dryRun: true }) + const r = await seed.upsertBySlug('pages', { slug: { pl: 'nowa' }, rows: [{ page: { $page: 'nowa' } }], title: { pl: 'Nowa' } }) + expect(r.status).toBe('create') + expect((await payload.find({ collection: 'pages', where: { slug: { equals: 'nowa' } } })).totalDocs).toBe(0) + expect(seed.summary().created).toBe(1) + expect(lines.join('\n')).toMatch(/DRY RUN/) + }) + + test('update: untouched records are updated, records edited since seeding are skipped', async () => { + const first = await seeder().upsertBySlug('pages', { slug: { pl: 'oferta' }, title: { en: 'Offer', pl: 'Oferta' } }) + const edited = await seeder().upsertBySlug('pages', { slug: { pl: 'o-nas' }, title: { pl: 'O nas' } }) + // An editor saves "o-nas" 10 minutes after it was created. + vi.useFakeTimers({ now: Date.now() + 600_000, toFake: ['Date'] }) + await payload.update({ id: edited.id!, collection: 'pages', data: { title: 'O nas — poprawione' }, locale: 'pl' }) + vi.useRealTimers() + + const seed = seeder({ update: true }) + const up = await seed.upsertBySlug('pages', [ + { slug: { pl: 'oferta' }, title: { en: 'Our offer', pl: 'Nasza oferta' } }, + { slug: { pl: 'o-nas' }, title: { pl: 'O nas (seed)' } }, + ]) + expect(up.map((r) => r.status)).toEqual(['update', 'skip (edited)']) + expect(up[1].note).toMatch(/after creation/) + expect((await readPage(first.id!, 'en')).title).toBe('Our offer') + expect((await readPage(edited.id!, 'pl')).title).toBe('O nas — poprawione') + expect(seed.summary()).toMatchObject({ skippedEdited: 1, updated: 1 }) + }) + + test('hash field: repeated updates while untouched; an editor change is detected', async () => { + const created = await seeder().upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post', pl: 'Wpis' } }) + vi.useFakeTimers({ now: Date.now() + 600_000, toFake: ['Date'] }) + // Timestamps alone would call this edited — the stored hash says it is untouched. + expect((await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 2', pl: 'Wpis 2' } })).status).toBe('update') + expect((await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 3', pl: 'Wpis 3' } })).status).toBe('update') + await payload.update({ id: created.id!, collection: 'posts', data: { title: 'Changed by an editor' }, locale: 'en' }) + const r = await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 4', pl: 'Wpis 4' } }) + vi.useRealTimers() + expect(r).toMatchObject({ note: 'seedHash differs', status: 'skip (edited)' }) + expect((await payload.findByID({ id: created.id!, collection: 'posts', locale: 'en' })).title).toBe('Changed by an editor') + }) + + test('upsertBy matches a natural key', async () => { + expect((await seeder().upsertBy('posts', { title: 'Formularz' }, { slug: 'formularz', title: 'Formularz' })).status).toBe('create') + expect((await seeder().upsertBy('posts', { title: 'Formularz' }, { slug: 'x', title: 'Formularz' })).status).toBe('skip (exists)') + }) + + test('fillGlobal fills only empty fields, in every locale', async () => { + await payload.updateGlobal({ slug: 'header', data: { phone: '+48 600 000 000' } }) + const seed = seeder() + const r = await seed.fillGlobal('header', { + links: [{ label: { en: 'Contact', pl: 'Kontakt' } }], + phone: '+48 111 111 111', + tagline: { en: 'Hello', pl: 'Cześć' }, + }) + expect(r.status).toBe('create') + expect(r.note).toBe('empty fields filled: links, tagline') + const pl = await payload.findGlobal({ slug: 'header', fallbackLocale: false as never, locale: 'pl' }) + const en = await payload.findGlobal({ slug: 'header', fallbackLocale: false as never, locale: 'en' }) + expect(pl.phone).toBe('+48 600 000 000') + expect(pl.tagline).toBe('Cześć') + expect(en.tagline).toBe('Hello') + expect((en.links as { id: string; label: string }[])[0]).toMatchObject({ id: (pl.links as { id: string }[])[0].id, label: 'Contact' }) + expect((await seeder().fillGlobal('header', { tagline: { pl: 'Inne' } })).status).toBe('skip (exists)') + }) + + test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => { + vi.stubEnv('NODE_ENV', 'production') + expect(() => seeder({ update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/) + expect(() => seeder()).not.toThrow() // create-only is always allowed + vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') + expect(seeder({ update: true }).update).toBe(true) + expect(lines.join('\n')).toMatch(/Did you back it up/) + + vi.unstubAllEnvs() + vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app') + expect(() => seeder({ update: true })).toThrow(/the database is not local/) + expect(() => seeder({ guard: { localHosts: ['db'] }, update: true })).not.toThrow() + expect(() => seeder({ guard: false, update: true })).not.toThrow() + vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') + expect(() => seeder({ force: true, update: true })).toThrow(/force refused/) + }) + + test('env defaults: SEED_DRY_RUN, SEED_UPDATE', () => { + vi.stubEnv('SEED_DRY_RUN', '1') + vi.stubEnv('SEED_UPDATE', '1') + const s = createSeeder(payload, { log }) + expect(s.dryRun).toBe(true) + expect(s.update).toBe(true) + }) + + test('seed writes skip IndexNow; a normal save still pings', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 })) + vi.stubEnv('NODE_ENV', 'production') + vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl') + vi.stubEnv('INDEXNOW_KEY', 'k123') + + const seed = seeder({ update: true }) + await seed.upsertBySlug('pages', [ + { slug: { en: 'news', pl: 'aktualnosci' }, _status: 'published', title: { en: 'News', pl: 'Aktualności' } }, + { slug: { pl: 'oferta' }, _status: 'published', title: { pl: 'Oferta po aktualizacji' } }, + ]) + await seed.fillGlobal('header', { phone: '+48 1' }) + await flush() + await flush() + expect(fetchSpy).not.toHaveBeenCalled() + + const page = await payload.create({ collection: 'pages', data: { slug: 'zwykla', _status: 'published', title: 'Zwykła' }, locale: 'pl' }) + await flush() + await flush() + expect(fetchSpy).toHaveBeenCalled() + expect(page.id).toBeDefined() + }) +})