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 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b61b753ec2
commit
cff76c2a69
@@ -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']
|
||||
}
|
||||
@@ -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'
|
||||
@@ -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:<key>)` 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<string, unknown>
|
||||
/** 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: '<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
|
||||
/** 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 }
|
||||
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<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 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`,
|
||||
)
|
||||
|
||||
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<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).
|
||||
* 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 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<string, unknown> = {}
|
||||
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<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, items: Item[]): Promise<SeedResult[]> => {
|
||||
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<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' }
|
||||
}
|
||||
}
|
||||
}
|
||||
return plan.map((p) => report(p.result!))
|
||||
}
|
||||
|
||||
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}"` }
|
||||
})
|
||||
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<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 => {
|
||||
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 }
|
||||
}
|
||||
@@ -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<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
|
||||
|
||||
export function isLocalizedValue(v: unknown, codes: string[]): v is Record<string, unknown> {
|
||||
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<string, unknown> | 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<string, unknown> = {}
|
||||
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<string, unknown>
|
||||
/** 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<string, unknown>
|
||||
/** 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<string, unknown>
|
||||
>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, unknown>,
|
||||
{ context = {}, draft = false }: WriteLocalesOptions = {},
|
||||
): Promise<void> {
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user