Database naming rule; seeding after launch touches named records only

- Rule (VERY IMPORTANT): databases are named <domain without dots>_prod /
  _dev (intecion.com → intecioncom_prod / intecioncom_dev) on MongoDB and
  Postgres — AGENT.md top rules, deployment.md §4.2a (Coolify), env.md,
  ipal-setup architecture questions (derive, then confirm), AGENTS.md
  template. ipalEnvRules({ databaseName }) warns (never fails) on a
  mismatch, domain from NEXT_PUBLIC_SERVER_URL or { domain }, { warn }
  overridable; helpers databaseNamesFor, databaseNameFromUri,
  checkDatabaseName from the root and /env.
- Rule (VERY IMPORTANT): after launch never re-seed everything — AGENT.md,
  seeding.md, ipal-site, ipal-form, ipal-reference. createSeeder gains
  `only` / SEED_ONLY (pages:slug, forms:title, global:slug, collection:*;
  the rest → "skip (not listed)") and refuses a run with no record list
  against a production / non-local database unless IPAL_SEED_ALLOW_FULL=1
  (guard.allowFull; dry runs allowed). Seed templates carry an ONLY list;
  the form seed touches only its own form.
- Tests: seed only/full-run guard, database-name helpers and warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 13:27:46 +01:00
co-authored by Claude Opus 5.5
parent 9ecab39783
commit af7d96f0e3
19 changed files with 331 additions and 46 deletions
+53 -10
View File
@@ -29,6 +29,8 @@ import {
* - `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.
*
@@ -36,7 +38,7 @@ import {
* package throws outside a bundled server, and `payload run` is plain Node.
*/
export type SeedStatus = 'create' | 'error' | 'skip (edited)' | 'skip (exists)' | 'update'
export type SeedStatus = 'create' | 'error' | 'skip (edited)' | 'skip (exists)' | 'skip (not listed)' | 'update'
export type SeedResult = {
/** Record id; a placeholder `(new:<key>)` for a planned create in a dry run. */
@@ -50,6 +52,8 @@ export type SeedResult = {
export type SeedSummary = {
created: number
errors: number
/** Records left out because they are not in `only`. */
notListed: number
skipped: number
skippedEdited: number
updated: number
@@ -83,6 +87,11 @@ export type SeederOptions = {
*/
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). */
@@ -99,6 +108,14 @@ export type SeederOptions = {
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. */
@@ -120,6 +137,8 @@ export type Seeder = {
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
@@ -142,7 +161,7 @@ const defaultLog = (line: string) => {
process.stdout.write(`${line}\n`)
}
type Item = { data: Record<string, unknown>; key: Record<string, number | string>; label: string }
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 hasRef = (v: unknown): boolean =>
@@ -162,12 +181,24 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
const untouchedSeconds = options.editCheck?.untouchedSeconds ?? defaultUntouchedSeconds()
const pagesCollection = options.pagesCollection ?? 'pages'
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` +
@@ -184,11 +215,11 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
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, update: 0 }
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>()
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`,
`${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 => {
@@ -197,6 +228,10 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
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)
@@ -262,7 +297,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
return editedSinceSeed({ currentHash, doc, hashField: withHash ? hashField : false, untouchedSeconds })
}
const upsertMany = async (collection: string, items: Item[]): Promise<SeedResult[]> => {
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
@@ -334,7 +370,9 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
}
}
}
return plan.map((p) => report(p.result!))
// 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) => {
@@ -354,17 +392,21 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
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}"` }
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(' ')}` }]))[0]
(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 withHash = hasHashField(payload.config.globals.find((g) => g.slug === slug)?.fields as undefined | unknown[])
@@ -398,16 +440,17 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
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} · errors ${result.errors}`,
` 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, summary, update, upsertBy, upsertBySlug }
return { dryRun, fillGlobal, force, local, only, summary, update, upsertBy, upsertBySlug }
}