Seeds: guardSeedExit() — a run that ends early exits 1 with the reason, never a silent 0

payload run starts the CLI with `void start()` and imports the script; when the script's top-level await
is left without live handles, Node exits with code 0 and no output — a success in Coolify's Terminal.
guardSeedExit() (@intecion/ipal-kit/seed, dependency-free) listens for beforeExit: until summary() runs it
prints "[seed] ended before Payload initialized" / "… before the seed finished" and exits 1. createSeeder
marks the run initialized, summary() finished; process.exit paths (normal, errors, the production
refusals) are untouched. Wired into the ipal-site and ipal-form seed templates and the reference seed, so
ipal-kit create sites get it. Tests include a real child process started like payload run.
Docs: seeding.md, deployment.md §4.7, AGENT.md, ipal-reference (+ api.md), CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 19:19:14 +01:00
co-authored by Claude Opus 5.5
parent 55dc69b69f
commit f789e36636
14 changed files with 277 additions and 9 deletions
+17
View File
@@ -8,6 +8,23 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## Unreleased
A seed run that stops early now fails loudly instead of looking like a success.
### New
- `guardSeedExit()` in `@intecion/ipal-kit/seed` ([seeding.md](./seeding.md)): call it first in a seed script. A run that
ends before Payload initializes or before `summary()` — `payload run` exits with code 0 and no output when the
script's top-level await is left without anything that keeps Node running — now prints `[seed] ended before Payload
initialized` / `… before the seed finished` and exits 1. `createSeeder` and `summary()` report to it; normal runs, dry
runs, write errors and the production refusals keep their exit codes and messages. Also `activeSeedExitGuard()` and
the types `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`.
- The seed templates (`ipal-site`, `ipal-form`) and the reference site call it, so sites made with `ipal-kit create` have it.
### Requires project changes
- Recommended: add `guardSeedExit()` (imported from `@intecion/ipal-kit/seed`) as the first statement of every seed
script, before `getPayload()`. Without it nothing changes.
## 1.15.0
A new site in one command (`ipal-kit create`), built from a complete reference site; `ipal-doctor`, which checks any site
+2
View File
@@ -51,6 +51,8 @@ stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (d
**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:
- Call `guardSeedExit()` first in every seed script (before `getPayload`): a run that ends early exits 1 with the reason
instead of a silent 0 that looks like success in Coolify's Terminal.
- 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 }`.
@@ -25,7 +25,7 @@
* `email` field (no extra recipients, no header injection).
*/
import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
// ─── fill from the brief ────────────────────────────────────────────────────
@@ -104,6 +104,8 @@ function richText(text: string) {
}
}
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
guardSeedExit({ label: '[seed-form]' })
const payload = await getPayload({ config })
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file.
// A form seed touches exactly one record — this form (matched by its title). After launch that stays true:
+1 -1
View File
@@ -248,7 +248,7 @@ 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) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). 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`.
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). 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), with `guardSeedExit()` called first (an early exit → exit 1 with the reason, never a silent 0). 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 |
|---|---|
@@ -562,13 +562,14 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `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`).
**Types:** `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess` — the early-exit guard; `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`
@@ -32,7 +32,7 @@
*/
import config from '@payload-config'
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { pageTemplates } from '@intecion/ipal-kit/templates'
import { getPayload } from 'payload'
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
const ONLY: string[] | undefined = undefined
// ----------------------------------------------------------------- /CONTENT --
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
guardSeedExit()
// 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 }), { only: ONLY, pagesCollection: COLLECTION })
+4 -1
View File
@@ -387,7 +387,10 @@ For a seed (script, flags and data format: [seeding.md](./seeding.md)):
1. **dry run** — `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts`, read the planned changes;
2. **Backup now** on the database (§4.6);
3. the real run; check the panel and the site.
3. the real run; check the panel and the site;
4. `echo $?` — `0` after the summary means done. `1` with `[seed] ended before Payload initialized` (or `… before the
seed finished`) means the run stopped early and silently would have looked like a success — the seed's
`guardSeedExit()` caught it (seeding.md); run it again.
The seed script and its dependencies must be in the image (they are when Coolify builds from the whole repo).
+26 -2
View File
@@ -152,6 +152,8 @@ Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSe
— the plan must name only the records the owner asked for.
3. Back up the database (**Backup now**).
4. The real run, without `SEED_DRY_RUN`.
5. Check the exit code (`echo $?`): `0` with the summary means done. A run that stops early prints
`[seed] ended before …` and exits `1` (`guardSeedExit`, below) — run it again; nothing after that point was written.
The seed script and its dependencies must be in the image. Env vars (`DATABASE_URI`, `PAYLOAD_SECRET`, …)
must be available at runtime, not only at build time. The container already has `NODE_ENV=production`, so
@@ -178,9 +180,10 @@ 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 { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
guardSeedExit() // first — an early exit becomes exit 1 with the reason, never a silent 0
const seed = createSeeder(await getPayload({ config }))
await seed.upsertBySlug('pages', [
{ title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] },
@@ -211,6 +214,26 @@ Each method prints one line per record (see [Running a seed](#running-a-seed)) a
with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production
guard refuses the run.
### A run that ends early fails loudly — `guardSeedExit()`
`payload run` starts the CLI with `void start()` and then imports the script. When the script's top-level
`await getPayload()` (or a later await) is left with nothing that keeps Node's event loop alive, Node simply exits:
**code 0, no output** — in Coolify's Terminal that looks exactly like a successful seed. Call `guardSeedExit()` first
in every seed script (the templates and the reference site do):
| The run | Exit | What you see |
|---|---|---|
| ends before Payload initialized | 1 | `[seed] ended before Payload initialized — the run stopped early …` |
| ends after `createSeeder` but before `summary()` | 1 | `[seed] ended before the seed finished — …` |
| finishes: `summary()`, then `process.exit(errors ? 1 : 0)` (or ends naturally after the summary, e.g. a dry run) | 0 / 1 | the summary, as before |
| a write fails | 1 | the `error` lines and the summary, as before |
| the production guard refuses (`full seed refused`, `update refused`) or the script throws | 1 | the error, as before (`payload run` prints it) |
`createSeeder` marks the run initialized and `summary()` marks it finished, so the guard needs nothing else.
`guardSeedExit({ label: '[seed-form]', log, process })` — label of the message, where it goes (default stderr), and
the process (tests). `dispose()` stops watching. Check: `pnpm seed` with a reachable database prints the summary as
before; an interrupted run prints the line above and `echo $?` shows `1`.
On a collection with drafts the helper reads the latest draft, both to match records and to tell
whether an editor changed them.
@@ -218,13 +241,14 @@ whether an editor changed them.
| Export | Use |
|---|---|
| `guardSeedExit({ label, log, process })` | the early-exit guard above → `{ initialized, finished, dispose, state }`; `activeSeedExitGuard()` returns the current one (`createSeeder` and `summary()` report to it) |
| `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`,
Types: `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`, `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`,
`UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`.
## Turn off, override, extend