# PROGRAMISTA.md — install, new project, deployment, ipal-kit development
> **Who it is for:** a human — a developer at the agency. Rules for writing code (for AI and
> for humans) are in [AGENT.md](../agent/AGENT.md); module APIs are in the module files (map in
> AGENT.md §12). This file is the process: how to set up, deploy and update a project, and
> how to release a new plugin version.
>
> Building a project with an AI agent? Ready-made prompts, step by step: [vibe.md](./vibe.md).
## 0. MAIN RULE — the plugin helps, never limits
ipal-kit is a plugin: it helps projects, it never limits them.
- Every module / feature can be turned off on its own.
- Every default (access rules, fields, hooks, labels, routes, collections, globals) can be
overridden — **the project config wins**.
- Safe defaults, always with an option to relax them.
- We export building blocks (helpers, builders, hooks), not only finished features.
- We never force a dependency, route, UI or data shape where an option or an
exported building block is enough.
Where the code does not meet this yet, the module docs say so plainly ("currently always added").
Contents: 0. Main rule · 1. Install · 2. New project · 3. Environment variables · 4. Deployment
(Coolify) · 5. Compliance · 6. Updating an old project · 7. Troubleshooting ·
8. ipal-kit development and publishing · 9. Git and Gitea
---
## 1. INSTALLING ipal-kit IN A PROJECT
**`.npmrc` in the project root (commit it — it holds no secret):**
```ini
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
This rule applies only to the `@intecion/*` scope — everything else (`react`, `payload`…) still
comes from npm. The registry is public for reading, so install needs no token.
```bash
pnpm add @intecion/ipal-kit
pnpm add @payloadcms/plugin-seo @payloadcms/plugin-form-builder # peer dependencies
pnpm add @clocklimited/payload-2fa@3.0.0-beta.7 # 2FA (optional peer, but required unless twoFactor: false)
pnpm add @payloadcms/storage-s3 # optional peer — only when media live in R2
pnpm add tailwindcss @tailwindcss/postcss
pnpm exec ipal-skills # agent skills + pointer to the guide in AGENTS.md / CLAUDE.md (§2.1a)
```
`nodemailer`, `lucide-react` (`^0.400.0` = only `0.400.x`), `slugify`, `server-only` are regular
`dependencies` of the plugin — they install with it, do not add them. The other peers (`payload`,
`@payloadcms/next`, `@payloadcms/ui`, `@payloadcms/richtext-lexical`, `next`, `react`) come from
`create-payload-app`. If the project uses `lucide-react` itself, keep it at `~0.400.0` (another version = two copies).
**Never from git** (`git+https://…`) — a path with a hash breaks the React Client Manifest
(the plugin's `'use client'` components fail at runtime).
**`@payloadcms/*` versions must match `payload` exactly** — otherwise you get an empty SEO
tab, a missing Forms collection or a crash. In `package.json`:
```json
"pnpm": {
"overrides": {
"payload": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/storage-s3": "3.90.2"
}
}
```
(match the database adapter: `db-postgres` / `db-mongodb`). Then
`rm -rf node_modules pnpm-lock.yaml && pnpm install`.
**Build with webpack** (Turbopack conflicts with `withPayload`):
```json
"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"
```
Check that the registry responds:
```bash
curl -s -o /dev/null -w "%{http_code}\n" \
https://git.intecion.net/api/packages/IntecionSoftware/npm/@intecion%2Fipal-kit # 200
```
**Updating to the latest version:** `pnpm up --latest @intecion/ipal-kit`. Plain
`pnpm up @intecion/ipal-kit` changes nothing when `package.json` has an exact version
(`"1.8.13"`) — it stays within the range. Then follow the "Requires project changes" sections of the CHANGELOG.
**401 when fetching the package** (`ERR_PNPM_FETCH_401 … Unauthorized`) even though the registry
is public: `~/.npmrc` has an old `_authToken` for `git.intecion.net`, and an invalid token
also blocks reading. Remove that line (the token is needed only for publishing, §8.3) or run
once: `NPM_CONFIG_USERCONFIG=/dev/null pnpm up --latest @intecion/ipal-kit`.
---
## 2. NEW PROJECT — ORDER
Pnpm, Node 22+, Next 16, Payload 3. The order matters.
### 2.1 Skeleton
```bash
npx create-payload-app@latest my-project # Blank; Postgres or Mongo
cd my-project
```
Delete the starter `(frontend)/layout.tsx` and `(frontend)/page.tsx` — the root becomes the
layout under `[locale]` (because `` must know the language).
### 2.1a Skills and AGENTS.md
```json
// project package.json
"scripts": {
"ipal:skills": "ipal-skills"
}
```
Run `pnpm ipal:skills` after install and after every ipal-kit update; commit `.agents/skills/`.
(`ipal-skills` is the package `bin` — without the script: `pnpm exec ipal-skills`; options
`--dest
`, `--dry-run`, `--no-pointer`.)
The command also adds to `AGENTS.md` a `…` block
with a pointer to AGENT.md and the `ipal-reference` / `ipal-setup` skills, and creates a missing
`CLAUDE.md` with the line `@AGENTS.md`. On later runs it replaces only the text between the
markers. This way an agent that opens the project lands on the full guide right away —
without a `postinstall` script (the package has none and never will).
**Project `tsconfig.json`: `"exclude": ["node_modules", ".agents"]`** — the skills contain
`.ts`/`.tsx` templates; without the exclusion `tsc` and `next build` check them as project code and fail
(`ipal-skills` and `ipal-audit` warn about it). In the root, `AGENTS.md` follows the template from [AGENT.md §13](../agent/AGENT.md).
List of skills: AGENT.md §14.
### 2.2 Locale — one source
```ts
// src/i18n.config.ts
import type { I18nConfig } from '@intecion/ipal-kit'
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const satisfies I18nConfig
```
Single-language site: one locale, no `[locale]` folder — layout with `i18nConfig.defaultLocale`,
`createPageRoute` / `createNotFoundPage` unchanged, Markdown in `app/md/[[...slug]]/route.ts` (i18n.md).
Do not add `[locale]` "just in case" with one language — links would be without `/pl`, pages with `/pl`.
### 2.3 payload.config.ts
```ts
import { buildConfig } from 'payload'
import { buildR2Storage, ipalKit, mailAdapter } from '@intecion/ipal-kit'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { s3Storage } from '@payloadcms/storage-s3'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
import { Pages } from '@/collections/Pages'
import { Media } from '@/collections/Media'
export default buildConfig({
collections: [Pages, Media], // ipalKit adds users (your own only for extra fields)
email: mailAdapter(), // without it form-builder emails are not sent
plugins: [
ipalKit({
i18n: i18nConfig,
access: { authCollection: 'users' },
pages: { slug: 'pages' }, // System pages (homepage, 404, policies)
content: contentConfig, // collections with an archive (blog…), optional
seo: { collections: ['pages'] },
forms: { redirectRelationships: ['pages'] },
twoFactor: { issuer: 'Nazwa Klienta', plugin: payloadTotp },
whiteLabel: true, // logo/name from Site settings in the admin panel
indexNow: true, // publish → Bing / ChatGPT Search (production)
consentLog: true, // proof of consent (GDPR Art. 7(1)), no personal data
// adminRoute: '/its', // + move app/(payload)/admin → its and put `its` in the proxy matcher (§2.6)
}),
buildR2Storage(['media'], { s3Storage }), // ALWAYS — R2 when all R2_* are in env, local disk without them
],
})
```
The mandatory feature set (SEO, GEO, R2, Turnstile, forms…) and how to check it:
**AGENT.md §0b**. Code for all routes below (§2.7–2.9).
### 2.4 Collections, blocks, shared fields
- `Pages`: `title` (localized), `buildSlugField({ from: 'title' })`,
`buildNoindexField()`, `buildSummaryField()` (summary for AI — GEO), `layout`
of type `blocks` (min. 1 block), `trackSlugHistoryHook`, `buildRevalidateHook`.
- `Media`: upload with `mimeTypes` (images + PDF), `alt` (required, localized),
`normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField` (oversized files, with consent),
`buildMediaPlaceholderHook` + `buildMediaPlaceholderField` (blur/color for `mediaImageProps`) — media.md;
R2 through `buildR2Storage(['media'], { s3Storage })` — `s3Storage` from `@payloadcms/storage-s3`, injected (storage.md).
- Fields from the plugin: links (`buildLinkField`, `buildLinksField` — links.md), section header and
settings (`buildSectionHeaderField`, `buildSectionSettingsField` — blocks.md). The project holds only
the visual UI primitives in `src/components/ui/` (CMSLink on `resolveLink`, Button, Media, Section,
SectionHeader) and `src/components/forms/formClasses.ts` — ready code in
`agent/skills/ipal-block/resources/section-code.md` and `ipal-form/resources/`, rules in AGENT.md §6.
Create them **before** the first block.
### 2.5 Tailwind
```js
// postcss.config.mjs
export default { plugins: { '@tailwindcss/postcss': {} } }
```
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@import "@intecion/ipal-kit/fluid.css"; /* optional: fluid typography and spacing scale */
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
@theme inline {
--text-display: var(--ipal-fs-display);
--text-h1: var(--ipal-fs-h1);
--text-h2: var(--ipal-fs-h2);
--text-h3: var(--ipal-fs-h3);
--text-lead: var(--ipal-fs-lg);
--spacing-section: var(--ipal-space-section);
--spacing-gutter: var(--ipal-space-gutter);
--spacing-gap: var(--ipal-space-gap);
}
```
`fluid.css` is only `clamp()` variables (360 → 1280 px, in `rem`) — classes `text-h1`,
`py-section`, `px-gutter`. `fluid-wide.css` — the same variables, scaled up to 1920 px (13″ ≠ 27″);
import one of the two. Both also have height and width variables: `--ipal-hero-min-h`,
`--ipal-fs-display-fit`, `--ipal-space-section-fit`, `--ipal-measure`, `--ipal-container`
(AGENT.md §6.11a). Override numbers from `DESIGN.md` in the project's `:root`
(`--ipal-fs-h1: clamp(…)`); do not write the formulas from scratch.
Without `@source` the plugin's components (cookie banner, Turnstile) have no styles.
Colors of the plugin's components: `--ipal-primary`, `--ipal-radius` (consent.md).
### 2.6 Proxy (NOT middleware.ts)
```ts
// src/proxy.ts
import { NextResponse } from 'next/server'
import { createProxy } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
// markdown: true (GEO) — /md/… passes without a language redirect, and a page
// fetched with `Accept: text/markdown` gets its Markdown version
export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })
// Inline literal — Next analyzes it statically; importing a variable = proxy on /admin → 500
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
```
Sets `x-locale` / `x-pathname`, the language cookie with consent, redirects `/`.
The headers are for dynamic routes (API, route handlers) — in SSG/ISR pages,
layouts and `not-found.tsx` **do not read `headers()`** (AGENT.md §4.6).
### 2.7 Data layer — one source
```ts
// src/lib/content.ts — the ONLY place for configuration: data, routes, links, layout
import { createContentHelpers } from '@intecion/ipal-kit'
import config from '@/payload.config'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
export const {
// data
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getNotFoundPage,
generatePageMetadata, generateStaticParams, getPageJsonLd, resolvePageRedirect, i18n,
// layout, forms, links
getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav, getSystemLinks,
// routes (re-exported in app/)
sitemap, sitemapRoute, robots, manifest, llmsRoute, llmsFullRoute, markdownRoute,
mcpGET, mcpPOST, healthRoute, indexNowKeyRoute,
} = createContentHelpers({
config,
content: contentConfig,
i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
markdownAlternate: true, // GEO: on every page
summaryField: 'aiSummary', // llms.txt and MCP take the AI description from buildSummaryField
mcp: { serverName: '-site' },
// pageJsonLd: { faq: (doc) => …map the FAQ block to { question, answer }… },
// siteJsonLd: async ({ settings, baseUrl, locale }) => [buildLocalBusinessJsonLd({…})], // local business
})
```
Everything is computed only on first use and cached per request. You can skip any
function and build the page from lower-level blocks (`createPageMetadata`,
`createLlmsTxtRoute`, `createMcpRoute`… — seo.md, mcp.md) — the plugin forces nothing.
### 2.8 Routes
```tsx
// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '@/lib/content'
import '../styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
const shell = await getSiteShell(locale) // consent, analytics, Turnstile, site JSON-LD, Site settings
return (
{/* NO — Next manages it itself */}
}>
{/* */}
{children}
{/* */}
)
}
```
`SiteProviders` wires things in the right order: `MediaPreconnect`, `JsonLdGraph` (WebSite + Organization
from Site settings), `ConsentProvider` → `TurnstileProvider` (always — it turns itself off without keys) →
banner, `CookieButton`, `Analytics` (inside consent). It adds no markup. You can change or
turn off every part: `banner={}` / `false`, `cookieButton`,
`analytics={{ defer: true }}` / `false`, `jsonLd={[buildNavigationJsonLd(…)]}`, `cookieMap`,
`preconnect={false}`. A fully custom layout: pass the same data from `shell` to the providers (consent.md).
Pick the consent settings window with the banner's `settings` prop: `'inline'` (default — categories in the bar),
`'modal'` (small window in the center) or `'detailed'` (large window: each category with a switch, a description and
an expandable list of cookies from Cookie banner → Cookie list). Example:
`banner={}` — description: consent.md, the
`settings="detailed"` section.
```tsx
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — DOUBLE brackets
import { notFound, permanentRedirect } from 'next/navigation'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
import { sendForm } from '../actions'
export const revalidate = 3600 // ISR — a literal in the file (Next reads it statically)
const route = createPageRoute(content, {
blocks: blockRegistry,
notFound, permanentRedirect, // injected from next/navigation
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
// render: ({ route, blocks }) => route.type === 'archive' ? : undefined,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // SSG → synchronous
```
`createPageRoute`: route (`resolveRoute`), old slug → 308 (`resolvePageRedirect`), 404, metadata,
`generateStaticParams`, page JSON-LD (`getPageJsonLd`, turn off: `jsonLd: false`) and blocks with
`locale` + `blockProps`. No `searchParams` — an archive with pagination (`?page=`) is a separate route or
deliberately dynamic (pages.md). Custom page: the same helpers by hand (pages.md).
```tsx
// src/app/(frontend)/[locale]/notFoundView.ts — 404 content from the admin panel in one language (server action, since 1.12.0)
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export async function loadNotFoundView(locale: string) {
return renderNotFoundView(content, { blocks: blockRegistry }, locale)
}
// src/app/(frontend)/[locale]/not-found.tsx — 404 in the URL's language, no headers(); content loads only on a 404,
// not in the RSC data of every page (pages.md → why it is lazy)
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
```
```ts
// SEO / GEO / ops routes — each one is a re-export, the configuration lives in lib/content.ts
// src/app/sitemap.xml/route.ts — XML for Google, human-readable styling from the plugin (nothing in /public)
export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/robots.ts — robots from code + the AI crawler policy from Site settings → Search engines
export { getRobots as default } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/manifest.ts
export { manifest as default } from '@/lib/content'
export const dynamic = 'force-dynamic'
// ---- GEO: all of the below are mandatory (AGENT.md §0b.5–8) ----
// src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: llmsFullRoute)
export { llmsRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/md/[locale]/[[...slug]]/route.ts — every page as Markdown (noindex + canonical to the HTML)
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/indexnow-key.txt/route.ts — IndexNow key (from Site integrations or INDEXNOW_KEY)
export { indexNowKeyRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/api/mcp/route.ts — public MCP server (AI browses the site)
export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/api/health/route.ts
export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
```
One sitemap: `sitemap.xml/route.ts` **or** `sitemap.ts` — never both. The sitemap
heading = "XML Sitemap", below it "Technology by Intecion.com"; change it
with `createContentHelpers({ sitemapStyle })` (seo.md).
### 2.9 next.config.ts and instrumentation.ts
```ts
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import { buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders } from '@intecion/ipal-kit'
const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production' })
export default withPayload({
images: { ...buildImagesConfig() }, // AVIF/WebP, R2 domain (R2_PUBLIC_URL), 31-day cache
htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
async headers() {
return [{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]
},
})
```
CSP (`buildCsp`) — first `report-only`, then `enforce` after checking the console
(security.md). `src/instrumentation.ts`: `assertEnv(ipalEnvRules({...}))` from **`@intecion/ipal-kit/env`**, only when `NEXT_RUNTIME === 'nodejs'` (env.md).
### 2.10 Generate and start
```bash
pnpm generate:types
pnpm payload generate:importmap # after every change to admin components
pnpm dev
```
### 2.11 Configuration in the admin panel (`/admin`)
1. First user (admin) + 2FA setup.
2. **Site settings → General** — site name, logo, favicon (PNG).
3. **Pages** — the homepage with a title **in every language** (empty EN slug = 404 on `/en`).
4. **Site settings → System pages** — Homepage (without it `/pl` → 404), 404,
policies; archives of content collections.
5. **Cookie banner** — banner texts per language; **Cookies** (list from the scan, `ipal-consent-check`) and **Detail
labels** (captions of the list in the `settings="detailed"` window) — also in every language.
6. **Notifications** — form messages per language.
7. **Site integrations** — SMTP/Graph (From Name, From Address), Turnstile, analytics/pixel
IDs, IndexNow (integrations.md). Mail / Turnstile problems show as an alert on the
dashboard and a banner on the tab.
`/` → redirect to `/pl`. Turnstile test keys: site
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`.
---
## 3. ENVIRONMENT VARIABLES
| Variable | Required | Description |
|---|---|---|
| `DATABASE_URI` | ✅ | Postgres / Mongo (dev can use SQLite) |
| `PAYLOAD_SECRET` | ✅ | random, ≥32 characters, different in production |
| `NEXT_PUBLIC_SERVER_URL` | ✅ | public URL (canonical, hreflang, OG); without it links are relative |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | ⬜ | email through Microsoft Graph |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | ✅ prod | media in Cloudflare R2 — always in production (missing → container disk, files vanish on redeploy without a volume); in dev they can be empty (storage.md) |
| `R2_PUBLIC_URL` | ⬜ | **empty by default** — media served through the app (`/api/media/file/…`); a media domain whose zone is on Cloudflare only for media-heavy sites (storage.md, deployment.md §6); in dev alone = read-only media |
| `NODE_ENV` | ⬜ | `development` / `production` / `test` — `production` tightens the `ipalEnvRules` rules (R2, `IPAL_IP_HEADER`) |
| `IPAL_NOINDEX` | ⬜ | `1` **only on staging / preview** — the whole site out of Google (robots, meta, header) |
| `INDEXNOW_KEY` | ⬜ | IndexNow key, when not set in the admin panel (Site integrations → IndexNow generates one itself) |
| `IPAL_IP_HEADER` | ✅ prod | header with the real IP for the rate limit: `cf-connecting-ip` behind Cloudflare, `x-forwarded-for` behind plain Traefik/nginx (forms.md) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | fallback when the Turnstile keys are not in the admin panel (`ipalEnvRules({ turnstile: true })` makes them required) |
Full list and validation at startup: env.md, deployment.md.
R2 example:
```bash
R2_BUCKET=klient-media
R2_ENDPOINT=https://.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
R2_PUBLIC_URL= # empty = media through the app (default)
```
Rules: secrets only in `.env` (dev) and the Coolify app's Environment Variables (prod — build time vs runtime:
deployment.md §4.2), never in the repo.
`.env.example` (no values) always in the repo. Content the editor can change →
admin panel, not env. Infrastructure (R2, Graph, database) → env, not the admin panel.
---
## 4. DEPLOYMENT (Coolify)
Every project runs on Coolify on our servers; we also run the DNS zones. Full procedure: deployment.md §4
(Coolify) and §6 (DNS).
### 4.1 Before deploying
- [ ] `pnpm build` passes locally (not only dev)
- [ ] env in the Coolify app: `NEXT_PUBLIC_*` at build time + runtime, secrets at runtime, `DATABASE_URI` /
`PAYLOAD_SECRET` also at build time when pages are prerendered (§4.3; deployment.md §4.2)
- [ ] `NEXT_PUBLIC_SERVER_URL` = production URL, production `PAYLOAD_SECRET`
- [ ] HSTS on; media in R2 (served through the app, `R2_PUBLIC_URL` empty, Media with public `read`) or a persistent
volume — local media vanish on redeploy
- [ ] Postgres: committed migrations, run on container start (`prodMigrations`); scheduled backups to S3/R2
- [ ] policies + cookie banner (§5)
### 4.2 Order
1. DNS: `A`/`AAAA` apex + `www` → the Coolify server; CAA (if any) allows `letsencrypt.org` (deployment.md §6).
2. Coolify: database resource (Postgres/Mongo) + backups schedule to S3/R2 (deployment.md §4.6).
3. Coolify application from the Git repo: port 3000, domains `https://klient.pl,https://www.klient.pl`, www ↔ apex
redirect matching `NEXT_PUBLIC_SERVER_URL`, env variables, health check `/api/health` (deployment.md §4.1–4.4).
4. Deploy. What runs:
```bash
pnpm install --frozen-lockfile
pnpm generate:types
pnpm build
pnpm start # Postgres: pending migrations run here, before the container is healthy
```
**Migrations are not** Coolify Pre-/Post-deployment commands (pre runs in the old container and is skipped on the
first deploy; post runs after traffic has switched). Use `postgresAdapter({ …, prodMigrations: migrations })` or the
start command `pnpm payload migrate && pnpm start`; keep migrations backward compatible (the old container serves
during the rolling update). Mongo: no migrations. Details: deployment.md §4.3.
### 4.3 Database at build time
- **The build sees the database** → `generateStaticParams` prerenders pages (SSG, `●`),
`` is complete. This is what we want: `DATABASE_URI` marked for build time in Coolify and reachable from the build.
- **The build does not see the database** → the plugin does not break the build (returns `[]`), but pages
render on demand (`ƒ`) and SEO falls back to the metadata-in-body problem.
Make the database reachable from the build (same server/network, deployment.md §3a3).
- `generateStaticParams` from `lib/content` covers **only the pages collection** (max 1000 per language);
content collection entries and pages above the limit render on demand (ISR).
- Routes that read the database (`sitemap`, `manifest`, `llms.txt`, `health`) have
`force-dynamic` — they are not prerendered.
Test without a database: `DATABASE_URI=mongodb://invalid-host:27017/x pnpm build` → exit code 0.
### 4.4 Health check, rollback, backups, seed
- **Health check** — Coolify → Health Checks on `/api/health` (`healthRoute` from `lib/content` = `createHealthRoute`
pinging the pages collection: a database round-trip, 200/503, `no-store`), port 3000, a start period long enough for
migrations. A rolling update keeps the old container when the new one is unhealthy (deployment.md §4.4).
- **Rollback** — Coolify → Rollback → an earlier image (keep a few: image retention). It does not undo migrations →
restore the pre-deploy backup if needed (deployment.md §4.5).
- **Backups** — scheduled to S3/R2, **Backup now** before risky operations, restore via Import Backup; test
restores (deployment.md §4.6).
- **Seed / one-off scripts in production** — Coolify → Terminal in the app container: dry run → Backup now → real
run (deployment.md §4.7, [seeding.md](../seeding.md)).
### 4.5 After deploying
- [ ] `/` redirects to the locale, the admin panel and login (2FA) work
- [ ] the form sends (admin panel → Send test), media display (`/api/media/file/…` → 200 without login)
- [ ] `curl -A "Googlebot" URL | grep canonical` — in ``
- [ ] `/sitemap.xml`, `/robots.txt` respond; favicon in ``
- [ ] security headers (securityheaders.com); `www` redirects to the canonical host
- [ ] DNS records from deployment.md §6 checked with `dig`
### 4.6 Email — SMTP or Graph
Client on M365/Exchange → Graph (SMTP AUTH is often turned off). Own SMTP/Gmail →
SMTP. The switch is in the admin panel (Site integrations → SMTP → Email Transport).
Graph, one-time: App registration in Azure, the `Mail.Send` application permission
+ **Grant admin consent**, the `GRAPH_*` variables. `from.address` always =
`GRAPH_SENDER` (otherwise `ErrorSendAsDenied`); sender name from the admin panel; the
visitor's address goes into `replyTo`. More: email.md.
---
## 5. COMPLIANCE (PL/EU) — CHECKLIST BEFORE HANDOVER
**The boundary:** we deliver the mechanism. The client or their lawyer writes the text of
the policies and terms — we are not a law firm. Put this in the contract.
- [ ] Policy pages created (privacy, cookies, terms if there are services/sales/accounts)
- [ ] Roles assigned in System pages; content filled in (not a placeholder); `noindex` on policies
- [ ] The banner shows on the first visit; "Reject" is as easy as "Accept"
- [ ] Pixels (Meta, LinkedIn, TikTok) and Clarity do **not** load before consent (check Network).
GA4/GTM load right away in Consent Mode v2 with default `denied` (advanced mode:
no cookies, but with pings to Google) — if the client requires zero requests to Google before
consent, this is currently not met (analytics.md)
- [ ] `CookieButton` reopens the settings; cookies disappear after consent is withdrawn
- [ ] Forms have a `consent` checkbox (required, enforced server-side) with a link to the policy
- [ ] Data controller details in the global (policy + footer)
- [ ] Everything in every language
- [ ] Accessibility widget only when required (public bodies, some e-commerce — EAA)
---
## 6. UPDATING AN OLD PROJECT TO THE LATEST ipal-kit
**One rule:** when the plugin provides something the project has written by hand —
**delete the local version**. Two versions = everything runs twice.
Do one item at a time, build, check. Order by importance:
| # | What | Do | Doc |
|---|---|---|---|
| 1 | Metadata in `` | `htmlLimitedBots`, remove `` from the layout, `revalidate`, `generateStaticParams`, remove `await searchParams` | seo.md, pages.md |
| 2 | `middleware.ts` / hand-written proxy | `createProxy` (§2.6) | i18n.md |
| 3 | manifest/sitemap/llms routes | `createManifestHandler`, `sitemap`, `createLlmsTxtRoute` + `force-dynamic`; remove `_status` workarounds | seo.md |
| 4 | `ConsentWrapper` with `setTimeout` | delete — `CookieBanner`/`CookieButton` have their own mount guard | consent.md |
| 5 | Language switcher with 404 | `LanguageSwitcher` / `switchLocalePath` with `getLocalizedSlugs` | i18n.md |
| 6 | Own Lexical parser | `RenderRichText` | richtext.md |
| 7 | Hand-written form logic, `getSafeString` | `useForm`/`useContactForm`, `resolveLocalized`, honeypot | forms.md |
| 8 | Hook with a `['pl','en']` list | `buildCrossLocaleFieldSync` | hooks.md |
| 9 | Hand-written noindex checkbox + hook | `buildNoindexField` | seo.md |
| 10 | Old slugs → 404 | `trackSlugHistoryHook` + `resolveRedirect` in the catch-all | hooks.md, content.md |
| 11 | No env validation | `instrumentation.ts` + `assertEnv` | env.md |
| 12 | Third-party scripts without consent | `ConsentScript` / `Analytics` | consent.md, analytics.md |
| 13 | No health check | `healthRoute` from `lib/content` / `createHealthRoute` (§2.8) | deployment.md |
| 14 | 2FA crash "Cannot find module" | inject `plugin: payloadTotp` | security.md |
| 14a | workarounds from ≤ 1.8.13: a `payloadTotp` adapter cast to `CollectionSlug`, `'@clocklimited/payload-2fa'` in `serverExternalPackages` | delete — `plugin: payloadTotp` directly, no entry in `next.config` | security.md |
| 15 | `ctaLabel`/`pdfUrl` fields, monolithic sections | refactor per AGENT.md §6.7 (with a data migration!) | AGENT.md |
| 15a | `buildR2Storage(['media'])` without an adapter (since 1.8.1 an error when R2 env is set) | `pnpm add @payloadcms/storage-s3`, `buildR2Storage(['media'], { s3Storage })` | storage.md |
| 15b | `src/fields/link.ts`, `src/lib/links.ts` in the project | imports from the plugin, delete the copies (no database migration) | links.md |
| 15c | `createPageMetadata(...)` in `page.tsx` | `generatePageMetadata(locale, slug)` from `lib/content` — cache shared with the page component, fewer queries | seo.md |
| 15d | no limits for oversized images / video in Media | `buildOptimizeUploadHook()` + `buildOptimizeUploadField()`, field migration | media.md |
| 15e | "Add Row" arrays, "Item 01" rows, `cta1`/`cta2`, PL labels in the admin panel | `labels` + `rowLabel()` on arrays, slots → array (with a migration!), EN labels — AGENT.md §6.5a; after updating the plugin **`pnpm payload generate:importmap`** (buildLinksField uses `RowLabel`) | links.md |
| 15f | `public/sitemap.css` + own route / `app/sitemap.ts` | `app/sitemap.xml/route.ts`: `export { sitemapRoute as GET } from '@/lib/content'` + `force-dynamic`; delete `public/sitemap.css` and `app/sitemap.ts` | seo.md |
| 15g | `instrumentation.ts` imports from the root (Edge/Turbopack crash: `fileTypeFromFile`) | `import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'` + `if (process.env.NEXT_RUNTIME !== 'nodejs') return`; remove the dynamic `await import` | env.md |
| 15h | `` in the admin panel = XSS) | seo.md |
| 15i | own `clamp()` formulas in `styles.css` | `@import "@intecion/ipal-kit/fluid.css"` + mapping in `@theme` (§2.5) | — |
| 15j | the form front end sends `fetch('/api/form-submissions')` (from this version REST returns 403 for anonymous users) | rewrite as a server action + `submitForm` (skill `ipal-form`) | forms.md |
| 15k | Turnstile secret saved by code (`updateGlobal` in `onInit` / an action) or own `verify` without `remoteip` | delete the workaround: secret in the admin panel or env `TURNSTILE_SECRET_KEY`; the plugin does not send `remoteip` and logs the rejection reason | turnstile.md |
| 15l | a Turnstile outage blocked forms | nothing in the project: on an error on our side the plugin accepts the submission and shows an alert in the admin panel; `generate:importmap`, Postgres: `migrate:create` | turnstile.md |
| 15m | own plugin moving Notifications into a group; `formOverrides`/`formSubmissionOverrides` only for labels and the admin group | delete — the plugin itself puts Form messages → Settings, and forms → the "Forms" group with labels (`forms.adminGroup`) | forms.md |
| 15n | mail errors visible only in logs | nothing in the project: `mailAdapter()` shows the send error on the dashboard and in Site integrations → SMTP; `generate:importmap`, Postgres: `migrate:create` | email.md |
| 16 | Hard-coded 404 | 404 role in System pages + `getNotFoundPage` | pages.md |
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` in the layout | delete the whole parameter; enter the text in Cookie banner → Privacy link label | consent.md |
| 17 | **AI/GEO (mandatory since 1.9.0)** | llms.txt + llms-full.txt, the `/md/…` route, `markdownAlternate: true`, `prefersMarkdown` in the proxy, `/api/mcp`, `buildSummaryField`, AI bots allowed — AGENT.md §0b | content.md, seo.md, mcp.md |
| 18 | **1.9.0** — `TurnstileProvider siteKey` from `getSiteIntegrations(…).turnstileSiteKey` | `getTurnstileConfig(payload).siteKey`. Note: with both keys set `submitForm` **requires** a token — a form without the widget will be rejected | turnstile.md |
| 19 | **1.9.0** — `twoFactor: { issuer }` without `plugin` | add `plugin: payloadTotp` (the fallback with a dynamic import was removed — startup fails with an error) | security.md |
| 20 | **1.9.0** — IP in the form action computed by hand from `x-forwarded-for` | `clientIp(await headers())` + `IPAL_IP_HEADER` in the production env | forms.md |
| 21 | **1.9.0** — media without R2 in production / no `buildR2Storage` | wire `buildR2Storage(['media'], { s3Storage })`, set `R2_*` | storage.md |
| 22 | **1.9.1** — hand-written `actions.ts` / `md` route / no form seed | `createSubmitAction`, `createMarkdownRoute`, seed from `ipal-form` (mail to the company + to the visitor) | forms.md, content.md |
| 23 | **1.9.1** — `createProxy` without `markdown: true` | add it — otherwise `/md/…` redirects to `/pl/md/…` | content.md |
| 24 | **1.9.1** — page JSON-LD assembled by hand | `getPageJsonLd`, `buildNavigationJsonLd`, `sameAsUrls`, `formatOpeningHours` | seo.md |
| 25 | **1.9.1** — consent: version, log, table | Cookie banner → Policy version; `consentLog: true` + `logEndpoint`; ``; scan + ``; Postgres: `migrate:create` | consent.md |
| 26 | **1.9.1** — media: `priority`, no placeholders, `images` in next.config | `` through `mediaImageProps`/`videoProps`, `buildMediaPlaceholderHook`, `buildImagesConfig`, `buildUploadSecurityHeaders` | media.md, storage.md |
| 27 | **1.9.1** — staging indexed | `IPAL_NOINDEX=1` in the staging env | seo.md |
| 28 | **1.9.2** — own `FormRenderer` (a copy of the engine on `useForm`) | **security:** it passed the whole form document, including the Emails tab, to the browser (company addresses in the HTML). Block → ``, styling into `formClasses.ts`, delete `FormRenderer.tsx`; unusual form → `useBuilderForm` | forms.md |
| 29 | **1.9.2** — multi-step forms / choice lists built in code | admin panel: the **Step**, **Radio**, **Checkbox group**, **Date** blocks; Form messages → next / back / stepOf; Postgres: `migrate:create` | forms.md |
| 30 | **1.9.2** — layout assembled by hand (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) | `` — the same options (banner, analytics, jsonLd, logEndpoint) | PROGRAMISTA §2.8 |
| 31 | **1.9.2** — catch-all page and `not-found.tsx` written by hand | `createPageRoute(content, {…})` / `createNotFoundPage(content, {…})` from `/rsc`; `revalidate` stays a literal | pages.md |
| 32 | **1.9.2** — llms/md/mcp/health/indexnow/manifest routes with configuration in every file | re-export from `lib/content` (`llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`); `summaryField`, `mcp` once in `createContentHelpers` | PROGRAMISTA §2.7 |
| 33 | **1.9.2** — `src/fields/sectionHeader.ts`, `sectionSettings.ts`, `lib/navigation.ts`, hand-written `resolveLinkHref` in `CMSLink` | `buildSectionHeaderField`, `buildSectionSettingsField` (same data shape — no migration), `resolveNav`, `resolveLink` from `lib/content` | blocks.md, links.md |
| 34 | **1.11.0** — a copy of `publicForm`, own field renderer with a variant / context | `RenderForm values` or `prepareBuilderForm` + ``; delete the copy | forms.md |
| 35 | **1.11.0** — extra "categories" relations next to links, links to entries as URLs | `buildLinkField({ relationTo: ['pages', 'categories'] })` (link data migration) | links.md |
| 36 | **1.11.0** — product / category JSON-LD assembled in the project, `jsonLd: false` | `pageJsonLd.entries` + `buildProductJsonLd`, `jsonLd` back on in `createPageRoute` | seo.md |
| 37 | **1.11.0** — own RenderBlocks in the page route only for the first section's `h1`; `storage` in `ipalEnvRules` conditional on NODE_ENV; hand-written `remotePatterns` / `dangerouslyAllowLocalIP` for localhost | `isFirst` from `createPageRoute`; `ipalEnvRules({ storage: true })`; `buildImagesConfig()` | pages.md, env.md, storage.md |
| 38 | **1.11.1** — `revalidatePath` wrapped in a `process.env.NEXT_RUNTIME` condition (seed / `payload run` failed) | delete the condition — the hook skips revalidation outside Next itself; on purpose: `context: { disableRevalidate: true }` | hooks.md |
| 39 | **1.11.1** — focus guard around `RenderForm` (the page scrolled to the form on return) | delete — `BuilderForm` moves focus only when the step changes | forms.md |
| 40 | **1.11.1** — own `ThemeScript` / theme switcher / `useSyncExternalStore` on `data-theme` | `` (or ``), ``, `useTheme`; the same `ipal-theme` key — visitors' choice is kept. Postgres: `migrate:create` (`system`, `themeToggleLabel`) | theme.md |
| 41 | **1.11.1** — own `anchors.ts` / `TableOfContents` / heading converter with `id` | `extractHeadings`, `` (`/client`), `RenderRichText headingIds`, `buildTableOfContentsField()` (same `show`/`label` shape — no data migration) | richtext.md |
| 42 | **1.11.1** — `notFound` caught in `page.tsx` to redirect to the homepage | `createPageRoute(…, { redirect, onMissing: 'redirectHome' })` | pages.md |
| 43 | **1.11.1** — `` sets the background color only for JPEG | delete the condition — `mediaImageProps` does it itself (`placeholderColor`) | media.md |
| 44 | **1.11.1** — `CmsLink['appearance']` replaced with an own type because the type depended on field order | types per shape: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`; `pnpm generate:types` and fix the imports | links.md |
| 45 | **1.11.1** — format description in a form field label / time as text | the **Placeholder** field in the admin panel, the **Time** type; Postgres: `migrate:create` | forms.md |
| 46 | **1.12.3** — own cookie settings window / cookie list in the banner written in the project | `` (list from Cookie banner → Cookie list, captions: Detail labels); delete your own version; Postgres: `migrate:create` | consent.md |
| 47 | **1.13.0** — staff access, Search engines, seed scripts, workarounds around plugin globals | without `access`: every logged-in account gets the staff features → `access` or `globalOverrides` / `formOverrides` / `formSubmissionOverrides` / `collectionOverrides`; with `access`: staff need `editor`/`admin`; Postgres: `migrate:create`; check `settingsDepth`, `sitemap()` throwing, 2FA slug, client IP; own seed code → `@intecion/ipal-kit/seed`; global hooks/access plugins → `revalidatePath` / `globalOverrides` | CHANGELOG 1.13.0, AGENT.md §7.1, seo.md, seeding.md |
| 48 | **1.14.0 — image lightbox** — own image modal (`useState(index)` + `div role="dialog"`), `glightbox` / other lightbox library, thumbnails linking to the raw file in a new tab | `ipalKit({ lightbox: true })` + Postgres `migrate:create`; ``; `` around the thumbnail; delete the old dialog and `pnpm remove glightbox`; old label fields → Form messages → Image viewer | lightbox.md → "Replacing a hand-made modal" |
| 49 | **1.14.0** — import map, Node, Next, audit, cookie list, admin languages | `pnpm payload generate:importmap` (`FaviconCheck`, `RowLabel`); Node 20.9+; `next@^16.4.3` + `sharp@^0.35.5` (Next ≤16.4.0 has two RCEs); `pnpm audit --prod` + `dompurify` / `undici` overrides on payload 3.90.x; hand-kept cookie list → `cookieScanner` (+ `crawl`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`) + `migrate:create`; English-only admin → `i18n.supportedLanguages`; tests on validator strings → full sentences | CHANGELOG 1.14.0, cookie-scanner.md, i18n.md, AGENT.md §4 items 11–12 |
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`.
---
## 7. TROUBLESHOOTING
| Symptom | Cause / fix |
|---|---|
| Empty SEO tab, no Forms collection | `@payloadcms/*` version mismatch — `pnpm.overrides` |
| `PayloadComponent not found in importMap` | `pnpm payload generate:importmap` |
| `Cannot destructure property 'config'` | duplicate `@payloadcms/ui` in the plugin — `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui` |
| `Cannot find module '@clocklimited/payload-2fa'` | inject `plugin: payloadTotp` in `twoFactor` (`serverExternalPackages` does not help) |
| `TS2322` on `plugin: payloadTotp` / `ipal-skills: command not found` | ipal-kit ≤ 1.8.13 — update |
| `[ipal] R2 storage: … adapter was not injected` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| Images 403 for visitors (`/api/media/file/…`) | the Media collection has no public read — `access: { read: () => true }` (storage.md) |
| `R2_PUBLIC_URL is required but missing` in production | media through the app — make the rule optional (env.md) |
| New deploy never goes live / old version keeps serving | the health check fails (migration error, database unreachable) — Coolify deployment log (deployment.md §4.4) |
| Banner without styles | no Tailwind or no `@source` for the plugin |
| `/admin`, `/_next` → 500 | the proxy matcher is not an inline literal |
| `slug.join is not a function` | `[slug]` instead of `[[...slug]]` |
| `/pl` → 404 | Homepage not assigned in System pages |
| `/en/*` → 404, `/pl/*` works | empty title/slug in EN |
| `Missing and ` | root layout deleted, and `[locale]/layout.tsx` does not have them |
| Routes `ƒ` despite `generateStaticParams` | the build does not see the database (§4.3) |
| Build fails on `ENOTFOUND` / Mongoose | a route that reads the database without `force-dynamic` |
| Emails are not sent | no `email: mailAdapter()` or an empty transport in the admin panel |
| Plugin change not visible | dev not restarted / old version in node_modules / `rm -rf .next` |
| Admin panel change not visible on the front end | Save was not clicked, or ISR — `buildRevalidateHook` |
| Old email sender name | mail client cache — check the raw headers |
**"Good code, wrong behavior" — in this order:** restart dev (Payload builds adapters
at startup) → save in the admin panel → duplicate dependency → importmap → cache.
---
## 8. ipal-kit DEVELOPMENT AND PUBLISHING
### 8.1 Change chain
Pre-release checks are the tests in `test/` (also run by `prepublishOnly`):
`docsConsistency.test.ts` (every import in the docs exists in the given entry point / in `lib/content`,
every public export is described in the docs) and `exports.test.ts` (`@intecion/ipal-kit/…` paths from the docs
exist in `exports`). There is no `ipal-release` skill with `check-exports`/`check-deps` in the repo.
**The version number always comes from a human.**
A change does not work in a project until it has passed every stage:
```
src → commit → version → publish (runs clean + build + tests itself) → pnpm add in the project → restart
```
```bash
cd ~/payload-cms/ipal-kit
grep -c "" src/ # >0 — the change is saved
# docs/: API/behavior change → update the module file IN THE SAME commit
pnpm clean && pnpm build
grep -c "" dist/ # >0 — the build picked it up (export in index.ts!)
# docs/CHANGELOG.md: new ## section at the top (keep at least the last 20 versions)
git add -A && git commit -m "description" # BEFORE version (dist/ is ignored anyway)
npm version # a human gives the number; minor = new API, major = breaking
npm publish # registry from publishConfig (Gitea), no --registry
git push && git push --tags
cd ~/
pnpm add @intecion/ipal-kit@
grep -c "" node_modules/@intecion/ipal-kit/dist/ # >0
pnpm dev # restart
```
Grep for a **single symbol**, not a phrase — key order in an object gives a
false 0. Common traps: `npm version` before the commit (dirty repo),
a missing export in `src/index.ts` (`is not a function` in the project), `pnpm add` while
dev is running.
`dist/` **is not in git** (`.gitignore`). `prepublishOnly` runs `pnpm clean && pnpm build &&
pnpm test:int` before every `npm publish`, so you cannot release a stale dist or a
version with red tests (`pnpm clean && pnpm build` above is only a grep check before the
commit). `prepare` (`pnpm build`) builds the package on install from git and on `pnpm install` in the repo.
`typecheck` and `lint` are **not** in `prepublishOnly` — before a commit: `pnpm typecheck && pnpm lint &&
pnpm test:int` (CI in `.gitea/workflows/ci.yml` runs typecheck, lint, test:int and build on push and PR).
### 8.1a Plugin tests
`test/` (outside `src`, not shipped in `dist`), vitest: `pnpm test:int` (once), `pnpm test:watch`.
| Kind | Where | For what |
|---|---|---|
| unit | `test/.test.ts` | pure functions: paths, metadata, robots, CSP, parsers (opening hours, Markdown), validation |
| with a fake Payload | `test/helpers.ts` → `fakePayload()` | logic on the Local API without a database: `submitForm`, Turnstile, MCP, IndexNow |
| integration | `test/integration.test.ts`, `test/drafts.test.ts` — **real Payload + in-memory SQLite** | access, hooks, field schema, drafts, globals — everything the fake cannot reproduce |
| package contract | `test/exports.test.ts` | every `@intecion/ipal-kit/…` path from the docs exists in `exports` |
| docs ↔ code | `test/docsConsistency.test.ts` | names imported in the docs exist in the entry points / `lib/content`; every public export is described in the docs |
| e2e | `pnpm test:e2e` (Playwright) | `pnpm test` = `test:int` + `test:e2e` |
Rules: **every fixed bug = a regression test** (check that it fails on the old code);
no network (`vi.spyOn(globalThis, 'fetch')`); env through `vi.stubEnv` + `unstubAllEnvs`;
`server-only` mocked (`vi.mock('server-only', () => ({}))`); a test for a behavior change
visible to projects → an entry in `docs/CHANGELOG.md`. Test the skill scripts (`audit.sh`,
`seo-check.mjs`, `cookie-scan.mjs`) on a fake site/project in a scratchpad:
an empty project (only errors) and a complete one (0 errors). CI (`.gitea/workflows/ci.yml`) runs
typecheck, lint, tests and build on every push.
### 8.2 Plugin package.json
- `"files": ["dist", "docs", "bin"]` — **the docs and the `ipal-skills` command ship in the package**; agents in projects
read `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Without `docs` they have nothing.
- One `exports` block, all paths to `./dist/` (not `./src/`).
- `payload`, `@payloadcms/*`, `next`, `react` → **`peerDependencies`**
(in `dependencies` = a second copy = hooks without context). `react-dom` is not listed (it comes with `next`).
Optional peers (`peerDependenciesMeta`): `@clocklimited/payload-2fa`, `@payloadcms/storage-s3`.
`dependencies` hold only: `lucide-react`, `nodemailer`, `server-only`, `slugify`.
- `publishConfig.registry` = the Gitea registry — `npm publish` will not reach the public npm.
- No self-reference (never `pnpm add` in the plugin directory).
- The plugin never imports `next/server`, `next/cache`, `@payload-config` or
optional packages directly — the project injects them (the `NextResponse`,
`revalidatePath`, `payloadTotp`, `s3Storage` pattern). Optional package = optional
`peerDependency` + a minimal-shape type in the plugin, zero imports.
- Import from `next/*` in a plugin client component: with the extension
(`'next/navigation.js'`) — `next` has no `exports` field, otherwise NodeNext cannot find it.
```bash
grep -c '"exports"' package.json # 1
grep -c "git+https.*ipal-kit" package.json # 0
grep '"import"' package.json | head -1 # ./dist/
```
### 8.3 Publishing token
Gitea → Settings → Applications → a token with `write:package`, in the **global**
`.npmrc` (`~/.npmrc`, Windows `%USERPROFILE%\.npmrc`):
```
//git.intecion.net/api/packages/IntecionSoftware/npm/:_authToken=${GITEA_TOKEN}
```
### 8.4 Verification after publishing
```bash
pnpm store prune
pnpm add @intecion/ipal-kit
node -e "console.log(require.resolve('@intecion/ipal-kit/next/middleware'))" # → dist/…
ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md
```
| Symptom | Cause |
|---|---|
| `Cannot find module …/src/…ts` | `exports` points to `src` |
| "Module not found" although the file exists | two `exports` blocks |
| `ENOENT …ipal-kit.tgz` | self-reference in `dependencies` |
| old code despite reinstalling | version not bumped; `pnpm store prune` + `rm -rf .next node_modules/@intecion` |
Versions: 1.x = Payload 3. Moving to Payload 4 → ipal-kit 2.0.
---
## 9. GIT AND GITEA (`git.intecion.net`)
### 9.1 Access (once)
**HTTPS + token:** Gitea → Settings → Applications → a `write:repository` token.
On `clone`/`push`: your Gitea login, and the **token** as the password (the account password does not work).
To remember it: macOS `git config --global credential.helper osxkeychain`, Windows
`… manager`, Linux `… 'cache --timeout=3600'`.
**SSH:** `ssh-keygen -t ed25519 -C "you@intecion.net"`, public key to Gitea →
Settings → SSH / GPG Keys, test with `ssh -T -p 22222 git@git.intecion.net`.
```bash
git clone https://git.intecion.net/IntecionSoftware/.git
git clone ssh://git@git.intecion.net:22222/IntecionSoftware/.git
```
### 9.2 Daily
```bash
git pull # before work and before push
git checkout -b # work on a branch
git add . && git commit -m "what and why"
git push -u origin # then a Pull Request to main in Gitea
```
Never `git push --force` on `main` (only on your own branch).
### 9.3 Several projects
Each project is a separate directory and repo (`~/projects/client-a`, `~/projects/ipal-kit`).
Git works on the directory you are in — after `cd` always run `git status` and
`git remote -v` before you push anything.
### 9.4 Errors
| Message | Fix |
|---|---|
| `Permission denied (publickey)` | key not added in Gitea or wrong port (`-p 22222`) |
| `Unauthorized` / password prompt over and over | use the token instead of the password; scope `write:repository` |
| `non-fast-forward`, "tip … is behind" | `git pull`, resolve conflicts, `git push` |
| `repository not found` | wrong address or no access to the repo |
| 404 on `pnpm add @intecion/…` | no `@intecion:registry` line in the project's `.npmrc` |