Compare commits

..
5 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 a515bd6851 1.15.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.1" section. PROGRAMISTA §6: item 56. Reference site: skills
and the AGENTS.md pointer on 1.15.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 09bff6a683 1.15.1
Version bump; the Unreleased section becomes 1.15.1: guardSeedExit() (a seed that
ends early exits 1 with the reason), wired into the seed templates and the
reference site; reference smoke tests start their own server. What projects must
update: nothing required; add guardSeedExit(), check echo $? after a seed in Coolify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 e715b5720d Reference smoke tests never test another project's server; skills refreshed
- reference/playwright.config.ts: reuseExistingServer only with E2E_REUSE_SERVER=1.
  Playwright starts the built site itself on E2E_BASE_URL's port (default 3100) and
  fails when the port is taken — before, a dev server of another project on 3100
  (intecion.com's) was tested instead. CI is unchanged: it starts nothing before
  test:e2e. README's production check follows.
- reference/.agents/skills refreshed after the seed-exit-guard merge (ipal-form and
  ipal-site seed templates, ipal-reference); INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:24:05 +01:00
Radosław Smoliński 03515c66c4 Merge claude/seed-exit-guard: guardSeedExit() — a seed that ends early exits 1, never a silent 0
guardSeedExit() (@intecion/ipal-kit/seed, opt-in): a beforeExit guard exits 1 with
the reason when a seed run ends before Payload initializes or before summary();
createSeeder and summary() mark the stages. Wired into the reference seed and the
ipal-site / ipal-form seed templates. Normal exit codes are unchanged.
2026-10-29 19:23:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 f789e36636 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]>
2026-10-29 19:19:14 +01:00
26 changed files with 330 additions and 22 deletions
+27
View File
@@ -8,6 +8,33 @@ 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 version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20. once there are more than 20.
## 1.15.1
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.
### Changed
- Reference site (not shipped): the Playwright smoke tests start their own server and fail when the port is taken
(`reuseExistingServer` only with `E2E_REUSE_SERVER=1`), so another project's dev server is never tested by mistake.
### What projects must update
- Nothing is required.
- Recommended: add `guardSeedExit()` (imported from `@intecion/ipal-kit/seed`) as the first statement of every seed
script, before `getPayload()`; without it nothing changes. A guarded script must end with `seed.summary()` (the seed
templates do), otherwise it exits 1 as "ended before the seed finished".
- **Check in Coolify:** after a seed in the app's Terminal, `echo $?` must print `0`; `1` with a `[seed] ended …` line
means the run stopped early and nothing after that point was written — run it again.
- `pnpm ipal:skills` for the updated `ipal-site` / `ipal-form` seed templates and `ipal-reference`.
## 1.15.0 ## 1.15.0
A new site in one command (`ipal-kit create`), built from a complete reference site; `ipal-doctor`, which checks any site 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 **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: `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. - 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. - 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 }`. - Every locale written separately with `fallbackLocale: false`; `context: { disableRevalidate: true, ipalSkipIndexNow: true }`.
+7 -3
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). --> <!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.15.0 ("Example Studio", made up) that uses The reference site is one complete client site on ipal-kit 1.15.1 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version: 40 lines are below in full; open the rest in the repo at the tag of your plugin version:
@@ -92,7 +92,11 @@ try {
// no .env (CI) // no .env (CI)
} }
/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */ /**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100' const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100'
export default defineConfig({ export default defineConfig({
@@ -105,7 +109,7 @@ export default defineConfig({
webServer: { webServer: {
command: 'pnpm start', command: 'pnpm start',
env: { PORT: new URL(baseURL).port || '3000' }, env: { PORT: new URL(baseURL).port || '3000' },
reuseExistingServer: true, reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
url: `${baseURL}/api/health`, url: `${baseURL}/api/health`,
}, },
workers: 1, workers: 1,
@@ -25,7 +25,7 @@
* `email` field (no extra recipients, no header injection). * `email` field (no extra recipients, no header injection).
*/ */
import config from '@payload-config' import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed' import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload' import { getPayload } from 'payload'
// ─── fill from the brief ──────────────────────────────────────────────────── // ─── 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 }) const payload = await getPayload({ config })
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file. // 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: // 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. **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 | | 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 }`. | | `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). | | `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`. | | `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`). | | `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. | | `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). | | `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. | | `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`). | | `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` ## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
@@ -32,7 +32,7 @@
*/ */
import config from '@payload-config' import config from '@payload-config'
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks' 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 { pageTemplates } from '@intecion/ipal-kit/templates'
import { getPayload } from 'payload' import { getPayload } from 'payload'
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
const ONLY: string[] | undefined = undefined const ONLY: string[] | undefined = undefined
// ----------------------------------------------------------------- /CONTENT -- // ----------------------------------------------------------------- /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: // Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file:
// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } }) // createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } })
const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION }) const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION })
+7
View File
@@ -217,6 +217,13 @@ and the browser tab shows the same separator.
**Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without **Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without
`SEED_ONLY` stops with "full seed refused". `SEED_ONLY` stops with "full seed refused".
**→ 1.15.1 (PROGRAMISTA §6, item 56; seed exit guard; seeding.md) — nothing required, recommended:**
1. Every seed script: `import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'` and `guardSeedExit()` as
the first statement, before `getPayload()`; the script ends with `seed.summary()` (the `ipal-site` / `ipal-form`
templates show it). `pnpm ipal:skills` for the updated templates.
2. **Check:** run the seed with `SEED_DRY_RUN=1` locally → exit 0; in Coolify's Terminal after a seed, `echo $?` → `0`
(a `1` with `[seed] ended …` means the run stopped early — run it again).
## 2. Inventory (no code changes) ## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff — **What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files): `git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+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; 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); 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). The seed script and its dependencies must be in the image (they are when Coolify builds from the whole repo).
+1
View File
@@ -663,6 +663,7 @@ Do one item at a time, build, check. Order by importance:
| 53 | **1.14.4** — cookie texts retyped in every language; three cookie entries in the admin navigation | `pnpm payload generate:importmap` (`CookieReviewTab`, `CookieSiteCheckTab`); empty languages fill themselves (`fillEmptyLocales: false` to keep them empty); with `cookieScanner` one **Cookies** entry with tabs (`cookieScanner: { adminLayout: 'separate' }` for the old entries); Cookie banner is now called Cookies — update editor instructions; no migration | consent.md, cookie-scanner.md, hooks.md, CHANGELOG 1.14.4 | | 53 | **1.14.4** — cookie texts retyped in every language; three cookie entries in the admin navigation | `pnpm payload generate:importmap` (`CookieReviewTab`, `CookieSiteCheckTab`); empty languages fill themselves (`fillEmptyLocales: false` to keep them empty); with `cookieScanner` one **Cookies** entry with tabs (`cookieScanner: { adminLayout: 'separate' }` for the old entries); Cookie banner is now called Cookies — update editor instructions; no migration | consent.md, cookie-scanner.md, hooks.md, CHANGELOG 1.14.4 |
| 54 | **1.14.6** (1.14.5 never published) — `/api/graphql` answers 500; graphql-scalars high advisory; theme stored as `ipal-theme`; hand-written `admin.meta` for the panel preview | Postgres: `migrate:create` for the title separator **plus `${sql.raw(titleSeparatorSql())}` after the first `SET DATA TYPE text;`**, and the cookie storage type; `graphql-scalars` override (Node 22 recommended); `THEME_STORAGE_KEY` instead of `'ipal-theme'`; `titleSeparatorChar()` for a raw `settings.titleSeparator`; remove hand-written panel `admin.meta`; `pnpm ipal:skills` (`--external` optional) | CHANGELOG 1.14.6 + 1.14.5, seo.md, theme.md, white-label.md, consent.md | | 54 | **1.14.6** (1.14.5 never published) — `/api/graphql` answers 500; graphql-scalars high advisory; theme stored as `ipal-theme`; hand-written `admin.meta` for the panel preview | Postgres: `migrate:create` for the title separator **plus `${sql.raw(titleSeparatorSql())}` after the first `SET DATA TYPE text;`**, and the cookie storage type; `graphql-scalars` override (Node 22 recommended); `THEME_STORAGE_KEY` instead of `'ipal-theme'`; `titleSeparatorChar()` for a raw `settings.titleSeparator`; remove hand-written panel `admin.meta`; `pnpm ipal:skills` (`--external` optional) | CHANGELOG 1.14.6 + 1.14.5, seo.md, theme.md, white-label.md, consent.md |
| 55 | **1.15.0** — a production seed runs everything; no design tokens / block library; no site check | `SEED_ONLY` for production seeds (full seed refused, `IPAL_SEED_ALLOW_FULL=1` with the owner's OK); optional tokens.css + the block library (block by block, `migrate:create`); CookieButton above the footer (`avoid={false}`); `pnpm ipal:skills`; `pnpm exec ipal-doctor` (`--url`); new sites with `ipal-kit create` | CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md | | 55 | **1.15.0** — a production seed runs everything; no design tokens / block library; no site check | `SEED_ONLY` for production seeds (full seed refused, `IPAL_SEED_ALLOW_FULL=1` with the owner's OK); optional tokens.css + the block library (block by block, `migrate:create`); CookieButton above the footer (`avoid={false}`); `pnpm ipal:skills`; `pnpm exec ipal-doctor` (`--url`); new sites with `ipal-kit create` | CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md |
| 56 | **1.15.1** — a seed in Coolify's Terminal ends with exit 0 and no output (it stopped before Payload started) | `guardSeedExit()` first in every seed script, `seed.summary()` at the end; check `echo $?` after a seed; `pnpm ipal:skills` | CHANGELOG 1.15.1, seeding.md |
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`. `node_modules/@intecion/ipal-kit/dist`.
+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. — the plan must name only the records the owner asked for.
3. Back up the database (**Backup now**). 3. Back up the database (**Backup now**).
4. The real run, without `SEED_DRY_RUN`. 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`, …) 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 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 ```ts
// scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
import config from '@payload-config' import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed' import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload' 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 })) const seed = createSeeder(await getPayload({ config }))
await seed.upsertBySlug('pages', [ await seed.upsertBySlug('pages', [
{ title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] }, { 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 with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production
guard refuses the run. 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 On a collection with drafts the helper reads the latest draft, both to match records and to tell
whether an editor changed them. whether an editor changed them.
@@ -218,13 +241,14 @@ whether an editor changed them.
| Export | Use | | 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) | | `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 | | `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 | | `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 | | `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 | | `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`. `UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`.
## Turn off, override, extend ## Turn off, override, extend
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@intecion/ipal-kit", "name": "@intecion/ipal-kit",
"version": "1.15.0", "version": "1.15.1",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.", "description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
@@ -25,7 +25,7 @@
* `email` field (no extra recipients, no header injection). * `email` field (no extra recipients, no header injection).
*/ */
import config from '@payload-config' import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed' import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload' import { getPayload } from 'payload'
// ─── fill from the brief ──────────────────────────────────────────────────── // ─── 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 }) const payload = await getPayload({ config })
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file. // 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: // A form seed touches exactly one record — this form (matched by its title). After launch that stays true:
@@ -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. **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 | | 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 }`. | | `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). | | `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`. | | `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`). | | `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. | | `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). | | `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. | | `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`). | | `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` ## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
@@ -32,7 +32,7 @@
*/ */
import config from '@payload-config' import config from '@payload-config'
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks' 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 { pageTemplates } from '@intecion/ipal-kit/templates'
import { getPayload } from 'payload' import { getPayload } from 'payload'
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
const ONLY: string[] | undefined = undefined const ONLY: string[] | undefined = undefined
// ----------------------------------------------------------------- /CONTENT -- // ----------------------------------------------------------------- /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: // Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file:
// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } }) // createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } })
const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION }) const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION })
@@ -217,6 +217,13 @@ and the browser tab shows the same separator.
**Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without **Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without
`SEED_ONLY` stops with "full seed refused". `SEED_ONLY` stops with "full seed refused".
**→ 1.15.1 (PROGRAMISTA §6, item 56; seed exit guard; seeding.md) — nothing required, recommended:**
1. Every seed script: `import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'` and `guardSeedExit()` as
the first statement, before `getPayload()`; the script ends with `seed.summary()` (the `ipal-site` / `ipal-form`
templates show it). `pnpm ipal:skills` for the updated templates.
2. **Check:** run the seed with `SEED_DRY_RUN=1` locally → exit 0; in Coolify's Terminal after a seed, `echo $?` → `0`
(a `1` with `[seed] ended …` means the run stopped early — run it again).
## 2. Inventory (no code changes) ## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff — **What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files): `git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions --> <!-- /starter:decisions -->
<!-- ipal-kit:start --> <!-- ipal-kit:start -->
## ipal-kit 1.15.0 — agent guide ## ipal-kit 1.15.1 — agent guide
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. --> <!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code: This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
+3 -2
View File
@@ -17,8 +17,9 @@ cp .env.example .env # then fill PAYLOAD_SECRET; DATABASE
pnpm seed # demo + base content, every language pnpm seed # demo + base content, every language
pnpm dev # http://localhost:3000/pl pnpm dev # http://localhost:3000/pl
``` ```
Production check: `pnpm build && ALLOW_LOCAL_MEDIA=1 PORT=3100 pnpm start`, then Production check: `pnpm build && pnpm payload run e2e/create-test-admin.ts && ALLOW_LOCAL_MEDIA=1 pnpm test:e2e`
`pnpm payload run e2e/create-test-admin.ts && pnpm test:e2e`. (Playwright starts the built site on port 3100 itself; another port: `E2E_BASE_URL=http://localhost:3200`, built with
the same `NEXT_PUBLIC_SERVER_URL`; a server you started yourself: `E2E_REUSE_SERVER=1`).
## What is where ## What is where
| Convention | Files | | Convention | Files |
+6 -2
View File
@@ -7,7 +7,11 @@ try {
// no .env (CI) // no .env (CI)
} }
/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */ /**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100' const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100'
export default defineConfig({ export default defineConfig({
@@ -20,7 +24,7 @@ export default defineConfig({
webServer: { webServer: {
command: 'pnpm start', command: 'pnpm start',
env: { PORT: new URL(baseURL).port || '3000' }, env: { PORT: new URL(baseURL).port || '3000' },
reuseExistingServer: true, reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
url: `${baseURL}/api/health`, url: `${baseURL}/api/health`,
}, },
workers: 1, workers: 1,
+3 -1
View File
@@ -13,7 +13,7 @@
* only with the owner's explicit OK). Pages are create-only; an edited record is skipped. * only with the owner's explicit OK). Pages are create-only; an edited record is skipped.
*/ */
import config from '@payload-config' import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed' import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload' import { getPayload } from 'payload'
import { seedBaseGlobals, seedBaseNavigation, seedBasePages, seedBaseTexts } from './base' import { seedBaseGlobals, seedBaseNavigation, seedBasePages, seedBaseTexts } from './base'
@@ -33,6 +33,8 @@ const withBase = layer === 'all' || layer === 'base'
//: const withBase = true // a new site has only the base layer (the reference site's demo is not copied) //: const withBase = true // a new site has only the base layer (the reference site's demo is not copied)
// @starter:endif // @starter:endif
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (seeding.md).
guardSeedExit()
const payload = await getPayload({ config }) const payload = await getPayload({ config })
const seed = createSeeder(payload) const seed = createSeeder(payload)
+7 -1
View File
@@ -6,8 +6,9 @@
* // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts * // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
* import config from '@payload-config' * import config from '@payload-config'
* import { getPayload } from 'payload' * import { getPayload } from 'payload'
* import { createSeeder } from '@intecion/ipal-kit/seed' * import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
* *
* guardSeedExit() // first: an early exit (no Payload, unfinished run) becomes exit 1, not a silent 0
* const seed = createSeeder(await getPayload({ config })) * const seed = createSeeder(await getPayload({ config }))
* await seed.upsertBySlug('pages', [{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }]) * await seed.upsertBySlug('pages', [{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }])
* await seed.fillGlobal('header', { links: [] }) * await seed.fillGlobal('header', { links: [] })
@@ -18,8 +19,10 @@
* package throws in plain Node, and `payload run` is plain Node. * package throws in plain Node, and `payload run` is plain Node.
*/ */
export { export {
activeSeedExitGuard,
createSeeder, createSeeder,
editedSinceSeed, editedSinceSeed,
guardSeedExit,
isLocalDatabase, isLocalDatabase,
projectOnto, projectOnto,
seedHash, seedHash,
@@ -29,6 +32,9 @@ export type {
EditedSinceSeedArgs, EditedSinceSeedArgs,
Seeder, Seeder,
SeederOptions, SeederOptions,
SeedExitGuard,
SeedExitGuardOptions,
SeedExitProcess,
SeedResult, SeedResult,
SeedStatus, SeedStatus,
SeedSummary, SeedSummary,
+87
View File
@@ -0,0 +1,87 @@
/**
* A seed run that ends early must fail loudly. `payload run` starts the CLI with `void start()` and then
* `await import(script)`: when a seed 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 run. The guard turns it into exit 1 with the reason.
*
* Dependency-free on purpose: no Payload, no Node imports — safe to import first in any seed script.
*/
type ExitListener = () => void
/** The bits of `process` the guard uses — injectable for tests. */
export type SeedExitProcess = {
exit: (code: number) => void
exitCode?: null | number | string
off: (event: 'beforeExit', listener: ExitListener) => unknown
on: (event: 'beforeExit', listener: ExitListener) => unknown
}
export type SeedExitGuardOptions = {
/** Prefix of the message. Default '[seed]'. */
label?: string
/** Where the message goes. Default stderr. */
log?: (line: string) => void
/** Default the real `process`. */
process?: SeedExitProcess
}
export type SeedExitGuard = {
/** Stops watching (the run decides its exit code itself). */
dispose: () => void
/** The seed ended: `summary()` calls it. */
finished: () => void
/** Payload is up: `createSeeder` calls it. */
initialized: () => void
readonly state: 'finished' | 'initialized' | 'waiting'
}
let active: null | SeedExitGuard = null
/** The guard of the current run, if the script started one (`createSeeder` and `summary()` report to it). */
export function activeSeedExitGuard(): null | SeedExitGuard {
return active
}
/**
* Call it first in a seed script, before `getPayload()`. Until `summary()` runs, an exit through an empty
* event loop prints "[seed] ended before Payload initialized" (or "… before the seed finished") and exits 1.
* A normal `process.exit(code)` — after the summary, on an error, or the guard's own refusal — is untouched.
*/
export function guardSeedExit(options: SeedExitGuardOptions = {}): SeedExitGuard {
const proc: SeedExitProcess = options.process ?? process
const label = options.label ?? '[seed]'
const log = options.log ?? ((line: string) => {process.stderr.write(`${line}\n`)})
let state: SeedExitGuard['state'] = 'waiting'
const onBeforeExit = () => {
if (state === 'finished') {return}
const when = state === 'waiting' ? 'before Payload initialized' : 'before the seed finished'
log(
`${label} ended ${when} — the run stopped early and nothing after that point was written. ` +
'Exit code 1. Run it again; if it repeats, check the database connection and the seed script.',
)
proc.exitCode = 1
proc.exit(1)
}
const guard: SeedExitGuard = {
dispose: () => {
proc.off('beforeExit', onBeforeExit)
if (active === guard) {active = null}
},
finished: () => {
state = 'finished'
},
initialized: () => {
if (state === 'waiting') {state = 'initialized'}
},
get state() {
return state
},
}
active?.dispose()
proc.on('beforeExit', onBeforeExit)
active = guard
return guard
}
+2
View File
@@ -1,3 +1,5 @@
export { activeSeedExitGuard, guardSeedExit } from './exitGuard.js'
export type { SeedExitGuard, SeedExitGuardOptions, SeedExitProcess } from './exitGuard.js'
export { isLocalDatabase } from './guard.js' export { isLocalDatabase } from './guard.js'
export { createSeeder } from './seeder.js' export { createSeeder } from './seeder.js'
export type { Seeder, SeederOptions, SeedResult, SeedStatus, SeedSummary, UpsertOptions } from './seeder.js' export type { Seeder, SeederOptions, SeedResult, SeedStatus, SeedSummary, UpsertOptions } from './seeder.js'
+4
View File
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
import type { SeedTarget } from './values.js' import type { SeedTarget } from './values.js'
import { activeSeedExitGuard } from './exitGuard.js'
import { isLocalDatabase, seedDatabaseUrl } from './guard.js' import { isLocalDatabase, seedDatabaseUrl } from './guard.js'
import { import {
defaultHashField, defaultHashField,
@@ -178,6 +179,8 @@ const hasRef = (v: unknown): boolean =>
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef)) : !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder { 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 env = process.env
const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1') const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1')
const update = options.update ?? env.SEED_UPDATE === '1' const update = options.update ?? env.SEED_UPDATE === '1'
@@ -459,6 +462,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
} }
const summary = (): SeedSummary => { const summary = (): SeedSummary => {
activeSeedExitGuard()?.finished()
const result: SeedSummary = { const result: SeedSummary = {
created: counts.create, created: counts.create,
errors: counts.error, errors: counts.error,
+115
View File
@@ -0,0 +1,115 @@
import { spawnSync } from 'node:child_process'
import { EventEmitter } from 'node:events'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
import { activeSeedExitGuard, createSeeder, guardSeedExit, type SeedExitProcess } from '../src/exports/seed.js'
const guardFile = pathToFileURL(path.resolve(import.meta.dirname, '../src/modules/seed/exitGuard.ts')).href
/** A `process` stand-in: `beforeExit` is emitted by the test, `exit` is recorded. */
function fakeProcess() {
const emitter = new EventEmitter()
const exits: number[] = []
const proc: { exitCode?: null | number | string } & SeedExitProcess = {
exit: (code) => {exits.push(code)},
off: (event, listener) => emitter.off(event, listener),
on: (event, listener) => emitter.on(event, listener),
}
return { emit: () => emitter.emit('beforeExit'), exits, listeners: () => emitter.listenerCount('beforeExit'), proc }
}
afterEach(() => activeSeedExitGuard()?.dispose())
describe('guardSeedExit', () => {
it('fails a run that ends before Payload initialized', () => {
const fake = fakeProcess()
const lines: string[] = []
guardSeedExit({ log: (l) => lines.push(l), process: fake.proc })
fake.emit()
expect(fake.exits).toEqual([1])
expect(fake.proc.exitCode).toBe(1)
expect(lines[0]).toMatch(/^\[seed\] ended before Payload initialized/)
})
it('fails a run that ends after createSeeder but before summary()', () => {
const fake = fakeProcess()
const lines: string[] = []
const guard = guardSeedExit({ label: '[seed-form]', log: (l) => lines.push(l), process: fake.proc })
createSeeder({ config: { localization: false } } as never, { guard: false, log: () => {} })
expect(guard.state).toBe('initialized')
fake.emit()
expect(fake.exits).toEqual([1])
expect(lines[0]).toMatch(/^\[seed-form\] ended before the seed finished/)
})
it('leaves a finished run alone (summary() ends it), and dispose() removes the listener', () => {
const fake = fakeProcess()
const guard = guardSeedExit({ log: () => {}, process: fake.proc })
const seed = createSeeder({ config: { localization: false } } as never, { guard: false, log: () => {} })
seed.summary()
expect(guard.state).toBe('finished')
fake.emit()
expect(fake.exits).toEqual([])
guard.dispose()
expect(fake.listeners()).toBe(0)
expect(activeSeedExitGuard()).toBeNull()
})
it('a second guard replaces the first (one listener)', () => {
const fake = fakeProcess()
guardSeedExit({ log: () => {}, process: fake.proc })
const second = guardSeedExit({ log: () => {}, process: fake.proc })
expect(fake.listeners()).toBe(1)
expect(activeSeedExitGuard()).toBe(second)
})
})
/**
* The real thing in a child process, started the way `payload run` starts a script: `void start()` and
* `await import(script)`. Exit codes and messages must match what an operator sees in Coolify's Terminal.
*/
describe('guardSeedExit in a real process', () => {
const run = (body: string) => {
const script = `import { guardSeedExit } from '${guardFile}'
const start = async () => {
try {
${body}
} catch (error) {
console.error('Error running script:', error.message)
process.exit(1)
}
}
void start()`
return spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20_000 })
}
it('an await that never settles: exit 1 with the reason, not a silent 0', () => {
const r = run(`guardSeedExit()\n await new Promise(() => {}) // getPayload() left with nothing keeping the loop alive`)
expect(r.status).toBe(1)
expect(r.stderr).toMatch(/\[seed\] ended before Payload initialized/)
})
it('without the guard the same script exits 0 silently (the failure the guard exists for)', () => {
const r = run(`await new Promise(() => {})`)
expect(r.status).toBe(0)
expect(`${r.stdout}${r.stderr}`).toBe('')
})
it('a finished run exits with its own code; an error and a refusal keep exit 1 and their message', () => {
expect(run(`const g = guardSeedExit()\n g.initialized(); g.finished()\n console.log('summary')\n process.exit(0)`)).toMatchObject({ status: 0, stdout: 'summary\n' })
const failed = run(`const g = guardSeedExit()\n g.initialized(); g.finished()\n process.exit(1)`)
expect(failed.status).toBe(1)
expect(failed.stderr).not.toMatch(/ended before/)
const refused = run(`guardSeedExit()\n throw new Error('[seed] full seed refused: NODE_ENV=production and no record list.')`)
expect(refused.status).toBe(1)
expect(refused.stderr).toMatch(/full seed refused/)
expect(refused.stderr).not.toMatch(/ended before/)
})
it('a dry run that ends naturally after summary() exits 0', () => {
const r = run(`const g = guardSeedExit()\n g.initialized(); g.finished()`)
expect(r.status).toBe(0)
})
})