import type { BasePayload } from 'payload' import type { SeedTarget } from './values.js' import { activeSeedExitGuard } from './exitGuard.js' import { isLocalDatabase, seedDatabaseUrl } from './guard.js' import { defaultHashField, defaultUntouchedSeconds, editedSinceSeed, isLocalizedValue, isUnsetValue, 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; * - after launch a seed touches named records only (`only` / SEED_ONLY): a run with no * record list is refused on production / a non-local database unless IPAL_SEED_ALLOW_FULL=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)' | 'skip (not listed)' | '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 /** Records left out because they are not in `only`. */ notListed: 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 /** Collection `{ $form: '' }` references resolve in. Default 'forms'. */ formsCollection?: string /** * 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?: | { /** * A run without `only` on production / a non-local database (a full seed of a live site). * Default IPAL_SEED_ALLOW_FULL=1 — only with the owner's explicit OK. */ allowFull?: boolean /** 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 /** * The records this run may touch — everything else is reported as `skip (not listed)`. * `'pages:kontakt'` (collection + default-locale slug, or the `upsertBy` key values joined * with `|`), `'forms:Contact form'`, `'global:header'`, or `'pages:*'` for a whole collection. * Default SEED_ONLY (comma-separated). Undefined = every record (a full seed — refused on a * live database, see `guard.allowFull`). */ only?: string[] /** Collection `{ $page: '<slug>' }` 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<string, unknown>) => Promise<SeedResult> readonly force: boolean readonly local: boolean /** The record list (`only`), or null for a full seed. */ readonly only: null | string[] /** 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<string, number | string>, data: Record<string, unknown>) => Promise<SeedResult> /** * 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<string, unknown>, options?: UpsertOptions): Promise<SeedResult> (collection: string, data: Record<string, unknown>[], options?: UpsertOptions): Promise<SeedResult[]> } } const DEFAULT_CONTEXT = { disableRevalidate: true, ipalSeed: true, ipalSkipIndexNow: true } const defaultLog = (line: string) => { process.stdout.write(`${line}\n`) } type Item = { data: Record<string, unknown>; key: Record<string, number | string>; label: string; ref: string } type Planned = { action?: 'create' | 'update'; id?: number | string; result?: SeedResult } & Item const formRef = (v: object): string | undefined => { const ref = (v as { $form?: unknown }).$form return typeof ref === 'string' ? ref : undefined } const pageRef = (v: object): string | undefined => { const ref = (v as { $page?: unknown }).$page return typeof ref === 'string' ? ref : undefined } /** The default-locale slugs of the { $page } references a value holds. */ const pageRefsIn = (v: unknown, out = new Set<string>()): Set<string> => { if (Array.isArray(v)) {v.forEach((x) => pageRefsIn(x, out))} else if (v && typeof v === 'object') { const ref = pageRef(v) if (ref !== undefined) {out.add(ref)} else {Object.values(v).forEach((x) => pageRefsIn(x, out))} } return out } export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder { // Payload is up (the caller passed it in) — the run's exit guard, if any, now waits for summary() activeSeedExitGuard()?.initialized() 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 formsCollection = options.formsCollection ?? 'forms' const context = { ...DEFAULT_CONTEXT, ...options.context } const onlyList = options.only ?? (env.SEED_ONLY ? env.SEED_ONLY.split(',') : undefined) const only = onlyList ? onlyList.map((r) => r.trim()).filter(Boolean) : null 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' const allowFull = guard.allowFull ?? env.IPAL_SEED_ALLOW_FULL === '1' if (!dryRun && !only?.length && prodLike && !allowFull) { throw new Error( `${label} full seed refused: ${production ? 'NODE_ENV=production' : 'the database is not local'} and no record list.\n` + ' A live site keeps the owner\'s edits — after launch a seed touches named records only.\n' + ' 1. List them: SEED_ONLY="pages:kontakt,global:header" (or createSeeder(payload, { only: [...] })).\n' + ' 2. Run with SEED_DRY_RUN=1 and read the plan; back up the database.\n' + ' 3. A full seed of a live database only with the owner\'s explicit OK: IPAL_SEED_ALLOW_FULL=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<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, 'skip (not listed)': 0, update: 0 } const pageIds = new Map<string, number | string>() /** Forms planned for creation in a dry run, by title — a later { $form } to them is not an error. */ const plannedForms = new Set<string>() log( `${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'} · ${only ? `only: ${only.join(', ')}` : 'all records'}\n`, ) const report = (result: SeedResult): SeedResult => { counts[result.status]++ log(`${result.status.padEnd(14)} ${result.label}${result.note ? ` — ${result.note}` : ''}`) return result } /** Is this record on the run's list? `collection:*` lists a whole collection. */ const listed = (ref: string) => !only || only.includes(ref) || only.includes(`${ref.slice(0, ref.indexOf(':'))}:*`) const notListed = (label: string): SeedResult => ({ label, note: 'not in the record list (only / SEED_ONLY)', status: 'skip (not listed)' }) 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<string, number | string>) => { 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) * and { $form: title } with the form id (forms are seeded before the pages that use them). * lenient: an unknown page gives a placeholder instead of an error (edit check before pass 1). */ const resolveRefs = async (v: unknown, lenient = false): Promise<unknown> => { if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveRefs(x, lenient)))} if (!v || typeof v !== 'object') {return v} const form = formRef(v) if (form !== undefined) { const id = await findId(formsCollection, { title: form }) if (id !== undefined) {return id} // A dry run reports what the real run would do: a form planned earlier in this run will exist. if (lenient || (dryRun && plannedForms.has(form))) {return `(form:${form})`} throw new Error(`$form "${form}" not found — seed that form first or create it in the panel`) } const ref = pageRef(v) if (ref !== undefined) { 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<string, unknown> = {} for (const [k, x] of Object.entries(v)) {out[k] = await resolveRefs(x, lenient)} return out } /** * The first-pass value of a record being created: references to records that exist now become their ids, * so a required field (a layout whose block links to a page) is written complete. A { $page } to a page * planned in the same call and not created yet (`forward`) becomes null and is collected; pass 2 writes it. * Any other unknown target throws — nothing is written for that record. */ const resolveForCreate = async (v: unknown, forward: Set<string>, planned: Set<string>): Promise<unknown> => { if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveForCreate(x, forward, planned)))} if (!v || typeof v !== 'object') {return v} if (formRef(v) !== undefined) {return resolveRefs(v)} const ref = pageRef(v) if (ref !== undefined) { const known = pageIds.get(ref) ?? (await findId(pagesCollection, { slug: ref })) if (known !== undefined) { pageIds.set(ref, known) return known } if (planned.has(ref)) { forward.add(ref) return null } throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`) } const out: Record<string, unknown> = {} for (const [k, x] of Object.entries(v)) {out[k] = await resolveForCreate(x, forward, planned)} return out } /** Per-locale seed values (refs resolved) — what the hash describes. */ const perLocale = (data: unknown) => Object.fromEntries(localeKeys.map((l) => [l ?? '-', localize(data, l, undefined, codes)])) const editedReason = async (target: SeedTarget, data: Record<string, unknown>, 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<string, unknown> = {} 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, all: Item[]): Promise<SeedResult[]> => { const items = all.filter((item) => listed(item.ref)) 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[] = [] const plannedHere = new Set(trackPages ? items.map((i) => i.key.slug).filter((s): s is string => typeof s === 'string') : []) for (const item of items) { const p: Planned = { ...item } plan.push(p) try { p.id = await findId(collection, item.key) const slug = typeof item.key.slug === 'string' ? item.key.slug : undefined if (p.id === undefined) { // Every { $page } must exist already or be planned in this call — otherwise nothing is written (dry run too). for (const ref of pageRefsIn(item.data)) { if (plannedHere.has(ref) || pageIds.has(ref) || (await findId(pagesCollection, { slug: ref })) !== undefined) {continue} throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`) } p.action = 'create' if (dryRun && trackPages && slug) {pageIds.set(slug, `(new:${slug})`)} if (dryRun && collection === formsCollection && typeof item.key.title === 'string') {plannedForms.add(item.key.title)} continue } if (trackPages && slug) {pageIds.set(slug, p.id)} 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 complete — references to existing records resolved. A forward { $page } // (a page created later in this call) is null for now; a record whose required field needs it is retried // once that page exists. Required references in a cycle, or to a page that never appears, are an error // and nothing is written for those records. if (!dryRun) { const waiting = plan.filter((p) => p.action === 'create' && !p.result) const planned = new Set(trackPages ? waiting.map((p) => p.key.slug).filter((s): s is string => typeof s === 'string') : []) const blocked = new Map<Planned, { error: string; forward: Set<string> }>() let progress = true while (waiting.length && progress) { progress = false for (const p of [...waiting]) { const forward = new Set<string>() try { const first = (await resolveForCreate(p.data, forward, planned)) as Record<string, unknown> const created = await payload.create({ collection: collection as never, context, data: localize(first, defaultLocale, undefined, codes) as never, depth: 0, ...(defaultLocale ? { locale: defaultLocale as never } : {}), }) p.id = (created as { id: number | string }).id const slug = p.key.slug if (trackPages && typeof slug === 'string') { pageIds.set(slug, p.id) planned.delete(slug) } waiting.splice(waiting.indexOf(p), 1) blocked.delete(p) progress = true } catch (e) { if (forward.size) { // Valid only once the pages it links to exist — try again after the others. blocked.set(p, { error: (e as Error).message, forward }) continue } p.result = { label: p.label, note: (e as Error).message, status: 'error' } p.action = undefined waiting.splice(waiting.indexOf(p), 1) } } } for (const p of waiting) { const why = blocked.get(p) const targets = [...(why?.forward ?? [])].map((s) => `"${s}"`).join(', ') p.result = { label: p.label, note: `required references to pages not created yet (${targets}) — a cycle of required links; make one link optional or seed that page first${why ? ` (${why.error})` : ''}`, status: 'error', } p.action = undefined } } // Pass 2: full content in every locale (dry run: resolve refs to report broken ones). for (const p of plan) { if (p.action && !p.result) { try { const data = (await resolveRefs(p.data)) as Record<string, unknown> 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' } } } } // Results in the caller's order; records off the list are reported, never touched. const done = new Map(plan.map((p) => [p.ref, p.result!])) return all.map((item) => report(done.get(item.ref) ?? notListed(item.label))) } const slugOf = (data: Record<string, unknown>, 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<string, unknown>, options?: UpsertOptions): Promise<SeedResult> function upsertBySlug(collection: string, data: Record<string, unknown>[], options?: UpsertOptions): Promise<SeedResult[]> async function upsertBySlug( collection: string, data: Record<string, unknown> | Record<string, unknown>[], { slugField = 'slug' }: UpsertOptions = {}, ): Promise<SeedResult | SeedResult[]> { 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}"`, ref: `${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(' ')}`, ref: `${collection}:${Object.values(key).map(String).join('|')}`, }]))[0] const fillGlobal: Seeder['fillGlobal'] = async (slug, data) => { const label = `global ${slug}` if (!listed(`global:${slug}`)) {return report(notListed(label))} try { const target = { global: slug } const global = payload.config.globals.find((g) => g.slug === slug) const withHash = hasHashField(global?.fields as undefined | unknown[]) const fieldOf = (name: string) => (global?.flattenedFields as { defaultValue?: unknown; name?: string; type?: string }[] | undefined)?.find((f) => f.name === name) const cur = await readSeedTarget(payload, target, defaultLocale) // Empty, or a choice still at its default value (e.g. Theme → light): never text an editor wrote. // A field already holding exactly the seeded value is left alone (no write, reported as skip). const same = (k: string) => JSON.stringify(cur[k]) === JSON.stringify(localize(data[k], defaultLocale, cur[k], codes)) const empty = Object.keys(data).filter((k) => isUnsetValue(cur[k], fieldOf(k)) && !same(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<string, unknown> 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 => { activeSeedExitGuard()?.finished() const result: SeedSummary = { created: counts.create, errors: counts.error, notListed: counts['skip (not listed)'], 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} · not listed ${result.notListed} · errors ${result.errors}`, ) return result } return { dryRun, fillGlobal, force, local, only, summary, update, upsertBy, upsertBySlug } }