Project starter: ipal-kit create <domain> generates a new site from the reference site
- bin `ipal-kit` (subcommand `create`): the architecture questions (or --answers JSON), rendering from reference/ through starter.manifest.json (placeholders, @starter:if variants, //: alternatives, demo dropped), answers into AGENTS.md "Project decisions" and ipal-doctor.json, local .env with a fresh PAYLOAD_SECRET, install from the shipped lockfile, ipal-skills, ipal-tokens, generate:types/importmap, typecheck, ipal-doctor when shipped, secret check, first commit - @intecion/ipal-kit/starter: the building blocks (renderSite, validateAnswers, applyVariants, collectBundle, lockfileWithoutPlugin, secretFindings …) - build:starter packs reference/ into dist/starter/template.json.gz (90 KB); starter:gate in prepublishOnly: site from the packed tarball, frozen install, seed, build, targeted SEED_ONLY seed in production mode, full seed refused, pnpm start checks - D15: plugin dependencies pinned exactly (nodemailer 10.3.1) - reference/: @starter:if markers (runs as before), manifest generate/variants/rewrite - docs: project-starter.md, AGENT.md, ipal-setup, ipal-site, ipal-reference (+ api.md), README, PROGRAMISTA §2, CHANGELOG, docs/README, reference index Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
154049662e
commit
804a09efed
@@ -53,3 +53,6 @@ next-env.d.ts
|
||||
|
||||
# build output — produced by `pnpm build` (prepare/prepublishOnly), not committed
|
||||
/dist
|
||||
|
||||
# pnpm starter:gate work folder
|
||||
.starter-gate/
|
||||
|
||||
@@ -61,6 +61,16 @@ quick throwaway test it works. But prefer the registry for real projects:
|
||||
Keep the git install only for pulling a specific unreleased commit during
|
||||
plugin development.
|
||||
|
||||
### A new site in one command
|
||||
|
||||
```bash
|
||||
pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create intecion.com
|
||||
```
|
||||
|
||||
Asks the architecture questions (or reads `--answers answers.json`), generates the site from the reference
|
||||
site with every team convention, installs it from a shipped lockfile and makes the first commit. Needs the
|
||||
`@intecion` registry line in `~/.npmrc`. Details: [docs/project-starter.md](./docs/project-starter.md).
|
||||
|
||||
---
|
||||
|
||||
## Finish setting up your project
|
||||
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env node
|
||||
// ipal-kit — the plugin's command line.
|
||||
// pnpm dlx @intecion/ipal-kit@<version> create intecion.com → a new client site (docs/project-starter.md)
|
||||
// pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json
|
||||
// `pnpm dlx <package>` runs the bin named after the package, so every subcommand lives here.
|
||||
// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens.
|
||||
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const USAGE = `Usage: ipal-kit <command> [options]
|
||||
create <domain> a new client site from the reference site (ipal-kit create --help)
|
||||
|
||||
Other tools: ipal-skills, ipal-blocks, ipal-tokens`
|
||||
|
||||
const [command, ...args] = process.argv.slice(2)
|
||||
if (command !== 'create') {
|
||||
console.log(USAGE)
|
||||
process.exit(command === undefined || command === '--help' || command === '-h' ? 0 : 1)
|
||||
}
|
||||
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const { runCreateCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'starter', 'cli.js')).href)
|
||||
process.exit(await runCreateCli(args))
|
||||
+16
-1
@@ -11,9 +11,19 @@ once there are more than 20.
|
||||
## Unreleased
|
||||
|
||||
Database names follow one rule, and seeding a live site touches only the records you name. The block library:
|
||||
fifteen ready page sections and ten page templates.
|
||||
fifteen ready page sections and ten page templates. A new site in one command: `ipal-kit create`.
|
||||
|
||||
### New
|
||||
- **`ipal-kit create` — a new site in one command** ([project-starter.md](./project-starter.md)):
|
||||
`pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create intecion.com` asks the architecture
|
||||
questions (or reads `--answers answers.json`), generates the site from the reference site (`reference/` through
|
||||
`starter.manifest.json`: placeholders, `@starter:if` variants, demo left out), writes the answers into `AGENTS.md` →
|
||||
Project decisions and `ipal-doctor.json`, installs from a shipped lockfile, runs `ipal-skills`, `ipal-tokens`,
|
||||
`generate:types`, `generate:importmap`, `typecheck`, checks for secrets and makes the first commit. New bin `ipal-kit`
|
||||
(subcommand `create`), new entry `@intecion/ipal-kit/starter` with the building blocks (`renderSite`,
|
||||
`validateAnswers`, `applyVariants`, `collectBundle` …). New scripts `build:starter` and `starter:gate` in
|
||||
`prepublishOnly`: a site made from the packed tarball must install frozen, seed, build, run the targeted seed in
|
||||
production mode and serve `/pl` before a publish. Adds ~180 KB to the tarball.
|
||||
- **Design-token standard** ([design-tokens.md](./design-tokens.md)): one set of `--ipal-*` names for every site,
|
||||
only the values differ per brand. `@intecion/ipal-kit/tokens.css` (neutral defaults, light/dark on `data-theme`,
|
||||
`[data-surface="inverse"]` scope, reduced motion), `@intecion/ipal-kit/tailwind.css` (Tailwind 4 preset: `bg-surface`,
|
||||
@@ -50,6 +60,11 @@ fifteen ready page sections and ten page templates.
|
||||
plugin repo (`reference/`, not shipped) and is built, seeded and smoke-tested in the plugin's CI.
|
||||
|
||||
### Changed
|
||||
- The plugin's own dependencies are pinned to exact versions (`lucide-react` 0.400.0, `nodemailer` 10.3.1,
|
||||
`server-only` 0.0.1, `slugify` 1.6.9), so two sites created from the same release get identical trees. Projects:
|
||||
nothing to do (pnpm installs the pinned versions; `nodemailer` moves from 10.2.1 to 10.3.1).
|
||||
- The reference site carries `@starter:if` markers (comment lines) and the starter's alternatives as `//: ` lines;
|
||||
it runs exactly as before.
|
||||
- **Cookie banner / button colours** read the single token names (`--ipal-surface`, `--ipal-text` …) instead of
|
||||
`dark:` + `--ipal-*-dark`. With `tokens.css` they switch with the theme. Without it, the built-in fallback follows the
|
||||
page's `color-scheme` (`light-dark()`): a site without a dark theme no longer gets a dark banner on a dark-mode
|
||||
|
||||
@@ -29,6 +29,7 @@ API details — one file per module:
|
||||
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
|
||||
| Routing, archives, redirects, Markdown, search | [content.md](./content.md) |
|
||||
| Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) |
|
||||
| New site in one command (`ipal-kit create`, `@intecion/ipal-kit/starter`) | [project-starter.md](./project-starter.md) |
|
||||
| Deployment, production variables, health check | [deployment.md](./deployment.md) |
|
||||
| Seeds: create-only, dry run, backup, production update guard | [seeding.md](./seeding.md) |
|
||||
| Email SMTP / Graph | [email.md](./email.md) |
|
||||
|
||||
@@ -78,6 +78,11 @@ the ready-to-send list is in **ipal-setup** stage 0 (ipal-site phase 0 uses the
|
||||
| Admin | 2FA, white-label (client brand in the panel), agency credit |
|
||||
| Hosting | Coolify, the production domain(s), who adds the DNS records (deployment.md §6) |
|
||||
|
||||
- **A new site starts with `ipal-kit create`** (docs/project-starter.md): `pnpm --config.auto-install-peers=false dlx
|
||||
@intecion/ipal-kit@<version> create <domain>` asks exactly these questions (or reads them from `--answers file.json`),
|
||||
generates the site from the reference site, writes the answers into `AGENTS.md` and makes the first commit. Ask the owner
|
||||
first, then pass the answers — the command never fills a gap. The manual path (`ipal-setup` stages 1–11) is for an
|
||||
existing project or what the command does not cover yet (another default language, no URL prefix, Postgres).
|
||||
- Write every answer into the project's `AGENTS.md` → **"Project decisions"** (one line per topic).
|
||||
- **Do not guess a missing answer.** No answer to an architecture question → do not build that part; ask again.
|
||||
(Only *content* gaps — company data, texts, IDs — may wait: use `[TO FILL: …]` in the panel, §0a.)
|
||||
@@ -1314,6 +1319,7 @@ Anything that needs a developer → move it to the panel.
|
||||
| R2, `buildImagesConfig`, YouTube | [storage.md](../storage.md) |
|
||||
| Front end: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](../frontend.md) |
|
||||
| Integrations (the `site-integrations` global, statuses, email test) | [integrations.md](../integrations.md) |
|
||||
| New site from the reference site: `ipal-kit create`, `@intecion/ipal-kit/starter` | [project-starter.md](../project-starter.md) |
|
||||
| Deployment, production env, health check | [deployment.md](../deployment.md) |
|
||||
| Seeds on production: create-only, dry run, backup, update guard | [seeding.md](../seeding.md) |
|
||||
| Meta Pixel / GA4 via GTM | [gtm-meta-pixel.md](../gtm-meta-pixel.md) |
|
||||
|
||||
@@ -25,7 +25,7 @@ Rules: AGENT.md §13, §0a.
|
||||
| `README.md` | how to run the reference site and what is where |
|
||||
| `docs/DEPLOY.md` | the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback |
|
||||
| `ipal-doctor.json` | the production domain and launch state for ipal-doctor (below) |
|
||||
| `next.config.ts` | security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By (below) |
|
||||
| `next.config.ts` | security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By |
|
||||
| `package.json` | scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides |
|
||||
| `playwright.config.ts` | smoke tests against the built, seeded site (below) |
|
||||
| `postcss.config.mjs` | Tailwind 4 through PostCSS (below) |
|
||||
@@ -67,48 +67,6 @@ legacy-peer-deps=true
|
||||
}
|
||||
```
|
||||
|
||||
### `next.config.ts`
|
||||
|
||||
```ts
|
||||
import type { NextConfig } from 'next'
|
||||
|
||||
import {
|
||||
buildAdminCspHeaders,
|
||||
buildImagesConfig,
|
||||
buildSecurityHeaders,
|
||||
buildUploadSecurityHeaders,
|
||||
withSecurityConfig,
|
||||
} from '@intecion/ipal-kit'
|
||||
import { withPayload } from '@payloadcms/next/withPayload'
|
||||
|
||||
// CSP enforced: the reference site is the example after the report-only phase (security.md → "ROLL OUT CSP").
|
||||
// Flags = what the site loads: Turnstile on forms, Google analytics/GTM when IDs are set in Site integrations.
|
||||
const csp = { mode: 'enforce', r2Url: process.env.R2_PUBLIC_URL, reportUri: '/api/csp-report' } as const
|
||||
|
||||
const securityHeaders = buildSecurityHeaders({
|
||||
csp: { ...csp, analytics: true, turnstile: true },
|
||||
hsts: process.env.NODE_ENV === 'production',
|
||||
})
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
// ALLOW_LOCAL_MEDIA=1 (local / CI production checks only): let next/image optimize files the app serves on localhost
|
||||
images: buildImagesConfig(process.env.ALLOW_LOCAL_MEDIA === '1' ? { production: false } : {}),
|
||||
// Metadata in <head> for crawlers (deployment.md §3a)
|
||||
htmlLimitedBots:
|
||||
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
|
||||
async headers() {
|
||||
return [
|
||||
{ source: '/:path*', headers: securityHeaders },
|
||||
{ source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, // after the site-wide rule
|
||||
...buildUploadSecurityHeaders(),
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
|
||||
export default withPayload(withSecurityConfig(nextConfig))
|
||||
```
|
||||
|
||||
### `playwright.config.ts`
|
||||
|
||||
```ts
|
||||
@@ -200,8 +158,12 @@ import type { ContentOption } from '@intecion/ipal-kit'
|
||||
*/
|
||||
export const contentConfig: ContentOption = {
|
||||
collections: [
|
||||
// @starter:if posts
|
||||
{ slug: 'posts', label: 'Blog', perPage: 9 },
|
||||
// @starter:endif
|
||||
// @starter:if caseStudies
|
||||
{ slug: 'caseStudies', label: 'Case studies', perPage: 9 },
|
||||
// @starter:endif
|
||||
],
|
||||
}
|
||||
```
|
||||
@@ -245,9 +207,21 @@ export function register() {
|
||||
// databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor).
|
||||
// R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md).
|
||||
assertEnv(
|
||||
ipalEnvRules({ databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) =>
|
||||
rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule,
|
||||
),
|
||||
ipalEnvRules({
|
||||
// @starter:if crawl
|
||||
//: cookieCrawl: true, // IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN — the shared cookie-crawler service
|
||||
// @starter:endif
|
||||
databaseName: { domain: 'example-studio.pl' },
|
||||
// @starter:if graph
|
||||
//: emailGraph: true, // GRAPH_* — e-mail through Microsoft Graph
|
||||
// @starter:endif
|
||||
ipHeader: true,
|
||||
// @starter:if r2
|
||||
storage: process.env.ALLOW_LOCAL_MEDIA !== '1',
|
||||
// @starter:else
|
||||
//: storage: false, // media on local disk — a Coolify persistent volume (AGENTS.md → Project decisions)
|
||||
// @starter:endif
|
||||
}).map((rule) => (rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule)),
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -566,12 +540,18 @@ import { libraryBlocks, type LibraryBlocksOptions } from '@intecion/ipal-kit/blo
|
||||
export const blockOptions = {
|
||||
contact: true,
|
||||
cta: true,
|
||||
// @starter:if collections
|
||||
entryList: {
|
||||
collections: [
|
||||
// @starter:if posts
|
||||
{ label: { en: 'Blog posts', pl: 'Wpisy' }, value: 'posts' },
|
||||
// @starter:endif
|
||||
// @starter:if caseStudies
|
||||
{ label: { en: 'Case studies', pl: 'Realizacje' }, value: 'caseStudies' },
|
||||
// @starter:endif
|
||||
],
|
||||
},
|
||||
// @starter:endif
|
||||
faq: true,
|
||||
featureGrid: true,
|
||||
gallery: true,
|
||||
|
||||
@@ -195,6 +195,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
|
||||
| a11y widget CSS | `styles.css` | `@import "@intecion/ipal-kit/a11y.css";` (only with `<AccessibilityWidget>`) | widget options change the page | accessibility.md |
|
||||
| `/its` panel | `app/(payload)/its/…` | `adminRoute: '/its'` + `its` in the proxy matcher | `/its` login, `/admin` 404 | security.md |
|
||||
| skills | `package.json` | `"ipal:skills": "ipal-skills"` | `.agents/skills/` up to date | PROGRAMISTA §2.1a |
|
||||
| a new site | CLI (from the parent folder) | `pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <domain> [--answers answers.json] [--dir] [--external] [--no-install] [--no-git] [--dry-run]`; in a project: `pnpm exec ipal-kit create <domain> --dir ../<name>-web`. Building blocks: `@intecion/ipal-kit/starter` (resources/api.md) | one commit, `AGENTS.md` decisions filled, `pnpm typecheck` passes | project-starter.md |
|
||||
| eject a library block | CLI | `pnpm exec ipal-blocks list` / `pnpm exec ipal-blocks eject faq [--dest src/blocks] [--dry-run]` → `src/blocks/Faq/`; then the ejected builder in `blockOptions`' place and `components: { faq: FaqBlock }` | the block renders from the project file | block-library.md "Own blocks and eject" |
|
||||
|
||||
**`createContentHelpers` keys (exports of `@/lib/content`)** — all lazy and cached per request:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# ipal-kit — export index
|
||||
|
||||
Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`,
|
||||
`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`), grouped by module. Search with grep
|
||||
`/server`, `/seed`, `/starter`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`), grouped by module. Search with grep
|
||||
(`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself.
|
||||
"Import from" column — the first entry is preferred. Plugin options, env, routes and what the
|
||||
project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`.
|
||||
@@ -739,6 +739,31 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP
|
||||
|
||||
**Types:** `ThemeOptions` (root, `ipalKit({ theme })`), `Theme`, `ThemeSetting`, `ThemeConfig` (root, `/client`) — theme, setting from the panel and theme options; `ThemeScriptProps` (`/rsc`), `ThemeSwitcherProps`, `ThemeSwitcherClassNames` (`/client`) — component props.
|
||||
|
||||
## Project starter (`starter`) — details: `node_modules/@intecion/ipal-kit/docs/project-starter.md`
|
||||
|
||||
Bin: `ipal-kit create <domain>` (`pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create …`).
|
||||
`@intecion/ipal-kit/starter` uses Node built-ins only (no Payload) — the building blocks of the command.
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `runCreateCli(args, log?)`, `CREATE_USAGE` | `@intecion/ipal-kit/starter` | The command (`ipal-kit create`) — returns the exit code. |
|
||||
| `parseCreateArgs(args)`, `normalizeDomain(input)`, `localEnv(example)` | `@intecion/ipal-kit/starter` | Its pieces: options, `https://www.X.pl/` → `x.pl` (punycode), `.env` with a fresh `PAYLOAD_SECRET`. |
|
||||
| `validateAnswers(input)`, `STARTER_TOPICS` | `@intecion/ipal-kit/starter` | The architecture answers (`StarterAnswers`): every missing / invalid one as a line; `[]` = valid. |
|
||||
| `flagsFromAnswers(answers)` | `@intecion/ipal-kit/starter` | The `@starter:if` flags the answers turn on (`twoFactor`, `posts`, `crawl`, `r2`, `enforceCsp: false`, `demo: false`…). |
|
||||
| `askAnswers(ask)` | `@intecion/ipal-kit/starter` | The questions with any `ask(question) → Promise<string>` (terminal, chat bridge). |
|
||||
| `collectBundle(dir)`, `packBundle(bundle)`, `unpackBundle(buffer)`, `bundleFlags(bundle)` | `@intecion/ipal-kit/starter` | `reference/` → the bundle (fails on a fake value in a kept file) → gzip and back; the flags the markers use. |
|
||||
| `renderSite(bundle, answers, ctx)`, `placeholderValues(answers, ctx)` | `@intecion/ipal-kit/starter` | The new site's files (path → content), in memory; the value of every `{{token}}`. |
|
||||
| `applyVariants(text, flags, file?)`, `variantFlags(text)` | `@intecion/ipal-kit/starter` | `@starter:if` / `else` / `endif` blocks (nesting; `//: ` / `#: ` lines uncommented inside kept blocks). |
|
||||
| `applyPlaceholders(text, fakes, values)`, `leftoverFakes(text, fakes)` | `@intecion/ipal-kit/starter` | Fake values → the site's values (longest first); what is left. |
|
||||
| `assertManifest(value)`, `fileRole(path, manifest)`, `matchGlob(path, glob)`, `ALWAYS_SKIPPED` | `@intecion/ipal-kit/starter` | `starter.manifest.json`: drop / generate / template / keep. |
|
||||
| `renderI18nConfig`, `renderTokens`, `renderDesignMd`, `renderAgentsMd`, `renderDecisions`, `renderDoctorConfig` | `@intecion/ipal-kit/starter` | Files and sections written from the answers (languages, brand, DESIGN.md, AGENTS.md decisions, ipal-doctor.json). |
|
||||
| `rewriteFonts(layout, answers)`, `fontExport(name)`, `rewritePackageJson(text, rules, ctx, answers)` | `@intecion/ipal-kit/starter` | next/font calls → the answered fonts; the manifest's package.json rewrite. |
|
||||
| `lockfileWithoutPlugin(lock)` | `@intecion/ipal-kit/starter` | The reference lockfile without the plugin (shipped with the bundle). |
|
||||
| `secretFindings(files)` | `@intecion/ipal-kit/starter` | The pre-commit check: `.env*`, assigned secrets, private keys. |
|
||||
|
||||
**Types:** `StarterAnswers`, `AnalyticsTool`, `ContentCollection` — the answers; `StarterBundle`, `StarterManifest`, `FileRole`,
|
||||
`StarterFlags`, `SiteContext` — the bundle, the manifest, the flags and the site context (all `/starter`).
|
||||
|
||||
## Design tokens (`tokens`) — details: `node_modules/@intecion/ipal-kit/docs/design-tokens.md`
|
||||
|
||||
CSS: `@intecion/ipal-kit/tokens.css` (neutral `--ipal-*` defaults, light/dark, `[data-surface="inverse"]`), `@intecion/ipal-kit/tailwind.css`
|
||||
|
||||
@@ -66,7 +66,21 @@ propose a concrete choice and get a yes before you build it.
|
||||
|
||||
## 1. Installation
|
||||
|
||||
**Steps.** Scaffold: `npx create-payload-app@latest <project>` (Blank, Postgres/Mongo), delete the starter
|
||||
**New site: `ipal-kit create` does stages 1–10 in one command** (`node_modules/@intecion/ipal-kit/docs/project-starter.md`).
|
||||
After stage 0, write the answers as JSON (shape `StarterAnswers` from `@intecion/ipal-kit/starter`) and run, from the
|
||||
folder that will hold the project (needs the `@intecion` registry line in `~/.npmrc`):
|
||||
```bash
|
||||
pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <domain> --answers answers.json
|
||||
```
|
||||
It generates the site from the reference site, writes `.env` (fresh `PAYLOAD_SECRET`), installs from the shipped
|
||||
lockfile, runs `ipal-skills`, `ipal-tokens`, `generate:types`, `generate:importmap`, `typecheck` (and `ipal-doctor
|
||||
--strict` when shipped), checks for secrets and makes the first commit. **Check:** `git log --oneline` = 1 commit,
|
||||
`git status` clean, `AGENTS.md` → "Project decisions" holds every answer, `pnpm typecheck` passes. Then go to stage 11.
|
||||
**Turn off / override:** it refuses another default language than `pl`, sites without `en`, URLs without a prefix and
|
||||
Postgres — use the stages below; every generated file is the project's own afterwards. The stages below are also the
|
||||
path for an existing project.
|
||||
|
||||
**Steps (manual path).** Scaffold: `npx create-payload-app@latest <project>` (Blank, Postgres/Mongo), delete the starter
|
||||
`src/app/(frontend)/layout.tsx` and `page.tsx` (the frontend root becomes `[locale]/layout.tsx`). Do not create
|
||||
`middleware.ts` (Next 16 = `proxy.ts`; delete an existing one). Never install from git (`git+https://…`).
|
||||
```ini
|
||||
|
||||
@@ -45,7 +45,12 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r
|
||||
decision (AGENT §0a) and on a plugin gap (ipal-plugin-gap — report, wait for the owner).
|
||||
|
||||
## Phase 1 — Foundation
|
||||
- New project → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`). Every file you wire has its canonical
|
||||
- **New site → `ipal-kit create`** with the phase-0 answers as JSON (`docs/project-starter.md`):
|
||||
`pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <domain> --answers answers.json`.
|
||||
It generates the site from the reference site (every §0b item wired), installs the skills, writes the answers into
|
||||
`AGENTS.md`, and makes the first commit. Check: `git log --oneline` = 1 commit, `pnpm typecheck` passes. Then continue
|
||||
with phase 2. What it refuses (another default language, no URL prefix, Postgres) → the manual path below.
|
||||
- New project without the command → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`). Every file you wire has its canonical
|
||||
version in the reference site: `node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md` (AGENT.md
|
||||
"Reference site") — copy the pattern, change only the content.
|
||||
- Existing project on an older ipal-kit → **ipal-upgrade** before anything else.
|
||||
|
||||
@@ -95,6 +95,11 @@ once: `NPM_CONFIG_USERCONFIG=/dev/null pnpm up --latest @intecion/ipal-kit`.
|
||||
|
||||
## 2. NEW PROJECT — ORDER
|
||||
|
||||
**Fastest: one command.** `pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <domain>`
|
||||
generates the whole site from the reference site — questions, files, install, skills, first commit
|
||||
([project-starter.md](../project-starter.md)). The order below is the manual path (an existing project, or what the
|
||||
command does not cover yet).
|
||||
|
||||
Pnpm, Node 22+, Next 16, Payload 3. The order matters.
|
||||
|
||||
### 2.1 Skeleton
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
# Project starter — proposal (`ipal-kit create`)
|
||||
|
||||
**Status:** built (revision 3) — the user guide is [docs/project-starter.md](../project-starter.md). Differences from
|
||||
this design, found while building: the env rules stay inline in `instrumentation.ts` as in the reference site (no
|
||||
`src/env.rules.ts`); no `packageManager` field (the reference site has none — add it there and the starter copies it);
|
||||
the command needs `--config.auto-install-peers=false` to keep `dlx` small (7 packages instead of 356); the templates
|
||||
and the lockfile travel in one bundle (`dist/starter/template.json.gz`); the seed command is the reference's
|
||||
`SEED_ONLY=… pnpm seed`; the language answers are limited to default `pl` + `en` (the base seed is Polish + English).
|
||||
**Revision 3 (2026-10-29):** the owner accepted every remaining recommendation (D2–D16) with two changes:
|
||||
**MongoDB only** in v1, and **no Dockerfile** — the team builds and checks locally, Coolify deploys the app from
|
||||
the repo with its default build pack, and MongoDB runs as its own Coolify resource on the same Docker network
|
||||
(§4.8). The doctor runs in CI only on new sites; client sites stay untouched.
|
||||
**Revision 2 (2026-10-29):** the owner chose "just ipal-kit" — the starter is a command of
|
||||
`@intecion/ipal-kit`, not a separate package (§5); D6 is done on main (`0ed3898`); the live-site risks in
|
||||
§1.3 are information only (the owner talks to the clients — no fix sessions, no edits to client sites).
|
||||
**Branch:** `claude/project-starter-14fd31` · **Plugin version at writing:** 1.14.6 · **Date:** 2026-10-29
|
||||
|
||||
**Goal:** one command creates a new Payload 3 + Next 16 client site that already follows every team
|
||||
convention, so every project starts identical and passes `ipal-doctor` with zero findings on day one.
|
||||
|
||||
```bash
|
||||
pnpm dlx @intecion/ipal-kit@1.15.0 create intecion.com
|
||||
```
|
||||
|
||||
Contents: §1 survey of the existing sites · §2 the command and its questions · §3 the generated tree ·
|
||||
§4 what each file does · §5 where it lives and how it ships · §6 staying in sync with the plugin ·
|
||||
§7 how it fits the sibling tracks · §8 decisions for the owner · §9 build plan.
|
||||
|
||||
---
|
||||
|
||||
## 1. Survey — the seven existing sites
|
||||
|
||||
Read-only survey of `architektimprezpl-web`, `coastalclimatesupplycomau-web`, `ecogenicacouk-web`,
|
||||
`intecioncom-web`, `saydiamondspl-web`, `thecleanteampl-web`, `vanstevpl-web` (nothing edited).
|
||||
|
||||
### 1.1 What they already share (the starter keeps it)
|
||||
|
||||
- Payload 3 + Next 16 App Router, `(payload)` group + a frontend group with `[[...slug]]` on `createPageRoute`.
|
||||
- `proxy.ts` (no `middleware.ts` anywhere), identical: `createProxy(i18nConfig, { NextResponse, markdown: true })`
|
||||
with the inline matcher.
|
||||
- `src/{payload.config,i18n.config,proxy,instrumentation}.ts`, `src/lib/content.ts` (`createContentHelpers`),
|
||||
`api/{health,mcp}`, `llms.txt`, `llms-full.txt`, `sitemap.xml`, `md/`, `robots.ts`, `manifest.ts`,
|
||||
`src/blocks/<Name>/`, `src/collections`, `src/globals`, `src/components`.
|
||||
- **MongoDB in production on all seven**; `buildR2Storage(['media'], { s3Storage })`; `mailAdapter()`;
|
||||
`payloadTotp` 2FA; `ipalKit` always with `i18n`, `access`, `pages`, `seo`, `forms.redirectRelationships`.
|
||||
- `next.config`: `buildSecurityHeaders`, `buildImagesConfig()`, `buildUploadSecurityHeaders()`, the same
|
||||
`htmlLimitedBots` regex; `build` with `--webpack`.
|
||||
- `instrumentation.ts` with `assertEnv(ipalEnvRules(…))` from `/env`, nodejs-guarded.
|
||||
- `.npmrc` = `legacy-peer-deps=true` + the `@intecion` registry line; `.agents/skills/ipal-*` committed;
|
||||
`tsconfig` excludes `.agents`; nobody uses `.claude/skills`.
|
||||
- `scripts/seed-form-<name>.ts` via `payload run` + `createSeeder`.
|
||||
- **No site has CI, a Coolify file (`nixpacks.toml`) or a working Docker setup.** Five build with Coolify's
|
||||
default (Nixpacks); the two Dockerfiles are stock Next examples.
|
||||
|
||||
### 1.2 Where they drift
|
||||
|
||||
| Item | architekt | coastal | ecogenica | intecion | saydiamonds | cleanteam | vanstev |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| ipal-kit | 1.14.6 | 1.14.1 | 1.14.1 | 1.14.6 | 1.11.0 | ^1.12.2 | 1.12.2 |
|
||||
| payload | 3.90.2 | ^3.0.0 (unpinned) | 3.92.0 | 3.90.2 | 3.90.2 | 3.90.2 | 3.88.0 |
|
||||
| next | ^16.4.3 | ^16.4.3 | 16.4.3 | 16.4.3 | ^16.3.6 | 16.2.6 ⚠ | 16.2.6 ⚠ |
|
||||
| packageManager | pnpm 10.34.3 | pnpm 11.15.0 | pnpm 10.17.1 | — | pnpm 10.34.7 | — | — |
|
||||
| engines.node | ≥22.0 | ≥22.13 | ≥22.23.4 | ≥20.9 | — | ^18 \|\| ≥20.9 | — |
|
||||
| extra DB adapters | — | sqlite | — | — | — | sqlite | sqlite + postgres |
|
||||
| DB env var | URI | URI \|\| URL | URI | URI | URI | URL \|\| URI | URI |
|
||||
| DB name | `dev` | `…_dev`/`_prod` (drops "com") | `ecogenicacouk_dev`/`_prod` ✓ | `intecioncom-dev` | `saydiamonds` | `test` in prod ⚠ | `vanstevpl` |
|
||||
| withSecurityConfig / CSP | yes / report-only | yes / report-only | yes / report-only | yes / report-only | no / enforce | no / enforce + unsafe-eval | no / enforce + unsafe-eval |
|
||||
| admin CSP + `csp-report` route | yes | yes | yes | yes | no | no | no |
|
||||
| locales / `[locale]` | pl / no | en / no | en / no | pl,en / yes | pl,en / yes (`(site)`) | pl,en / yes | pl,en,de / yes |
|
||||
| consentLog, indexNow | yes | yes | yes | yes | yes | yes | no |
|
||||
| cookieScanner | yes | — | — | yes | — | — | — |
|
||||
| adminMeta / agency / theme option | — | — | — | — (theme prop only) | — | — | — |
|
||||
| Tailwind 4 | yes | yes | yes | yes | none | yes | yes |
|
||||
| eslint / prettier | — | stub / yes | — | — | — | full / yes | — |
|
||||
| tests | tsx --test | — | playwright | — | playwright | vitest + playwright | — |
|
||||
| seed | full | named forms only | foundation (refuses non-`_dev`) | full | full, creates admin from env | partial | full + upgrade |
|
||||
| AGENTS ipal block / CLAUDE.md | yes / yes | yes / yes | AGENT.md inlined ×4 / yes | yes / yes | no / no | no / no | no / no |
|
||||
| "Project decisions" | EN | EN | EN (renamed) | PL §6 | PL | PL | `.agents/context/project.md` |
|
||||
| Docker | — | stock, broken | — | — | — | stock + `standalone` | — |
|
||||
| package name | `architektimprezpl-web` | `coastalclimatesupplyau-web` | ✓ | ✓ | `say-diamondspl-web` | `the-clean-team` | ✓ |
|
||||
|
||||
### 1.3 Problems found — information only
|
||||
|
||||
The owner decided (2026-10-29): no fix sessions and no edits to any client site; they will ask each client
|
||||
whether to move to the latest ipal-kit, which supports these fixes. Kept here as context.
|
||||
|
||||
1. `thecleanteampl-web`: per its `AGENTS.md` production reads the Mongo database `test` (URL without a db
|
||||
name) on the same instance as dev. Highest risk.
|
||||
2. `ecogenicacouk-web`: the local `.env` points at `ecogenicacouk_prod` — a plain local run writes to production.
|
||||
3. `saydiamondspl-web/.env.example` commits a real server IP and the Coolify internal hostname (also in
|
||||
`thecleanteampl-web/AGENTS.md`).
|
||||
4. `coastalclimatesupplycomau-web/Dockerfile` copies `.next/standalone` without `output: 'standalone'` (build
|
||||
fails); its compose file uses Node 20 against `engines ≥22.13`; `payload` unpinned.
|
||||
5. `vanstevpl-web`: seed hard-codes a path in a developer's home folder; `PAYLOAD_SECRET` has a hard-coded
|
||||
fallback; its own `Users` duplicates the injected one; `payloadTotp as never`; consentLog off and the
|
||||
default banner without `logEndpoint`; hand-rolled `ipal:skills`.
|
||||
6. `thecleanteampl-web` and `vanstevpl-web` are on Next 16.2.6 — below the 16.4.1 minimum (AGENT.md §4 item 11).
|
||||
7. saydiamonds and cleanteam set `localization` by hand — dead code, the plugin overwrites it.
|
||||
8. Three sites lack the `ipal-reference` skill and the `AGENTS.md` pointer block.
|
||||
|
||||
### 1.4 What the survey decides for the starter
|
||||
|
||||
- **MongoDB is the default** (all seven); database names `<dbBase>_dev` / `_prod` exactly as ecogenica does,
|
||||
in `DATABASE_URI` only (never `DATABASE_URL`, never a hard-coded fallback).
|
||||
- `.agents/skills` (no site uses `.claude/skills`), `"ipal:skills": "ipal-skills"`, `ipal-reference` included.
|
||||
- `withSecurityConfig` + report-only CSP + admin CSP + `csp-report` route — four sites already do it.
|
||||
- Pin everything: `packageManager`, `engines`, `.nvmrc`, exact `payload`/`@payloadcms/*`/`next` — drift in all
|
||||
three is the biggest source of difference today.
|
||||
- The Coolify path the team already uses: build from the repo with Coolify's default build pack (Nixpacks),
|
||||
no Dockerfile; Node pinned through `engines` so the build picks Node 22 (§4.8).
|
||||
- One "Project decisions" heading, in English, outside the ipal block; never inline AGENT.md.
|
||||
- Ship `eslint`/`prettier` (cleanteam's set) and a `typecheck` script — today only one site lints.
|
||||
- `adminMeta`, `agency`, `theme` and the cookie scanner are new; the starter makes them explicit choices.
|
||||
|
||||
---
|
||||
|
||||
## 2. The command
|
||||
|
||||
```bash
|
||||
pnpm dlx @intecion/ipal-kit@1.15.0 create <domain> [options] # from anywhere: creates ./<name>-web
|
||||
```
|
||||
|
||||
`pnpm dlx` runs a package's bin named after the package (`ipal-kit`) when it has several, so the plugin
|
||||
gets one new bin, `ipal-kit`, with subcommands — `create` now; `ipal-skills`, `ipal-doctor`, `ipal-tokens`
|
||||
stay as they are (§5.1). Always give the version: it pins the templates and therefore every dependency.
|
||||
|
||||
| Option | Default | What it does |
|
||||
|---|---|---|
|
||||
| `<domain>` | — (required) | production domain, e.g. `intecion.com` (no `www.`, no scheme) |
|
||||
| `--dir <path>` | `./<domain without dots>-web` | target folder; must not exist or must be empty |
|
||||
| `--answers <file.json>` | — | the architecture answers as JSON — for agents and CI; no prompts |
|
||||
| `--no-install` | install | skip `pnpm install` (and therefore the checks that need it) |
|
||||
| `--no-git` | git | skip `git init` and the first commit |
|
||||
| `--external [ext-a,ext-b]` | none | also install the vendored third-party skills (`ipal-skills --external`) |
|
||||
| `--dry-run` | off | print the file tree and the decisions, write nothing |
|
||||
|
||||
**Derived names** (from the domain, never asked). Database names come from the plugin's own
|
||||
`databaseNamesFor()` (`@intecion/ipal-kit/env`, merged on main in `0ed3898`) — one rule for the starter,
|
||||
`ipalEnvRules({ databaseName })` and `ipal-doctor`:
|
||||
|
||||
| Name | Rule | `intecion.com` | `architekt-imprez.pl` |
|
||||
|---|---|---|---|
|
||||
| production database | `databaseNamesFor(domain).prod` — dots removed, `www.` stripped | `intecioncom_prod` | `architekt-imprezpl_prod` |
|
||||
| development database | `databaseNamesFor(domain).dev` | `intecioncom_dev` | `architekt-imprezpl_dev` |
|
||||
| folder / repo / `package.json` name | `<domain without dots>-web` (the live sites' pattern) | `intecioncom-web` | `architekt-imprezpl-web` |
|
||||
| `NEXT_PUBLIC_SERVER_URL` (prod) | `https://<www.?><domain>` per the hosting answer | `https://intecion.com` | — |
|
||||
| MCP server name | `<domain without dots>-site` | `intecioncom-site` | — |
|
||||
|
||||
Hyphens stay, as in the plugin rule; MongoDB accepts them. No live site has a hyphenated domain.
|
||||
|
||||
### 2.1 Architecture questions — asked up front, written into `AGENTS.md`
|
||||
|
||||
The generator asks the nine topics from AGENT.md "Ask before you build" (the same list as `ipal-setup`
|
||||
stage 0), **all before it writes a single file**. There is no `--yes`: a missing answer stops the run
|
||||
with the list of open topics (AGENT.md: never guess an architecture answer). Each prompt shows the
|
||||
recommended choice; picking it is recorded as the owner's answer, not as "default".
|
||||
|
||||
| # | Topic | Prompt (choices) | Drives |
|
||||
|---|---|---|---|
|
||||
| 1 | Languages | locales (`pl,en`), default (`pl`), URLs: every language prefixed / default without prefix | `i18n.config.ts`; one language → no `[locale]` folder, `md/[[...slug]]` |
|
||||
| 2 | Styling | the tokens track's five: primary (+ secondary/accent); heading + body font (Google name or system); theme light / dark / both + default; radius sharp / soft / round; fluid or fluid-wide | `src/design/tokens.ts`, `DESIGN.md`, `next/font`, `<SiteProviders theme>` + `ThemeSwitcher`, Site settings → Theme seed |
|
||||
| 3 | Content | pages list (free text); content collections (none / blog / case studies / products / other) | "Site map" + "Project decisions"; collections are **not** generated — `ipal-collection` adds them |
|
||||
| 4 | Forms + e-mail | forms list; recipient; transport SMTP (panel) / Microsoft Graph | `mailAdapter()`; Graph → `emailGraph: true` in env rules + `GRAPH_*` in `.env.example`; the contact form in `src/seed/base` with the answered recipient |
|
||||
| 5 | Analytics + consent | tools (GA4, GTM, Meta, LinkedIn, TikTok, Clarity, none); Consent Mode advanced / basic; banner settings inline / modal / detailed; cookie scanner yes/no; browser crawl yes/no | CSP flags, `analytics={{ consentMode }}`, `<CookieBanner settings>`, `cookieScanner` (+ `crawl` → `cookieCrawl: true` + `IPAL_COOKIE_SCAN_*`) |
|
||||
| 6 | SEO / GEO | market (PL / AU / UK / …); local business yes/no (type); AI bots allow / block-training / disallow | `siteJsonLd` with `buildLocalBusinessJsonLd`; `robots.aiBots`; a block → `ipal-audit-skip: aibots` with the reason |
|
||||
| 7 | Data + media | media: R2 / local disk (Coolify volume). Database is always MongoDB (D12) — not asked | `src/db.ts` (`mongooseAdapter`); `buildR2Storage`; env rules `storage` |
|
||||
| 8 | Admin | 2FA on / off (+ reason); white-label yes/no; agency credit Intecion / other `{ name, url }` / none; panel link preview on/off | `twoFactor`, `whiteLabel`, `agency`, `adminMeta` |
|
||||
| 9 | Hosting | Coolify server + project name; canonical host apex / www; extra domains; who adds DNS (team default) | `NEXT_PUBLIC_SERVER_URL`, `DEPLOY.md` (domains, DNS table pre-filled) |
|
||||
| + | Agent tooling | external skills (none / pick); skills always in `.agents/skills` | `ipal-skills --external`, `tsconfig` exclude |
|
||||
|
||||
The answers file (`--answers`) has the same keys; the generator writes the final, complete answers to
|
||||
`.ipal/starter.json` in the site (no secrets) so `ipal-doctor` and a later upgrade can read them.
|
||||
|
||||
**`AGENTS.md` output** — AGENT.md §13 template, filled in, outside the `ipal-kit:start…end` block:
|
||||
|
||||
```markdown
|
||||
# AGENTS.md
|
||||
|
||||
**Project:** <site name> · intecion.com · market PL · industry <…>
|
||||
**Languages:** pl (default), en · **Media:** R2 · **Email:** Graph
|
||||
|
||||
## Rules
|
||||
(§13 text, unchanged)
|
||||
|
||||
## Site map
|
||||
- <pages from answer 3> — sections written later by ipal-site
|
||||
|
||||
## Project decisions
|
||||
- Languages: pl (default), en — every language prefixed (/pl/…, /en/…)
|
||||
- Styling: tokens from scratch — primary #0B5FFF, Inter / Inter, theme system + toggle
|
||||
- Content: pages Home, About, Services, Contact; collections none
|
||||
- Forms + e-mail: contact form → biuro@…; transport Microsoft Graph
|
||||
- Analytics/consent: GA4; Consent Mode advanced; banner detailed; cookie scanner on, crawl off
|
||||
- SEO/GEO: market PL; LocalBusiness (ProfessionalService); AI bots allow
|
||||
- Database + media: MongoDB (intecioncom_prod / intecioncom_dev); R2, media through the app
|
||||
- Admin: 2FA on; white-label on; agency credit Intecion.com; panel link preview on
|
||||
- Hosting: Coolify <server>/<project>; canonical https://intecion.com (www → apex); DNS by the team
|
||||
- Agent tooling: external skills none
|
||||
- Created with `ipal-kit create` 1.15.0 on 2026-11-02
|
||||
<!-- ipal-kit:start --> … written by ipal-skills … <!-- ipal-kit:end -->
|
||||
```
|
||||
|
||||
A "2FA off" or "AI bots blocked" answer also writes the matching `ipal-audit-skip:` line with the reason,
|
||||
so `ipal-audit` and `ipal-doctor` accept it.
|
||||
|
||||
### 2.2 What the command runs, in order
|
||||
|
||||
1. Validate the domain and the target folder; collect and validate all answers (stop on any gap).
|
||||
2. Render the template (§6) into the folder: files + conditional fragments, placeholders filled.
|
||||
3. Write the local `.env` (git-ignored): random `PAYLOAD_SECRET` (`crypto.randomBytes(48)`), the dev
|
||||
database URI with `<dbBase>_dev`, `NEXT_PUBLIC_SERVER_URL=http://localhost:3000`. Nothing else.
|
||||
4. `pnpm install` against the lockfile shipped for this database: every locked entry kept, only the plugin
|
||||
and its own dependencies resolved (§5.4); the complete lockfile is committed in step 8.
|
||||
5. `pnpm exec ipal-skills [--external …]` — skills + the `AGENTS.md`/`CLAUDE.md` pointer;
|
||||
`pnpm exec ipal-tokens` — generates `tokens.css` and the contrast report (AA failure → back to question 2).
|
||||
6. `pnpm generate:types && pnpm generate:importmap`.
|
||||
7. `pnpm typecheck && pnpm lint` and `pnpm exec ipal-doctor` → must be zero findings (error, warning and
|
||||
info), else the run fails and prints them — the starter's contract with the doctor track. Every
|
||||
deliberate difference is written to `ipal-doctor.json` as a silenced rule **with the reason**, never
|
||||
hidden: CSP `report-only` on day 1 ("rollout: enforce after clean reports"), and each owner answer that
|
||||
turns a recommended module off (2FA, cookie scanner, adminMeta, agency) with the owner's reason — the
|
||||
same reason as the `ipal-audit-skip:` line.
|
||||
8. `git init -b main`, secret check of the index (§4.9), first commit
|
||||
`chore: create site with ipal-kit create <version>`. No remote is added.
|
||||
9. Print the report: what is wired, next steps (dev database, first user + 2FA, panel steps from
|
||||
`ipal-setup` §11), the Coolify env list and the DNS records for this domain.
|
||||
|
||||
Steps 4–7 need the network only for the pinned registry install; `--no-install` stops after step 3 and
|
||||
prints the remaining commands.
|
||||
|
||||
---
|
||||
|
||||
## 3. The generated tree
|
||||
|
||||
Shown for the default answers (pl + en, MongoDB, R2, 2FA on, cookie scanner on, theme with toggle).
|
||||
`†` = present only for some answers (§4 says which).
|
||||
|
||||
```
|
||||
intecioncom-web/
|
||||
├── .agents/skills/ipal-*/ # by ipal-skills — committed
|
||||
├── .ipal/starter.json # the answers + starter/plugin versions (no secrets)
|
||||
├── ipal-doctor.json # { domain, launched: false } + silenced rules with the owner's reason
|
||||
├── .github/workflows/ci.yml † # or .gitea/workflows/ci.yml — §8 D7
|
||||
├── .env # local only, git-ignored, never committed
|
||||
├── .env.example # from ipalEnvRules (§4.4) — committed, no values
|
||||
├── .gitignore
|
||||
├── .npmrc # @intecion registry + legacy-peer-deps (no token)
|
||||
├── .nvmrc # 22
|
||||
├── .prettierrc.json
|
||||
├── AGENTS.md # §2.1 output + ipal-kit pointer block
|
||||
├── CLAUDE.md # @AGENTS.md (by ipal-skills)
|
||||
├── DESIGN.md # 9 sections, values from answer 2 (tokens track)
|
||||
├── eslint.config.mjs
|
||||
├── next.config.ts # withPayload(withSecurityConfig(…)), CSP report-only
|
||||
├── package.json # exact versions, scripts (§4.1), pnpm.overrides
|
||||
├── pnpm-lock.yaml # the shipped lockfile for this variant
|
||||
├── postcss.config.mjs
|
||||
├── tsconfig.json # exclude node_modules + the skills folder
|
||||
├── docs/DEPLOY.md # Coolify + DNS for this domain (§4.8)
|
||||
└── src/
|
||||
├── app/
|
||||
│ ├── (frontend)/
|
||||
│ │ ├── styles.css # imports only — identical on every site (tokens track)
|
||||
│ │ └── [locale]/ # † single language: no [locale]
|
||||
│ │ ├── layout.tsx # SiteProviders, CookieBanner, Header/Footer, fonts
|
||||
│ │ ├── actions.ts # sendForm = createSubmitAction(…)
|
||||
│ │ ├── not-found.tsx · notFoundView.ts
|
||||
│ │ └── [[...slug]]/page.tsx
|
||||
│ ├── (payload)/… # Payload admin (generated, importMap.js)
|
||||
│ ├── api/{health,mcp,csp-report}/route.ts
|
||||
│ ├── llms.txt/ · llms-full.txt/ · indexnow-key.txt/ · sitemap.xml/ # route.ts each
|
||||
│ ├── md/[locale]/[[...slug]]/route.ts
|
||||
│ ├── manifest.ts · robots.ts
|
||||
├── blocks/registry.ts # createBlockRegistry(content) — blocks + UI primitives come from the plugin
|
||||
├── collections/{Pages,Media}.ts # Pages.layout = libraryBlocks({ … }) from @intecion/ipal-kit/blocks
|
||||
├── components/
|
||||
│ ├── forms/formClasses.ts
|
||||
│ └── layout/{Header,Footer}.tsx # ui/ only for a primitive the project overrides (ui: { Media })
|
||||
├── globals/{Header,Footer,Company}.ts
|
||||
├── db.ts # the database adapter (MongoDB)
|
||||
├── seed/ # seed.ts (`--only page:…,form:…,global:…`, §4.7) + base/
|
||||
├── lib/content.ts # createContentHelpers — the only data access
|
||||
├── design/tokens.ts · tokens.css # brand tokens; tokens.css generated by `ipal-tokens`
|
||||
├── content.config.ts · i18n.config.ts
|
||||
├── env.rules.ts # the ONE ipalEnvRules call (instrumentation + env:check + .env.example)
|
||||
├── instrumentation.ts
|
||||
├── payload.config.ts
|
||||
└── proxy.ts
|
||||
```
|
||||
|
||||
Not generated: any content collection (blog etc. — `ipal-collection`), real content (ipal-site phase 6),
|
||||
`middleware.ts`, anything in `public/` that the plugin serves as a route.
|
||||
|
||||
---
|
||||
|
||||
## 4. What each part does
|
||||
|
||||
### 4.1 `package.json`
|
||||
|
||||
- `name` = folder name, `private: true`, `type: module`, `engines.node: ">=22 <23"`,
|
||||
`packageManager: "pnpm@<exact>"` (corepack, pinned).
|
||||
- **Exact versions** for everything (no `^`): `@intecion/ipal-kit`, `payload` and every `@payloadcms/*`
|
||||
at the same version, `next` + `eslint-config-next` at the same 16.4.x (≥ 16.4.1), `sharp` ≥ 0.35.5,
|
||||
`react`/`react-dom`, `@clocklimited/payload-2fa` (only with 2FA), `@payloadcms/storage-s3` (only with R2),
|
||||
the db adapter for the chosen database. `pnpm.overrides`: every `@payloadcms/*` pinned to the payload
|
||||
version + the advisory overrides from AGENT.md §4 item 12. The set comes from the release's
|
||||
shipped lockfile (§5.4) — the starter never resolves "latest".
|
||||
- Scripts (one name per job, same in every site):
|
||||
|
||||
| Script | Command |
|
||||
|---|---|
|
||||
| `dev` | `next dev` |
|
||||
| `build` | `cross-env NODE_OPTIONS="--max-old-space-size=3072" next build --webpack` |
|
||||
| `start` | `next start` |
|
||||
| `typecheck` | `tsc --noEmit` |
|
||||
| `lint` / `format` | `eslint .` / `prettier --write .` |
|
||||
| `payload` | `payload` |
|
||||
| `generate:types` / `generate:importmap` | `payload generate:types` / `payload generate:importmap` |
|
||||
| `seed` | `payload run src/seed/seed.ts` (`SEED_ONLY=… pnpm seed`) |
|
||||
| `env:check` | `payload run src/env.check.ts` (asserts `envRules` and prints the result) |
|
||||
| `ipal:skills` | `ipal-skills` (+ the chosen `--dest`) |
|
||||
| `doctor` | `ipal-doctor` |
|
||||
|
||||
### 4.2 `payload.config.ts`
|
||||
|
||||
`ipal-setup` stage 3 with the answers filled in: `ipalKit({ i18n, access, pages, content, seo, forms,
|
||||
twoFactor: { issuer: '<site name>', plugin: payloadTotp } | false, whiteLabel, agency, adminMeta,
|
||||
cookieScanner, indexNow: true, consentLog: true, revalidatePath })`, `email: mailAdapter()`,
|
||||
`buildR2Storage(['media'], { s3Storage })` (always wired — R2 works by itself when the keys are there).
|
||||
Only options that differ from the plugin default are written (`adminMeta` on and the Intecion `agency`
|
||||
are defaults, so they appear only when turned off or changed) — the file stays short and the plugin's
|
||||
defaults keep flowing in on upgrades.
|
||||
|
||||
Database: `mongooseAdapter({ url: process.env.DATABASE_URI })` in `src/db.ts`. The database name lives **only** in
|
||||
`DATABASE_URI` (`…/intecioncom_dev` locally, `…/intecioncom_prod` in Coolify); no name in code.
|
||||
|
||||
### 4.3 `next.config.ts` — security
|
||||
|
||||
Exactly `ipal-setup` stage 7: `withPayload(withSecurityConfig({...}))`, `buildSecurityHeaders({ hsts:
|
||||
production, csp: { mode: 'report-only', reportUri: '/api/csp-report', r2Url, turnstile: true, …flags } })`,
|
||||
`buildAdminCspHeaders(csp)` on `/admin/:path*`, `buildUploadSecurityHeaders()`, `buildImagesConfig()`,
|
||||
`htmlLimitedBots`. The CSP flags come from answer 5 (`analytics`, `metaPixel`, `linkedIn`, `tiktok`,
|
||||
`clarity`). `src/app/api/csp-report/route.ts` = `createCspReportRoute()`. `DEPLOY.md` has the step
|
||||
"after a week of clean `[csp]` logs switch to `mode: 'enforce'`".
|
||||
|
||||
### 4.4 Environment — one rule set, three uses
|
||||
|
||||
`src/env.rules.ts` exports `envRules = ipalEnvRules({ storage, ipHeader: true, emailGraph, cookieCrawl,
|
||||
databaseName: { domain: '<domain>' } })` (the domain is given, because `NEXT_PUBLIC_SERVER_URL` is localhost in dev)
|
||||
(with the `R2_PUBLIC_URL` optional mapping from `ipal-setup`). It is used by:
|
||||
1. `src/instrumentation.ts` → `assertEnv(envRules)` (nodejs runtime only, import from `/env`);
|
||||
2. `pnpm env:check` → the same check on demand (Coolify Terminal, CI);
|
||||
3. the generator → `.env.example` is rendered **from the same rules** (name, description, required in
|
||||
production) at template build time, so the example and the validation can never drift.
|
||||
|
||||
`.env.example` also lists the non-validated variables the plugin reads (`IPAL_NOINDEX`, `INDEXNOW_KEY`,
|
||||
Turnstile fallback) with a comment, and the database line as
|
||||
`DATABASE_URI=mongodb://localhost:27017/intecioncom_dev`.
|
||||
|
||||
### 4.5 Frontend wiring
|
||||
|
||||
`proxy.ts`, `lib/content.ts`, layout, catch-all, 404, all SEO/GEO routes: `ipal-setup` stages 6–8 1:1,
|
||||
answers filled in (`markdown: true`, `mcp.serverName`, `siteJsonLd` for a local business, `robots.aiBots`).
|
||||
Layout: `<SiteProviders shell logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice
|
||||
settings="<answer>" />} analytics={{ consentMode }} theme>` + Header/Footer + `<MediaPreconnect/>`.
|
||||
Theme answer "light only" → no `theme` prop and no switcher.
|
||||
|
||||
### 4.6 2FA, cookie scanner, white-label
|
||||
|
||||
- 2FA on (recommended): `twoFactor` + `@clocklimited/payload-2fa` + import map; check in the report:
|
||||
a new admin lands on `/admin/setup-totp?back=%2Fadmin`. Off: `twoFactor: false`, the dependency is
|
||||
left out, `ipal-audit-skip: twofactor — <reason>` in "Project decisions".
|
||||
- Cookie scanner on: `cookieScanner: true` (+ `crawl: true` → env rules `cookieCrawl` and the two env
|
||||
variables); the report lists the editor steps (*Scan cookies* → *Approve and add*) for after launch.
|
||||
- White-label + agency + adminMeta as answered.
|
||||
|
||||
### 4.7 Seeds — named records only
|
||||
|
||||
The plugin's `createSeeder` already has the record list and the full-seed guard (D6 done, main `0ed3898`):
|
||||
|
||||
```bash
|
||||
SEED_ONLY="pages:kontakt,forms:Contact form,global:header" pnpm seed # after launch: named records only
|
||||
SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm seed # plan only
|
||||
pnpm seed # before launch, local _dev database
|
||||
```
|
||||
|
||||
- `src/seed/base/*.ts` hold the reference site's `seed:base` set (system pages, globals, contact form,
|
||||
banner and notification texts); `seed:demo` is dropped. `src/seed/seed.ts` passes them to `createSeeder`
|
||||
(create-only, idempotent, every locale, `[TO FILL: …]`, no users/media/secrets).
|
||||
- A run without `SEED_ONLY` against production or a non-local database is refused by the plugin unless
|
||||
`IPAL_SEED_ALLOW_FULL=1` (the owner's explicit OK). The starter writes no guard of its own.
|
||||
- `docs/DEPLOY.md` has the Coolify Terminal steps: dry run with the list → **Backup now** → the real run.
|
||||
|
||||
### 4.8 Coolify — the team's existing path, written into `docs/DEPLOY.md`
|
||||
|
||||
No Dockerfile, no compose file, no new image model — the same process as the five live sites that deploy
|
||||
without one (§1.1):
|
||||
|
||||
1. **Locally:** `pnpm build && pnpm start`, the checks (`ipal-doctor`, `ipal-seo-check`), commit, push.
|
||||
2. **Coolify app** from the Git repo, Coolify's default build pack (Nixpacks). It reads `pnpm-lock.yaml` and
|
||||
`packageManager` (pnpm, pinned) and `engines.node` (`>=22 <23` → Node 22). Commands in the app's build
|
||||
settings: install `pnpm install --frozen-lockfile`, build `pnpm generate:types && pnpm build`, start
|
||||
`pnpm start`. Port 3000, no host port mapping, health check `GET /api/health`.
|
||||
3. **MongoDB** is a separate Coolify database resource (its own container) in the same project, on the same
|
||||
Docker network as the app. `DATABASE_URI` = the resource's **internal** URL with the database name
|
||||
added: `mongodb://<user>:<password>@<internal-host>:27017/<dbBase>_prod?authSource=admin`. Host and
|
||||
credentials stay in Coolify's env only — never in `.env.example`, `AGENTS.md` or `DEPLOY.md` (two live
|
||||
sites leak one, §1.3).
|
||||
4. **Seeds run in the app container:** Coolify → the app → **Terminal**. The build pack image is the whole
|
||||
repo with `node_modules`, so `src/seed/`, the Payload CLI and pnpm are there, and the container has the
|
||||
runtime env (production `DATABASE_URI`, `NODE_ENV=production`):
|
||||
```bash
|
||||
SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm seed # 1. plan — must list only the named records
|
||||
# 2. Coolify → MongoDB resource → Backups → Backup now
|
||||
SEED_ONLY="pages:kontakt" pnpm seed # 3. the real run
|
||||
```
|
||||
Without `SEED_ONLY` the plugin refuses the run on production (`createSeeder` guard, D6). The release
|
||||
gate (§5.3) runs this exact command in a container built the same way, so it is proven to work.
|
||||
|
||||
`docs/DEPLOY.md` (generated, domain filled in) holds these steps plus: domains
|
||||
`https://intecion.com,https://www.intecion.com` with the redirect to the canonical host, the env list with
|
||||
build-time / runtime flags (deployment.md §4.2; `DATABASE_URI` and `PAYLOAD_SECRET` also at build time only
|
||||
when pages prerender from the database, §3a3), scheduled MongoDB backups to S3/R2, R2 or a persistent volume
|
||||
for media, the DNS records from deployment.md §6 with this domain's names, and rollback notes.
|
||||
|
||||
### 4.9 Git and secrets
|
||||
|
||||
- `.gitignore`: `.env`, `.env.*` except `.env.example`, `node_modules`, `.next`, `media/`, `*.tsbuildinfo`.
|
||||
- Before the first commit the generator scans the index: no `.env`, no line matching
|
||||
`(SECRET|TOKEN|PASSWORD|KEY)=\S` outside `.env.example`, no private-key blocks — any hit aborts.
|
||||
- `.npmrc` holds only the registry line; the Gitea token stays in `~/.npmrc` (PROGRAMISTA §1).
|
||||
- One commit on `main`; no remote, no push — the developer adds the Gitea remote.
|
||||
|
||||
---
|
||||
|
||||
## 5. Where it lives and how it ships
|
||||
|
||||
### 5.1 A command of `@intecion/ipal-kit` (owner's choice)
|
||||
|
||||
- **Bin:** `bin/ipal-kit.mjs`, a small dispatcher: `ipal-kit create …` → `bin/create/*.mjs`. Node built-ins
|
||||
only (`node:fs`, `node:zlib`, `node:readline/promises`, `node:crypto`, `node:child_process`), no imports
|
||||
from `dist/` except the plain `databaseNamesFor` helper — so it runs without Payload or Next loaded.
|
||||
- **Why a dispatcher named `ipal-kit`:** with several bins in one package `pnpm dlx @intecion/ipal-kit …`
|
||||
runs the bin named after the package; any other name needs the longer
|
||||
`pnpm --package=@intecion/[email protected] dlx ipal-create …`. The existing bins stay for compatibility; the
|
||||
dispatcher can later also forward `skills`, `doctor`, `tokens`.
|
||||
- **Inside a project** (an agent that already has the plugin installed): `pnpm exec ipal-kit create <domain>
|
||||
--dir ../<name>-web` works the same; it refuses to write into the current project.
|
||||
- **Peer dependencies under `dlx`:** pnpm installs the plugin's peers (Payload, Next, React…) into its dlx
|
||||
cache by default. They land in the shared pnpm store, which the new site's install then reuses (hard
|
||||
links), so the second download is small; the generator itself never loads them. To be measured in build
|
||||
step 1; if it is slow, the docs add `--config.auto-install-peers=false` to the command (to be verified on
|
||||
pnpm 10).
|
||||
|
||||
### 5.2 Size cost in the published tarball
|
||||
|
||||
Measured inputs: the plugin today is ~9.3 MB unpacked (`dist` 7.2 MB, `docs` 2.1 MB). A live site's
|
||||
`pnpm-lock.yaml` is ~195 KB (~61 KB gzipped); the reference site's skeleton (demo dropped) is estimated at
|
||||
0.3–0.5 MB of source text.
|
||||
|
||||
| Shipped file | Unpacked size (estimate) |
|
||||
|---|---|
|
||||
| `dist/starter/template.json.gz` — every kept file as `{ path: content }`, gzip -9 | ~80–120 KB |
|
||||
| `dist/starter/lock.yaml.gz` (MongoDB only) | ~60 KB |
|
||||
| `bin/ipal-kit.mjs` + `bin/create/*` | ~30 KB |
|
||||
| **Total** | **~0.2 MB, about 2 % of the package** |
|
||||
|
||||
Stored gzipped, so every project that installs the plugin carries ~0.25 MB more on disk; the download grows
|
||||
by about the same (the npm tarball is gzipped already). The generator unpacks with `node:zlib` — no tar
|
||||
library. Exact numbers go into the build report and the CHANGELOG entry.
|
||||
|
||||
### 5.3 Release
|
||||
|
||||
One package, one version, one release step. `prepublishOnly` gains `build:starter`: read
|
||||
`reference/starter.manifest.json`, bundle the kept files, prepare the lockfile(s) (§5.4), then **test the
|
||||
packed tarball**: `pnpm pack` → `pnpm dlx ./ipal-kit-X.Y.Z.tgz create release-check.example` → install →
|
||||
typecheck → `next build` → `ipal-doctor --strict` → build the site the way Coolify does (the `nixpacks` CLI,
|
||||
version pinned in CI) and, in that container against a throw-away MongoDB container on the same Docker
|
||||
network, run `SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm seed` and the real run — this proves the
|
||||
§4.8 Terminal command works in the deployed image (pnpm, the Payload CLI and `src/seed/` present).
|
||||
Failure blocks the publish. `reference/` is not in
|
||||
`files`; only the bundle is. The owner approves the publish as for every release.
|
||||
|
||||
### 5.4 Nothing unpinned — the lockfile
|
||||
|
||||
- The generator never runs `create-payload-app`, `git clone`, `curl` or `…@latest`; templates come from
|
||||
the tarball, not from the Git tag.
|
||||
- **The shipped lockfile** is the reference site's resolved tree, with the plugin rewritten from `link:..`
|
||||
to the exact version `X.Y.Z`. One catch: the plugin's own lockfile entry needs the integrity hash of
|
||||
the tarball being built, which does not exist yet. So the shipped lockfile holds **every package except
|
||||
`@intecion/ipal-kit` itself and its four direct dependencies** (`lucide-react`, `nodemailer`,
|
||||
`server-only`, `slugify`). The generator runs `pnpm install` (not frozen): pnpm keeps every locked entry
|
||||
as it is and resolves only the plugin (exact `X.Y.Z` in `package.json`) and those four. The resulting
|
||||
complete lockfile is committed in the first commit; from then on `--frozen-lockfile` (Coolify's install command, CI).
|
||||
- To close the last gap, D15: pin the plugin's four dependencies to exact versions in its own
|
||||
`package.json`. Then two sites created from the same release get identical trees.
|
||||
- External skills come only from `ipal-skills --external` (vendored, hash-checked).
|
||||
- The only network access is the install from the team registry + npm.
|
||||
|
||||
---
|
||||
|
||||
## 6. Staying in sync with the plugin
|
||||
|
||||
**Templates are generated from the reference site, not maintained by hand.**
|
||||
|
||||
```
|
||||
reference site (runnable, all features on, CI-green with ipal-kit X.Y.Z)
|
||||
│ pnpm build:starter → dist/starter/*.gz (prepublishOnly)
|
||||
▼
|
||||
@intecion/ipal-kit tarball ← kept files + lockfile, placeholders and variant markers intact
|
||||
│ pnpm dlx @intecion/ipal-kit@X.Y.Z create <domain> (developer's machine)
|
||||
▼
|
||||
new site ── ipal-doctor: 0 findings
|
||||
```
|
||||
|
||||
- **"Project decisions"** in the reference `AGENTS.md` sit between `<!-- starter:decisions -->` markers;
|
||||
the starter replaces that block with the owner's answers.
|
||||
- **One manifest, owned by the reference site:** `reference/starter.manifest.json` (the reference
|
||||
session's proposal) marks every path `keep`, `drop` (demo) or `template`, and lists whole-file variants
|
||||
(`{ "if": "theme" }`). The starter keeps no template files and no mapping of its own.
|
||||
- **Placeholders.** The reference site uses one made-up company with unique fake values
|
||||
(`example-studio.pl`, `examplestudiopl_dev`); the manifest maps them to `{{domain}}`, `{{dbBase}}`,
|
||||
`{{projectName}}`, `{{siteName}}`, `{{locales}}`, `{{issuer}}`, `{{mcpName}}`, `{{serverUrl}}`. The
|
||||
build fails when a mapped value is missing or an unmapped fake value shows up in a new file.
|
||||
- **Variants inside a file** are comments that keep the reference site runnable:
|
||||
`// @starter:if theme` … `// @starter:endif` (`{/* @starter:if theme */}` in TSX). Flags: `theme`,
|
||||
`cookieScanner`, `crawl`, `graph`, `localBusiness`, `twoFactor`, `singleLocale`, one per analytics/CSP
|
||||
tool. The reference site runs "everything on"; the CI matrix proves the other combinations.
|
||||
- **What is dropped:** `src/seed/demo/`, `seed-media/`, the Blocks showcase page (the `/design` styleguide is the reference's D5), `.env`, generated files
|
||||
(`payload-types.ts`, `importMap.js` — regenerated on step 6), the reference site's own CI and notes.
|
||||
- **Release gate (CI in the ipal-kit repo):** build templates → generate the matrix (pl+en / pl only ×
|
||||
the toggles that change code) → `pnpm install` (§5.4) → typecheck, lint,
|
||||
`next build` (database service container), `ipal-doctor` = 0, `ipal-audit` quick = 0. Any failure
|
||||
blocks the starter release; the plugin can still ship.
|
||||
- **Agent guide:** a new option or wiring step lands in the reference site, then AGENT.md/skills in the
|
||||
same change (CLAUDE.md rule); the starter picks it up with no template edit. `ipal-doctor` checks the
|
||||
same rules, so "starter output" = "what the doctor expects" by construction.
|
||||
- **Existing sites** are not touched by the starter. They converge through `ipal-upgrade` + `ipal-doctor`
|
||||
findings; `.ipal/starter.json` lets the doctor tell starter-made sites from older ones.
|
||||
|
||||
Order of work: the reference site comes first; the starter's generator can be written and unit-tested
|
||||
in parallel against a small fixture tree and switches to `reference/` once it is green. No stop-gap
|
||||
templates are maintained by hand.
|
||||
|
||||
---
|
||||
|
||||
## 7. Fit with the sibling tracks
|
||||
|
||||
| Track | What the starter takes | Status (notes folder, 2026-10-29) |
|
||||
|---|---|---|
|
||||
| reference site (`reference/` in the plugin repo, not shipped) | the whole template source via `starter.manifest.json`; `seed:base` kept, `seed:demo` dropped; MongoDB only; no Dockerfile (owner, D9) | **aligned** — `starter-vs-reference.md` |
|
||||
| design tokens | `DESIGN.md` (9 fixed sections), `src/design/tokens.ts` via `defineTokens()` from `@intecion/ipal-kit/tokens` (light entry, no Payload import) (+ `tokens.css` generated by `ipal-tokens`; fallback: hand-written `tokens.css`, same path — tokens D1), the fixed `styles.css` imports, `next/font` with `--font-family-body` / `--font-family-heading` (not `--font-body`: a `var()` cycle with Tailwind's `font-body` key); questions: primary (+ secondary/accent), heading/body font, theme light/dark/both + default, radius sharp/soft/round, fluid vs fluid-wide; `ipal-tokens` contrast report into `DESIGN.md` (AA failure → ask again) | **aligned** with `design-tokens-wiring.md`; built on `claude/design-tokens-build` (`9511b12`); answer 2 in §2.1 expands to these five questions |
|
||||
| block library | imported, not copied: `libraryBlocks({ … })` in `Pages.layout` (`/blocks`), `registry.ts` = `createBlockRegistry(content)` (`/blocks/rsc`, also the five UI primitives — the project writes one only to override it), page templates from `/templates` for `seed/base`; default set hero, textMedia, featureGrid, cta, richText, faq, contact, gallery; after a block-list change `generate:types` + `generate:importmap` | **aligned** with `block-library-for-starter.md` |
|
||||
| ipal-doctor | step 7 of the run and the release gate: zero findings incl. info; `ipal-doctor.json` `{ domain, launched: false, rules: { <rule>: { off, reason } } }` | **aligned** — `ipal-doctor-for-starter.md` (doctor commit 7bdc5d6) |
|
||||
|
||||
**Conflicts between the drafts — all settled with the sibling sessions (2026-10-29):**
|
||||
1. **`src/` top level:** the doctor's exported allow list now includes `seed/`, `design/`, `db.ts`,
|
||||
`env.rules.ts`, `content.config.ts`; a project extends it with `ipal-doctor.json` `"layout": { "allow": […] }`.
|
||||
2. **`components/ui/`:** required only without `createBlockRegistry` (block library agreed; the doctor warns
|
||||
when a project primitive in `ui/` is not passed through `createBlockRegistry({ ui })`).
|
||||
3. **Optional modules:** silenced per rule with a reason — `"rules": { "2fa": { "off": true, "reason": "…" } }`;
|
||||
silenced findings don't fail `--strict`; an entry without a reason is ignored and reported. The starter
|
||||
writes these entries from the owner's answers (and one for CSP `report-only`).
|
||||
4. **Plugin version:** "not the latest" is a warning naming the newer version, an error only two or more
|
||||
minors behind (doctor's D2, owner to confirm) — a site made from an older starter release still passes.
|
||||
|
||||
All four depend on owner approvals of their own proposals; the starter follows whatever they settle, because
|
||||
it only copies the reference site.
|
||||
|
||||
---
|
||||
|
||||
## 8. Decisions for the owner
|
||||
|
||||
All decisions are settled (owner, 2026-10-29: "Accept all", with D9 and D12 changed as below).
|
||||
|
||||
| # | Decision | Status |
|
||||
|---|---|---|
|
||||
| D1 | A command of `@intecion/ipal-kit`: `pnpm dlx @intecion/[email protected] create <domain>` (§5.1) | decided |
|
||||
| D2 | The reference site is the only hand-edited tree; the starter is generated from it through `reference/starter.manifest.json` | accepted |
|
||||
| D3 | Exact dependency versions in new sites (no `^`, `packageManager`, `engines`), upgrades via `ipal-upgrade` | accepted |
|
||||
| D4 | Database names from the plugin's `databaseNamesFor` (hyphens kept) | settled |
|
||||
| D5 | `@payloadcms/storage-s3` and `@clocklimited/payload-2fa` always installed (one lockfile) | accepted |
|
||||
| D6 | `createSeeder` record list + full-seed guard | done — main `0ed3898` |
|
||||
| D7 | Gitea Actions CI in new sites only (typecheck, lint, build, `ipal-doctor`); client sites untouched | accepted |
|
||||
| D8 | Skills in `.agents/skills` | accepted |
|
||||
| D9 | **No Dockerfile.** Build and check locally; Coolify builds from the repo with its default build pack; MongoDB as its own Coolify resource on the same Docker network; seeds in the app container's Terminal (§4.8) | decided by the owner |
|
||||
| D10 | Single-language sites in v1 | accepted |
|
||||
| D11 | Node 22 pinned in `.nvmrc` and `engines`; pnpm pinned in `packageManager` | accepted |
|
||||
| D12 | **MongoDB only** in v1 — no `--db` option, no second lockfile, no Postgres CI job; Postgres stays a later, one-file addition (`src/db.ts`) | decided by the owner |
|
||||
| D13 | The §1.3 live-site problems: information only — no fix sessions, no edits to client sites | decided by the owner |
|
||||
| D14 | The four §7 conflicts as settled with ipal-doctor and the block library | accepted |
|
||||
| D15 | Pin the plugin's four runtime dependencies to exact versions | accepted |
|
||||
| D16 | One `ipal-kit` dispatcher bin (`create` now; later `skills`, `doctor`, `tokens`) | accepted |
|
||||
|
||||
---
|
||||
|
||||
## 9. Build plan (after approval)
|
||||
|
||||
1. `bin/ipal-kit.mjs` dispatcher + `create`: CLI, prompts, answers schema, renderer, secret check,
|
||||
report — unit-tested against a small fixture tree; measure the `dlx` peer cost (§5.1).
|
||||
2. `build:starter`: bundle from `reference/starter.manifest.json`, lockfile preparation (§5.4), the
|
||||
packed-tarball check in `prepublishOnly`; the matrix CI with `ipal-doctor --strict` once the reference
|
||||
site and the doctor are green.
|
||||
3. Docs and skills in the same change (CLAUDE.md rule): AGENT.md "Ask before you build" + §13/§14,
|
||||
`ipal-setup` stage 1 ("new site → `ipal-kit create`; existing site → the manual stages"), `ipal-reference`
|
||||
(the bin and its options), PROGRAMISTA §2, deployment.md → `docs/DEPLOY.md`, CHANGELOG with the size cost.
|
||||
4. Release with the next plugin version; try it on one real new site before announcing.
|
||||
@@ -0,0 +1,203 @@
|
||||
# project starter — `ipal-kit create`
|
||||
|
||||
One command creates a new Payload 3 + Next 16 client site that already follows every team convention, so
|
||||
every project starts identical. The site is generated from the **reference site** (`reference/` in the plugin
|
||||
repo, not shipped as a folder): the same files, with the made-up company's values replaced by the owner's
|
||||
answers and its demo content left out.
|
||||
|
||||
```bash
|
||||
pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@1.15.0 create intecion.com
|
||||
```
|
||||
|
||||
- Always give the version: it pins the templates and therefore every dependency of the new site.
|
||||
- Run it from the folder that will hold the project, with the `@intecion` registry line in `~/.npmrc`
|
||||
(README "Installation") — there is no project `.npmrc` yet.
|
||||
- `--config.auto-install-peers=false` keeps `dlx` to the plugin itself: 7 packages, ~44 MB, ~1 s with a warm
|
||||
store. Without it pnpm also installs the plugin's peers (Payload, Next, React — 356 packages, ~750 MB in the dlx
|
||||
cache) that the generator never loads.
|
||||
- An agent that already has the plugin installed: `pnpm exec ipal-kit create <domain> --dir ../<name>-web`. The
|
||||
command refuses to write into the current project.
|
||||
|
||||
## What it asks — and where the answers go
|
||||
|
||||
The architecture questions of AGENT.md "Ask before you build" (the same list as `ipal-setup` stage 0), all before
|
||||
a single file is written. Enter takes the recommendation shown in brackets — an explicit choice, recorded as the
|
||||
owner's answer. There is no `--yes`: a missing answer stops the run with the list of open topics.
|
||||
|
||||
| Topic | Asked | Goes to |
|
||||
|---|---|---|
|
||||
| Site name, market, industry | name (also the 2FA issuer) | `AGENTS.md` header, Site settings and Company (seed), `twoFactor.issuer` |
|
||||
| Languages | locales besides `pl` (default) and `en` | `src/i18n.config.ts` (every language with a URL prefix) |
|
||||
| Styling | primary (+ secondary, accent), body and heading font, theme light / dark / both + default, radius sharp / soft / round, fluid standard / wide | `src/design/tokens.ts`, `DESIGN.md`, the next/font calls in the root layout, Site settings → Theme (seed) |
|
||||
| Pages and content | the site map; collections `posts` / `caseStudies` | `AGENTS.md` → Site map; the collection files, `content.config.ts`, the entry list block, the blog archive page |
|
||||
| Forms | forms, the inbox that receives them, SMTP or Microsoft Graph | Company → E-mail (seed), the seeded forms, `ipalEnvRules({ emailGraph })` + `GRAPH_*` |
|
||||
| Analytics and consent | tools, Consent Mode, the settings window, cookie scanner, browser crawl | CSP flags in `next.config.ts`, `SiteProviders analytics` / `banner`, `cookieScanner`, `IPAL_COOKIE_SCAN_*` |
|
||||
| SEO / GEO | local business (schema.org type), AI crawlers | `siteJsonLd` with `buildLocalBusinessJsonLd`, `robots.aiBots` |
|
||||
| Media | R2 or local disk | `ipalEnvRules({ storage })`, `docs/DEPLOY.md` (Persistent Storage without R2) |
|
||||
| Admin | 2FA, white-label, agency credit, panel link preview | `twoFactor`, `whiteLabel`, `agency`, `adminMeta` |
|
||||
| Hosting | canonical host apex / www, Coolify server, who adds DNS | `NEXT_PUBLIC_SERVER_URL`, `docs/DEPLOY.md` |
|
||||
| Agent tooling | external skills | `ipal-skills --external` |
|
||||
|
||||
Every answer is written into `AGENTS.md` → **Project decisions** (one line per topic) and the full set into
|
||||
`.ipal/starter.json`. A module the owner turns off needs the owner's reason, which goes into
|
||||
`ipal-audit-skip:` and `ipal-doctor.json` (`"rules": { "2fa": { "off": true, "reason": "…" } }`).
|
||||
|
||||
**Limits of this version** (the generator refuses, the manual `ipal-setup` path covers them): the default
|
||||
language must be `pl` and `en` must be one of the locales (the base seed is Polish + English, with Polish
|
||||
default-locale slugs); every language gets a URL prefix; MongoDB only.
|
||||
|
||||
For agents and CI, the same answers as JSON (shape: `StarterAnswers`, `@intecion/ipal-kit/starter`):
|
||||
|
||||
```bash
|
||||
pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"siteName": "Intecion", "market": "PL", "industry": "software house",
|
||||
"languages": { "default": "pl", "locales": [{ "code": "pl", "label": "Polski" }, { "code": "en", "label": "English" }] },
|
||||
"styling": { "primary": "oklch(0.5 0.17 250)", "fontBody": "Inter", "fontHeading": "Inter", "theme": "both", "defaultTheme": "system", "radius": "soft", "fluid": "wide" },
|
||||
"content": { "pages": ["Home", "About", "Services", "Contact"], "collections": ["posts"] },
|
||||
"forms": { "list": ["Contact form"], "recipient": "biuro@intecion.com", "transport": "smtp" },
|
||||
"consent": { "tools": ["ga4"], "consentMode": "advanced", "banner": "detailed", "cookieScanner": true, "crawl": true },
|
||||
"seo": { "aiBots": "allow", "localBusiness": { "type": "ProfessionalService" } },
|
||||
"media": "r2",
|
||||
"admin": { "twoFactor": true, "whiteLabel": true, "agency": "intecion", "adminMeta": true },
|
||||
"hosting": { "canonical": "apex", "coolify": "coolify-1 / intecion", "dns": "the team" },
|
||||
"tooling": { "external": [] }
|
||||
}
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Option | Default | What it does |
|
||||
|---|---|---|
|
||||
| `<domain>` | — (required) | the production domain; `https://`, `www.` and a path are stripped, IDN → punycode |
|
||||
| `--dir <path>` | `./<domain without dots>-web` | target folder; must not exist or be empty |
|
||||
| `--answers <file>` | — | the answers as JSON, no questions |
|
||||
| `--external [a,b]` | none | also the vendored `ext-*` skills (all, or the listed ones) |
|
||||
| `--no-install` | install | write the files only; the report lists the remaining commands |
|
||||
| `--no-git` | git | no `git init` / first commit |
|
||||
| `--dry-run` | off | print the file list and the database names, write nothing |
|
||||
| `--plugin-spec <spec>` | the exact version | install the plugin from another spec — the release gate uses the packed tarball |
|
||||
|
||||
## What it does, in order
|
||||
|
||||
1. Validates the domain, the folder and every answer — nothing is written while one is missing.
|
||||
2. Renders the site from the starter bundle (below) and writes it; writes a local `.env` (`.env.example` with a
|
||||
fresh `PAYLOAD_SECRET`; git-ignored, never committed).
|
||||
3. `pnpm install` from the shipped lockfile, `pnpm exec ipal-skills` (+ `--external`), `pnpm exec ipal-tokens`
|
||||
(writes `src/design/tokens.css`, fails on a WCAG contrast error — pick another colour), `pnpm generate:types`,
|
||||
`pnpm generate:importmap`, `pnpm typecheck`, and `pnpm exec ipal-doctor --strict --offline` when the installed
|
||||
ipal-kit ships it.
|
||||
4. `git init -b main`, a secret check of every staged file (no `.env*` except `.env.example`, no assigned
|
||||
`*_SECRET` / `*_TOKEN` / `*_PASSWORD` / `*_ACCESS_KEY` value, no private key) and one commit
|
||||
`chore: create site with ipal-kit create <version>`. No remote, no push.
|
||||
5. Prints the next steps: local MongoDB with `<domain>_dev`, `pnpm seed` (before launch), the panel steps, the
|
||||
deploy (`docs/DEPLOY.md`).
|
||||
|
||||
**Check:** in the new folder `git log --oneline` = one commit, `git status` clean, `pnpm typecheck` passes,
|
||||
`grep -c 'Project decisions' AGENTS.md` = 1, `cat ipal-doctor.json` shows the domain and `launched: false`.
|
||||
|
||||
## The generated site
|
||||
|
||||
The reference site's tree (AGENT.md §3) with: the plugin pinned to the exact released version, the database
|
||||
names from `databaseNamesFor(domain)` (`intecion.com` → `intecioncom_dev` / `intecioncom_prod`; hyphens stay),
|
||||
CSP in **report-only** (`ipal-doctor.json` silences the report-only finding for 28 days with the reason),
|
||||
`assertEnv(ipalEnvRules({ databaseName, ipHeader, storage, … }))` in `instrumentation.ts`, the blocks from the
|
||||
block library (`libraryBlocks` + `createBlockRegistry(content, { Image, Link, … })`), the design-token standard
|
||||
(`styles.css` imports only, the brand in `src/design/tokens.ts`, next/font `--font-family-body` /
|
||||
`--font-family-heading`), seeds through `createSeeder` with `SEED_ONLY`, and `docs/DEPLOY.md` for the team's
|
||||
Coolify flow — build and check locally, Coolify builds the app from the repo with its default build pack,
|
||||
MongoDB is a separate Coolify resource on the same Docker network, **no Dockerfile**:
|
||||
|
||||
```bash
|
||||
SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm seed # in Coolify → the app → Terminal: read the plan
|
||||
# Coolify → MongoDB resource → Backup now
|
||||
SEED_ONLY="pages:kontakt" pnpm seed # the real run
|
||||
```
|
||||
|
||||
Not in a new site: the reference company's demo content and media, the Blocks showcase page, the smoke tests
|
||||
(`e2e/`), `.agents/skills` (re-installed by `ipal-skills`), `README.md`.
|
||||
|
||||
## How the reference site becomes a site
|
||||
|
||||
`reference/starter.manifest.json` (owned by the reference site) gives every path a role:
|
||||
|
||||
| Role | Meaning |
|
||||
|---|---|
|
||||
| `drop` | left out (demo seeds and media, e2e, generated files) |
|
||||
| `generate` | written by the starter from the answers (`src/i18n.config.ts`, `src/design/tokens.ts`, `DESIGN.md`, `ipal-doctor.json`) |
|
||||
| `template` | copied with `placeholders` replaced — the reference's unique fake values (`example-studio.pl`, `Example Studio`, `example-studiopl`…) → the new site's values |
|
||||
| `keep` | copied as is; must not contain a fake value (the bundle build fails) |
|
||||
| `variants` | whole files that exist only with a flag on (`src/collections/Posts.ts` → `posts`) |
|
||||
| `rewrite` | `package.json` entries set or removed (`null`) |
|
||||
|
||||
Inside files, variants are comment lines, so the reference site stays a normal, runnable project:
|
||||
|
||||
```ts
|
||||
// @starter:if twoFactor
|
||||
twoFactor: { issuer: 'Example Studio', plugin: payloadTotp },
|
||||
// @starter:else
|
||||
//: twoFactor: false, // turned off by the owner
|
||||
// @starter:endif
|
||||
```
|
||||
|
||||
`// @starter:if <flag>` / `!<flag>` … `// @starter:else` … `// @starter:endif` (also `#` in env files, `<!-- -->`
|
||||
in Markdown, `{/* */}` in TSX children); blocks nest. Inside a kept block a `//: ` / `#: ` line is uncommented —
|
||||
that is how the reference carries code it does not run itself. The flags come from the answers
|
||||
(`flagsFromAnswers`): `twoFactor`, `posts`, `caseStudies`, `collections`, `crawl`, `scannerWithoutCrawl`, `r2`,
|
||||
`graph`, `localBusiness`, `aiBotsBlockTraining`, `aiBotsDisallow`, `analytics`, `metaPixel`, `linkedIn`, `tiktok`,
|
||||
`clarity`, `consentBasic`, `bannerDetailed`, `bannerInline`, `bannerModal`, `themeToggle`, `defaultLight`,
|
||||
`defaultDark`, `defaultSystem`, `whiteLabel`, `adminMeta`, `agencyNone`, `agencyCustom`, `enforceCsp` (always
|
||||
off in a new site) and `demo` (always off). A flag the reference uses that this ipal-kit does not set stops the
|
||||
run with its name.
|
||||
|
||||
**Adding a feature to the starter** = changing the reference site: write the code there (marked with
|
||||
`@starter:if` when it depends on an answer), add a placeholder to the manifest when it holds a per-client value,
|
||||
and — for a new answer — the question in `answers.ts` / `prompts.ts` and the flag in `flagsFromAnswers`.
|
||||
|
||||
## Release: the bundle and the gate
|
||||
|
||||
`pnpm build:starter` (in `prepublishOnly`, after `pnpm build`) packs the reference site into
|
||||
`dist/starter/template.json.gz`: the kept files, the manifest and the reference lockfile **without the plugin
|
||||
itself** — its integrity hash does not exist before the tarball is published. The new site's `pnpm install`
|
||||
keeps every locked entry and resolves only the plugin (exact version) and its four dependencies (exact versions
|
||||
too), then the complete lockfile goes into the first commit; from then on `--frozen-lockfile`. Size (measured on
|
||||
1.14.6): the bundle is 90 KB gzipped (69 files + lockfile, 283 KB of text); everything the starter adds — bundle,
|
||||
compiled code with source maps, docs — is ~340 KB unpacked (~4 % of 7.96 MB) and ~180 KB of the 2.40 MB tarball.
|
||||
|
||||
`pnpm starter:gate` (the last step of `prepublishOnly`) blocks the publish unless a site created from the
|
||||
**packed tarball** works the way it will in Coolify: `dlx` create → frozen install → first seed of a fresh
|
||||
`_dev` database (MongoDB in its own Docker container) → `pnpm generate:types && pnpm build` →
|
||||
`SEED_ONLY="pages:kontakt" [SEED_DRY_RUN=1] pnpm seed` in production mode → a full seed in production refused →
|
||||
`pnpm start` with `/api/health`, `/pl`, report-only CSP, no `X-Powered-By`, `/llms.txt` → `ipal-doctor --strict`
|
||||
(when shipped) → with the `nixpacks` CLI on PATH, the same seed inside the Nixpacks image. Needs Docker;
|
||||
`--keep` leaves `.starter-gate/` for inspection.
|
||||
|
||||
## Building blocks — `@intecion/ipal-kit/starter`
|
||||
|
||||
Node built-ins only, no Payload: script your own generator or check a reference tree with them.
|
||||
|
||||
| Export | What it does |
|
||||
|---|---|
|
||||
| `runCreateCli(args, log?)`, `CREATE_USAGE`, `parseCreateArgs(args)`, `normalizeDomain(input)`, `localEnv(example)` | the command and its pieces |
|
||||
| `validateAnswers(input)`, `flagsFromAnswers(answers)`, `STARTER_TOPICS`, `askAnswers(ask)` | the questions as data, their validation, the flags they set, the prompts (any `ask` function) |
|
||||
| `collectBundle(dir)`, `packBundle(bundle)`, `unpackBundle(buffer)`, `bundleFlags(bundle)` | a reference tree → the bundle and back; the flags its markers use |
|
||||
| `renderSite(bundle, answers, ctx)`, `placeholderValues(answers, ctx)` | the new site's files (path → content), in memory |
|
||||
| `applyVariants(text, flags, file?)`, `variantFlags(text)`, `applyPlaceholders(text, fakes, values)`, `leftoverFakes(text, fakes)` | the text transforms |
|
||||
| `assertManifest(value)`, `fileRole(path, manifest)`, `matchGlob(path, glob)`, `ALWAYS_SKIPPED` | the manifest rules |
|
||||
| `renderI18nConfig`, `renderTokens`, `renderDesignMd`, `renderAgentsMd`, `renderDecisions`, `renderDoctorConfig`, `rewriteFonts`, `fontExport`, `rewritePackageJson` | the files and sections written from the answers |
|
||||
| `lockfileWithoutPlugin(lock)`, `secretFindings(files)` | the lockfile step and the secret check |
|
||||
|
||||
Types: `StarterAnswers`, `AnalyticsTool`, `ContentCollection`, `StarterBundle`, `StarterManifest`, `FileRole`,
|
||||
`StarterFlags`, `SiteContext`.
|
||||
|
||||
## Turn off, override
|
||||
|
||||
- The command is optional: the manual path (`ipal-setup` stages 1–11) still sets up any site, including what this
|
||||
version refuses (other default language, no URL prefix, Postgres).
|
||||
- Every generated file belongs to the project afterwards — change it like any other file; `ipal-upgrade` and
|
||||
`ipal-doctor` keep it in line with later plugin versions.
|
||||
- `--no-install`, `--no-git`, `--dir`, `--plugin-spec` change the run; a different reference tree → your own
|
||||
generator from the building blocks above.
|
||||
+13
-5
@@ -34,6 +34,11 @@
|
||||
"types": "./dist/exports/seed.d.ts",
|
||||
"default": "./dist/exports/seed.js"
|
||||
},
|
||||
"./starter": {
|
||||
"import": "./dist/exports/starter.js",
|
||||
"types": "./dist/exports/starter.d.ts",
|
||||
"default": "./dist/exports/starter.js"
|
||||
},
|
||||
"./templates": {
|
||||
"import": "./dist/exports/templates.js",
|
||||
"types": "./dist/exports/templates.d.ts",
|
||||
@@ -78,6 +83,7 @@
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"bin": {
|
||||
"ipal-kit": "bin/ipal-kit.mjs",
|
||||
"ipal-skills": "bin/ipal-skills.mjs",
|
||||
"ipal-blocks": "bin/ipal-blocks.mjs",
|
||||
"ipal-tokens": "bin/ipal-tokens.mjs"
|
||||
@@ -93,6 +99,7 @@
|
||||
],
|
||||
"scripts": {
|
||||
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
||||
"build:starter": "node scripts/build-starter.mjs",
|
||||
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
||||
"build:types": "tsc --outDir dist --rootDir ./src",
|
||||
"clean": "rimraf {dist,*.tsbuildinfo}",
|
||||
@@ -107,8 +114,9 @@
|
||||
"lint": "eslint ./src ./test",
|
||||
"lint:fix": "eslint ./src ./test --fix",
|
||||
"prepare": "pnpm build",
|
||||
"prepublishOnly": "pnpm clean && pnpm build && pnpm test:int",
|
||||
"prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate",
|
||||
"reference:index": "node scripts/reference-index.mjs",
|
||||
"starter:gate": "node scripts/starter-gate.mjs",
|
||||
"test": "pnpm test:int && pnpm test:e2e",
|
||||
"test:e2e": "playwright test",
|
||||
"test:int": "vitest run",
|
||||
@@ -116,10 +124,10 @@
|
||||
"typecheck": "tsc --noEmit -p . && tsc -p test"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^0.400.0",
|
||||
"nodemailer": "^10.2.1",
|
||||
"server-only": "^0.0.1",
|
||||
"slugify": "^1.6.6"
|
||||
"lucide-react": "0.400.0",
|
||||
"nodemailer": "10.3.1",
|
||||
"server-only": "0.0.1",
|
||||
"slugify": "1.6.9"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@clocklimited/payload-2fa": "^3.0.0-0",
|
||||
|
||||
Generated
+8
-8
@@ -26,16 +26,16 @@ importers:
|
||||
specifier: ^3.90.2
|
||||
version: 3.90.2(@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])
|
||||
lucide-react:
|
||||
specifier: ^0.400.0
|
||||
specifier: 0.400.0
|
||||
version: 0.400.0([email protected])
|
||||
nodemailer:
|
||||
specifier: ^10.2.1
|
||||
version: 10.2.1
|
||||
specifier: 10.3.1
|
||||
version: 10.3.1
|
||||
server-only:
|
||||
specifier: ^0.0.1
|
||||
specifier: 0.0.1
|
||||
version: 0.0.1
|
||||
slugify:
|
||||
specifier: ^1.6.6
|
||||
specifier: 1.6.9
|
||||
version: 1.6.9
|
||||
devDependencies:
|
||||
'@eslint/eslintrc':
|
||||
@@ -4437,8 +4437,8 @@ packages:
|
||||
resolution: {integrity: sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
nodemailer@10.2.1:
|
||||
resolution: {integrity: sha512-ZrDNsPFoDMwefNs7sJwrYiEJ/CG4ClJWDZv05iNJsEBWa8GRDry1QJHTJxsuTAY9eDDKjX4k+q3SxslXJOao7w==}
|
||||
nodemailer@10.3.1:
|
||||
resolution: {integrity: sha512-uF0AFsJC07Y1vdW7p580DKAnh7rAO+4UPSSB3mDCPNDufoiaOebV6JmrzpxB14OjEEEiBsNdYoM2Y+fN8M7BBA==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
[email protected]:
|
||||
@@ -10588,7 +10588,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
nodemailer@10.2.1: {}
|
||||
nodemailer@10.3.1: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
# @starter:if demo
|
||||
# Example Studio — reference site for @intecion/ipal-kit. Copy to .env for local work.
|
||||
# @starter:else
|
||||
#: # Example Studio — copy to .env for local work (`ipal-kit create` already wrote one with a fresh PAYLOAD_SECRET).
|
||||
# @starter:endif
|
||||
# Production values live in the Coolify app → Environment Variables (docs/DEPLOY.md), never in the repo.
|
||||
|
||||
# MongoDB — database name from databaseNamesFor('example-studio.pl'): example-studiopl_dev / example-studiopl_prod
|
||||
@@ -17,6 +21,14 @@ IPAL_NOINDEX=
|
||||
# NEVER set in Coolify — production requires R2.
|
||||
ALLOW_LOCAL_MEDIA=
|
||||
|
||||
# @starter:if graph
|
||||
#: # Microsoft Graph e-mail (agency-level, all four) — email.md
|
||||
#: GRAPH_TENANT_ID=
|
||||
#: GRAPH_CLIENT_ID=
|
||||
#: GRAPH_CLIENT_SECRET=
|
||||
#: GRAPH_SENDER=
|
||||
# @starter:endif
|
||||
|
||||
# Cloudflare R2 — all or none; empty = media on local disk (dev)
|
||||
R2_BUCKET=
|
||||
R2_ENDPOINT=
|
||||
@@ -28,16 +40,20 @@ R2_PUBLIC_URL=
|
||||
NEXT_PUBLIC_TURNSTILE_SITE_KEY=1x00000000000000000000AA
|
||||
TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA
|
||||
|
||||
# @starter:if crawl
|
||||
# Cookie scanner "Crawl site" — the shared services/cookie-crawler deployment
|
||||
IPAL_COOKIE_SCAN_URL=
|
||||
IPAL_COOKIE_SCAN_TOKEN=
|
||||
# @starter:endif
|
||||
|
||||
# IndexNow key (or generate one in Site integrations)
|
||||
INDEXNOW_KEY=
|
||||
|
||||
# @starter:if demo
|
||||
# Smoke tests only (e2e/, pnpm test:e2e) — a test admin on the LOCAL / CI database, created by
|
||||
# e2e/create-test-admin.ts with a known TOTP secret so the test signs in through the real 2FA screen.
|
||||
# Test values, never used anywhere else; the script refuses a production or non-local database.
|
||||
E2E_ADMIN_EMAIL=[email protected]
|
||||
E2E_ADMIN_PASSWORD=e2e-RC2nC29eKC8HJHfg
|
||||
E2E_TOTP_SECRET=JPURUZNWYTZX2L42MT4SS7736WWNQWBL
|
||||
# @starter:endif
|
||||
|
||||
@@ -25,7 +25,7 @@ pnpm test:e2e # smoke tests, after `pnpm pay
|
||||
| Start command | `pnpm start` (`next start` with `--disable-proto=throw`) |
|
||||
| Port | 3000 — no host port mapping (it disables rolling updates) |
|
||||
| Health check | `GET /api/health` → 200 (503 without the database) |
|
||||
| Domains | `https://example-studio.pl,https://www.example-studio.pl`, redirect www → apex (matches `NEXT_PUBLIC_SERVER_URL`) |
|
||||
| Domains | both hosts: `example-studio.pl` and `www.example-studio.pl` (with `https://`), redirect to the host of `NEXT_PUBLIC_SERVER_URL` |
|
||||
|
||||
## 3. The Coolify MongoDB resource
|
||||
- Same server and Docker network as the app; never exposed publicly.
|
||||
@@ -33,6 +33,10 @@ pnpm test:e2e # smoke tests, after `pnpm pay
|
||||
(database name from `databaseNamesFor('example-studio.pl')`; `instrumentation.ts` checks it).
|
||||
- Scheduled backups to S3/R2, and **Backup now** before every seed or bulk change.
|
||||
- MongoDB needs no migrations.
|
||||
<!-- @starter:if !r2 -->
|
||||
#: - **Media on local disk** (no R2): Coolify → the app → **Persistent Storage** → a volume for the `media` folder
|
||||
#: (the upload collection's `staticDir`), or every redeploy deletes the uploads (deployment.md §4.8).
|
||||
<!-- @starter:endif -->
|
||||
|
||||
## 4. Environment variables (Coolify → Environment Variables)
|
||||
| Variable | Build | Runtime | Note |
|
||||
@@ -40,10 +44,17 @@ pnpm test:e2e # smoke tests, after `pnpm pay
|
||||
| `DATABASE_URI` | ✓ | ✓ | build prerenders pages from the database |
|
||||
| `PAYLOAD_SECRET` | ✓ | ✓ | random, ≥ 32 characters |
|
||||
| `NEXT_PUBLIC_SERVER_URL` | ✓ | ✓ | `https://example-studio.pl` |
|
||||
<!-- @starter:if r2 -->
|
||||
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | | ✓ | required in production |
|
||||
| `R2_PUBLIC_URL` | ✓ | ✓ | empty = media served by the app |
|
||||
<!-- @starter:endif -->
|
||||
<!-- @starter:if graph -->
|
||||
#: | `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | | ✓ | e-mail through Microsoft Graph (all four) |
|
||||
<!-- @starter:endif -->
|
||||
| `IPAL_IP_HEADER` | | ✓ | `x-forwarded-for` behind Coolify's proxy (`cf-connecting-ip` behind Cloudflare) |
|
||||
<!-- @starter:if crawl -->
|
||||
| `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | | ✓ | the shared cookie-crawler service |
|
||||
<!-- @starter:endif -->
|
||||
| `INDEXNOW_KEY` | | ✓ | or generate the key in Site integrations |
|
||||
| `ALLOW_LOCAL_MEDIA` | — | — | **never set here** (local / CI only) |
|
||||
|
||||
|
||||
@@ -9,12 +9,36 @@ import {
|
||||
} from '@intecion/ipal-kit'
|
||||
import { withPayload } from '@payloadcms/next/withPayload'
|
||||
|
||||
// @starter:if enforceCsp
|
||||
// CSP enforced: the reference site is the example after the report-only phase (security.md → "ROLL OUT CSP").
|
||||
// Flags = what the site loads: Turnstile on forms, Google analytics/GTM when IDs are set in Site integrations.
|
||||
const csp = { mode: 'enforce', r2Url: process.env.R2_PUBLIC_URL, reportUri: '/api/csp-report' } as const
|
||||
// @starter:else
|
||||
//: // CSP step 1: report-only. Read the [csp] lines in the logs, add a flag or `extra` per report, then switch to
|
||||
//: // mode: 'enforce' (security.md → "ROLL OUT CSP"; ipal-doctor.json silences the report-only finding until then).
|
||||
//: const csp = { mode: 'report-only', r2Url: process.env.R2_PUBLIC_URL, reportUri: '/api/csp-report' } as const
|
||||
// @starter:endif
|
||||
|
||||
// Flags = what the site loads: Turnstile on forms, the analytics tools whose IDs are set in Site integrations.
|
||||
const securityHeaders = buildSecurityHeaders({
|
||||
csp: { ...csp, analytics: true, turnstile: true },
|
||||
csp: {
|
||||
...csp,
|
||||
// @starter:if analytics
|
||||
analytics: true,
|
||||
// @starter:endif
|
||||
// @starter:if metaPixel
|
||||
//: metaPixel: true,
|
||||
// @starter:endif
|
||||
// @starter:if linkedIn
|
||||
//: linkedIn: true,
|
||||
// @starter:endif
|
||||
// @starter:if tiktok
|
||||
//: tiktok: true,
|
||||
// @starter:endif
|
||||
// @starter:if clarity
|
||||
//: clarity: true,
|
||||
// @starter:endif
|
||||
turnstile: true,
|
||||
},
|
||||
hsts: process.env.NODE_ENV === 'production',
|
||||
})
|
||||
|
||||
|
||||
@@ -42,7 +42,18 @@ export default async function LocaleLayout({ children, params }: Props) {
|
||||
{/* NO <head> — Next manages it */}
|
||||
<body className="flex min-h-screen flex-col bg-bg font-body text-fg antialiased">
|
||||
<SiteProviders
|
||||
// @starter:if consentBasic
|
||||
//: analytics={{ consentMode: 'basic' }} // no request to Google before consent (AGENTS.md → Project decisions)
|
||||
// @starter:endif
|
||||
// @starter:if bannerInline
|
||||
//: banner={<CookieBanner controls="switch" equalChoice settings="inline" />}
|
||||
// @starter:endif
|
||||
// @starter:if bannerModal
|
||||
//: banner={<CookieBanner controls="switch" equalChoice settings="modal" />}
|
||||
// @starter:endif
|
||||
// @starter:if bannerDetailed
|
||||
banner={<CookieBanner controls="switch" equalChoice settings="detailed" />}
|
||||
// @starter:endif
|
||||
lightbox
|
||||
logEndpoint="/api/ipal/consent"
|
||||
shell={shell}
|
||||
|
||||
@@ -7,12 +7,18 @@ import { libraryBlocks, type LibraryBlocksOptions } from '@intecion/ipal-kit/blo
|
||||
export const blockOptions = {
|
||||
contact: true,
|
||||
cta: true,
|
||||
// @starter:if collections
|
||||
entryList: {
|
||||
collections: [
|
||||
// @starter:if posts
|
||||
{ label: { en: 'Blog posts', pl: 'Wpisy' }, value: 'posts' },
|
||||
// @starter:endif
|
||||
// @starter:if caseStudies
|
||||
{ label: { en: 'Case studies', pl: 'Realizacje' }, value: 'caseStudies' },
|
||||
// @starter:endif
|
||||
],
|
||||
},
|
||||
// @starter:endif
|
||||
faq: true,
|
||||
featureGrid: true,
|
||||
gallery: true,
|
||||
|
||||
@@ -6,7 +6,11 @@ import type { ContentOption } from '@intecion/ipal-kit'
|
||||
*/
|
||||
export const contentConfig: ContentOption = {
|
||||
collections: [
|
||||
// @starter:if posts
|
||||
{ slug: 'posts', label: 'Blog', perPage: 9 },
|
||||
// @starter:endif
|
||||
// @starter:if caseStudies
|
||||
{ slug: 'caseStudies', label: 'Case studies', perPage: 9 },
|
||||
// @starter:endif
|
||||
],
|
||||
}
|
||||
|
||||
@@ -7,8 +7,20 @@ export function register() {
|
||||
// databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor).
|
||||
// R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md).
|
||||
assertEnv(
|
||||
ipalEnvRules({ databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) =>
|
||||
rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule,
|
||||
),
|
||||
ipalEnvRules({
|
||||
// @starter:if crawl
|
||||
//: cookieCrawl: true, // IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN — the shared cookie-crawler service
|
||||
// @starter:endif
|
||||
databaseName: { domain: 'example-studio.pl' },
|
||||
// @starter:if graph
|
||||
//: emailGraph: true, // GRAPH_* — e-mail through Microsoft Graph
|
||||
// @starter:endif
|
||||
ipHeader: true,
|
||||
// @starter:if r2
|
||||
storage: process.env.ALLOW_LOCAL_MEDIA !== '1',
|
||||
// @starter:else
|
||||
//: storage: false, // media on local disk — a Coolify persistent volume (AGENTS.md → Project decisions)
|
||||
// @starter:endif
|
||||
}).map((rule) => (rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { faqItemsFromLayout } from '@intecion/ipal-kit/blocks'
|
||||
// @starter:if localBusiness
|
||||
import { buildLocalBusinessJsonLd, createContentHelpers } from '@intecion/ipal-kit'
|
||||
|
||||
import { getPayload } from 'payload'
|
||||
import { contentConfig } from '@/content.config'
|
||||
import { i18nConfig, type Locale } from '@/i18n.config'
|
||||
// @starter:else
|
||||
//: import { createContentHelpers } from '@intecion/ipal-kit'
|
||||
//:
|
||||
//: import { contentConfig } from '@/content.config'
|
||||
//: import { i18nConfig } from '@/i18n.config'
|
||||
// @starter:endif
|
||||
import config from '@/payload.config'
|
||||
|
||||
/** The ONLY access to Payload, routes, links and navigation (AGENT.md §3, PROGRAMISTA §2.7). */
|
||||
@@ -49,6 +56,13 @@ export const {
|
||||
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> on every page
|
||||
mcp: { serverName: 'example-studio-site' },
|
||||
pageJsonLd: { faq: (doc) => faqItemsFromLayout(doc) }, // FAQ blocks → FAQPage rich results
|
||||
// @starter:if aiBotsBlockTraining
|
||||
//: robots: { aiBots: 'block-training' }, // client decision — AGENTS.md → Project decisions (ipal-audit-skip: aibots)
|
||||
// @starter:endif
|
||||
// @starter:if aiBotsDisallow
|
||||
//: robots: { aiBots: 'disallow' }, // client decision — AGENTS.md → Project decisions (ipal-audit-skip: aibots)
|
||||
// @starter:endif
|
||||
// @starter:if localBusiness
|
||||
// LocalBusiness from the Company global (replaces the default WebSite + Organization from Site settings)
|
||||
siteJsonLd: async ({ baseUrl, locale }) => {
|
||||
const payload = await getPayload({ config })
|
||||
@@ -65,5 +79,6 @@ export const {
|
||||
}),
|
||||
]
|
||||
},
|
||||
// @starter:endif
|
||||
summaryField: 'aiSummary',
|
||||
})
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// @starter:if twoFactor
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
// @starter:endif
|
||||
import { buildR2Storage, ipalKit, mailAdapter } from '@intecion/ipal-kit'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { s3Storage } from '@payloadcms/storage-s3'
|
||||
@@ -8,10 +10,14 @@ import { buildConfig } from 'payload'
|
||||
import sharp from 'sharp'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
// @starter:if caseStudies
|
||||
import { CaseStudies } from './collections/CaseStudies'
|
||||
// @starter:endif
|
||||
import { Media } from './collections/Media'
|
||||
import { Pages } from './collections/Pages'
|
||||
// @starter:if posts
|
||||
import { Posts } from './collections/Posts'
|
||||
// @starter:endif
|
||||
import { contentConfig } from './content.config'
|
||||
import { db } from './db'
|
||||
import { Company } from './globals/Company'
|
||||
@@ -28,7 +34,17 @@ export default buildConfig({
|
||||
},
|
||||
// absolute URLs in form e-mails (logo, links)
|
||||
serverURL: process.env.NEXT_PUBLIC_SERVER_URL,
|
||||
collections: [Pages, Posts, CaseStudies, Media], // ipalKit injects `users` (roles + 2FA)
|
||||
// ipalKit injects `users` (roles + 2FA)
|
||||
collections: [
|
||||
Pages,
|
||||
// @starter:if posts
|
||||
Posts,
|
||||
// @starter:endif
|
||||
// @starter:if caseStudies
|
||||
CaseStudies,
|
||||
// @starter:endif
|
||||
Media,
|
||||
],
|
||||
globals: [Header, Footer, Company],
|
||||
db,
|
||||
editor: lexicalEditor(),
|
||||
@@ -42,14 +58,44 @@ export default buildConfig({
|
||||
access: { authCollection: 'users' },
|
||||
pages: { slug: 'pages' },
|
||||
content: contentConfig,
|
||||
seo: { collections: ['pages', 'posts', 'caseStudies'] },
|
||||
seo: {
|
||||
collections: [
|
||||
'pages',
|
||||
// @starter:if posts
|
||||
'posts',
|
||||
// @starter:endif
|
||||
// @starter:if caseStudies
|
||||
'caseStudies',
|
||||
// @starter:endif
|
||||
],
|
||||
},
|
||||
forms: { redirectRelationships: ['pages'], emailLayout: true },
|
||||
// @starter:if twoFactor
|
||||
twoFactor: { issuer: 'Example Studio', plugin: payloadTotp },
|
||||
// @starter:else
|
||||
//: twoFactor: false, // turned off by the owner — AGENTS.md → Project decisions, ipal-doctor.json
|
||||
// @starter:endif
|
||||
// @starter:if whiteLabel
|
||||
whiteLabel: true,
|
||||
// @starter:endif
|
||||
// @starter:if !adminMeta
|
||||
//: adminMeta: false, // turned off by the owner — AGENTS.md → Project decisions
|
||||
// @starter:endif
|
||||
// @starter:if agencyNone
|
||||
//: agency: false, // no agency credit (owner's choice)
|
||||
// @starter:endif
|
||||
// @starter:if agencyCustom
|
||||
//: agency: { name: 'Example Agency', url: 'https://agency.example' },
|
||||
// @starter:endif
|
||||
indexNow: true,
|
||||
consentLog: true,
|
||||
// Privacy → Cookie review: scan + approval; crawl needs IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN
|
||||
// @starter:if crawl
|
||||
cookieScanner: { crawl: true },
|
||||
// @starter:endif
|
||||
// @starter:if scannerWithoutCrawl
|
||||
//: cookieScanner: true,
|
||||
// @starter:endif
|
||||
lightbox: true,
|
||||
revalidatePath,
|
||||
}),
|
||||
|
||||
@@ -16,11 +16,24 @@ import { pageLink, tx } from './lib'
|
||||
const blocks = libraryBlockSlugs(blockOptions)
|
||||
|
||||
export async function seedBaseGlobals(seed: Seeder) {
|
||||
await seed.fillGlobal('company', { email: '[TO FILL: e-mail that receives form submissions]', name: '[TO FILL: company name]' })
|
||||
// the inbox and the name come from the starter's answers (AGENTS.md → Project decisions)
|
||||
await seed.fillGlobal('company', { email: '[email protected]', name: 'Example Studio' })
|
||||
await seed.fillGlobal('site-settings', {
|
||||
// @starter:if themeToggle
|
||||
allowThemeToggle: true,
|
||||
// @starter:else
|
||||
//: allowThemeToggle: false,
|
||||
// @starter:endif
|
||||
// @starter:if defaultLight
|
||||
//: defaultTheme: 'light',
|
||||
// @starter:endif
|
||||
// @starter:if defaultDark
|
||||
//: defaultTheme: 'dark',
|
||||
// @starter:endif
|
||||
// @starter:if defaultSystem
|
||||
defaultTheme: 'system',
|
||||
siteName: '[TO FILL: site name]',
|
||||
// @starter:endif
|
||||
siteName: 'Example Studio',
|
||||
themeToggleLabel: tx('Tryb ciemny', 'Dark mode'),
|
||||
})
|
||||
}
|
||||
@@ -32,7 +45,9 @@ export async function seedBasePages(seed: Seeder) {
|
||||
pageTemplates.services({ blocks }),
|
||||
pageTemplates.contact({ blocks, form: { $form: 'Contact form' } }),
|
||||
// The archive page lists its entries with an entry list block (the editor decides where)
|
||||
// @starter:if posts
|
||||
pageTemplates.blogIndex({ blocks, layout: (b) => [b[0], { blockType: 'entryList', entryCollection: 'posts', limit: 9, mode: 'latest', variant: 'cards' }, ...b.slice(1)] }),
|
||||
// @starter:endif
|
||||
pageTemplates.legal('privacyPolicy', { blocks }),
|
||||
pageTemplates.legal('termsOfService', { blocks }),
|
||||
pageTemplates.cookiePolicy({ blocks }),
|
||||
@@ -44,15 +59,35 @@ export async function seedBaseNavigation(seed: Seeder) {
|
||||
const link = (label: { en: string; pl: string }, slug: string) => ({ link: { label, page: { $page: slug }, type: 'internal' } })
|
||||
await seed.fillGlobal('site-settings', {
|
||||
...systemPageRefs({ cookiePolicy: 'polityka-cookies', homepage: 'start', notFound: 'nie-znaleziono', privacyPolicy: 'polityka-prywatnosci', termsOfService: 'regulamin' }),
|
||||
// @starter:if posts
|
||||
postsArchive: { $page: 'blog' },
|
||||
// @starter:endif
|
||||
})
|
||||
await seed.fillGlobal('header', {
|
||||
links: [pageLink(tx('Kontakt', 'Contact'), 'kontakt')],
|
||||
menuLabel: tx('Menu', 'Menu'),
|
||||
navItems: [link(tx('O nas', 'About'), 'o-nas'), link(tx('Usługi', 'Services'), 'uslugi'), link(tx('Blog', 'Blog'), 'blog'), link(tx('Kontakt', 'Contact'), 'kontakt')],
|
||||
navItems: [
|
||||
link(tx('O nas', 'About'), 'o-nas'),
|
||||
link(tx('Usługi', 'Services'), 'uslugi'),
|
||||
// @starter:if posts
|
||||
link(tx('Blog', 'Blog'), 'blog'),
|
||||
// @starter:endif
|
||||
link(tx('Kontakt', 'Contact'), 'kontakt'),
|
||||
],
|
||||
})
|
||||
await seed.fillGlobal('footer', {
|
||||
columns: [{ heading: tx('Strona', 'Site'), items: [link(tx('O nas', 'About'), 'o-nas'), link(tx('Usługi', 'Services'), 'uslugi'), link(tx('Blog', 'Blog'), 'blog')] }],
|
||||
columns: [
|
||||
{
|
||||
heading: tx('Strona', 'Site'),
|
||||
items: [
|
||||
link(tx('O nas', 'About'), 'o-nas'),
|
||||
link(tx('Usługi', 'Services'), 'uslugi'),
|
||||
// @starter:if posts
|
||||
link(tx('Blog', 'Blog'), 'blog'),
|
||||
// @starter:endif
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Seeds of the reference site — rules: node_modules/@intecion/ipal-kit/docs/seeding.md.
|
||||
*
|
||||
* pnpm seed # everything: demo layer first (filled pages win), then the base layer
|
||||
* pnpm seed:base # only what every new site keeps (the project starter runs this one)
|
||||
* pnpm seed:demo # only the made-up company's content (needs the base forms)
|
||||
* pnpm seed # the reference site: demo layer first (filled pages win), then the base layer;
|
||||
* # a site made by `ipal-kit create`: the base layer only
|
||||
* pnpm seed:base # only what every new site keeps
|
||||
* pnpm seed:demo # reference site only: the made-up company's content (needs the base forms)
|
||||
* SEED_DRY_RUN=1 pnpm seed # print the plan, write nothing
|
||||
*
|
||||
* VERY IMPORTANT — after launch: never the whole seed again. Name the records the run may touch:
|
||||
@@ -16,34 +17,50 @@ import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { seedBaseGlobals, seedBaseNavigation, seedBasePages, seedBaseTexts } from './base'
|
||||
// @starter:if demo
|
||||
import { DEMO_NOTIFY_EMAIL, seedDemoGlobals, seedDemoNavigation, seedDemoPages } from './demo'
|
||||
// @starter:endif
|
||||
import { seedForms } from './forms'
|
||||
// @starter:if demo
|
||||
import { seedMedia } from './media'
|
||||
// @starter:endif
|
||||
|
||||
// @starter:if demo
|
||||
const layer = process.env.SEED_LAYER ?? 'all'
|
||||
const withDemo = layer === 'all' || layer === 'demo'
|
||||
const withBase = layer === 'all' || layer === 'base'
|
||||
// @starter:else
|
||||
//: const withBase = true // a new site has only the base layer (the reference site's demo is not copied)
|
||||
// @starter:endif
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
const seed = createSeeder(payload)
|
||||
|
||||
// @starter:if demo
|
||||
const media = withDemo ? await seedMedia(payload) : {}
|
||||
if (withDemo) {await seedDemoGlobals(seed, media)}
|
||||
// @starter:endif
|
||||
if (withBase) {await seedBaseGlobals(seed)}
|
||||
|
||||
// Forms need the inbox that receives submissions: SEED_NOTIFY_EMAIL, else the Company global — never a guess.
|
||||
const company = (await payload.findGlobal({ slug: 'company' })) as { email?: null | string }
|
||||
// @starter:if demo
|
||||
const notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() || (withDemo ? DEMO_NOTIFY_EMAIL : company.email?.trim()) || ''
|
||||
// @starter:else
|
||||
//: const notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() || company.email?.trim() || ''
|
||||
// @starter:endif
|
||||
if (/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
|
||||
await seedForms(seed, notifyTo)
|
||||
} else {
|
||||
console.error('[seed] Forms skipped: fill Company → E-mail in the panel or run with SEED_NOTIFY_EMAIL=… (ask the client which inbox).')
|
||||
}
|
||||
|
||||
// @starter:if demo
|
||||
if (withDemo) {
|
||||
await seedDemoPages(seed, media)
|
||||
await seedDemoNavigation(seed)
|
||||
}
|
||||
// @starter:endif
|
||||
if (withBase) {
|
||||
await seedBasePages(seed)
|
||||
await seedBaseNavigation(seed)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"$comment": "How `ipal-kit create` turns this reference site into a new project. reference/ is the only hand-edited tree; the starter keeps no template files of its own. Paths are relative to reference/. Rules: keep = copied as is; drop = left out; template = copied with the placeholders below replaced. In-file variants: `// @starter:if <flag>` … `// @starter:endif` ({/* */} in TSX). The fake values are unique strings, so the generator fails if one is left in a file it does not map.",
|
||||
"$comment": "How `ipal-kit create` turns this reference site into a new project (docs/project-starter.md). reference/ is the only hand-edited tree; the starter keeps no template files of its own. Paths are relative to reference/. Roles: drop = left out; generate = written by the starter from the owner's answers; template = copied with the placeholders below replaced; keep = copied as is (and must hold no fake value). variants = whole files that exist only with a flag on. In-file variants: `// @starter:if <flag>` … `// @starter:else` … `// @starter:endif` ({/* */} in TSX, # in env files, <!-- --> in Markdown); inside a kept block a `//: ` / `#: ` line is uncommented — that is how this site carries code it does not run itself. Flags: src/modules/starter/answers.ts (flagsFromAnswers).",
|
||||
"schema": 1,
|
||||
"placeholders": {
|
||||
"{{domain}}": "example-studio.pl",
|
||||
@@ -8,47 +8,68 @@
|
||||
"{{issuer}}": "Example Studio",
|
||||
"{{projectName}}": "example-studiopl-web",
|
||||
"{{mcpName}}": "example-studio-site",
|
||||
"{{serverUrl}}": "https://example-studio.pl"
|
||||
"{{serverUrl}}": "https://example-studio.pl",
|
||||
"{{formRecipient}}": "[email protected]",
|
||||
"{{businessType}}": "ProfessionalService",
|
||||
"{{agencyName}}": "Example Agency",
|
||||
"{{agencyUrl}}": "https://agency.example"
|
||||
},
|
||||
"drop": [
|
||||
"src/seed/demo.ts",
|
||||
"src/seed/showcase.ts",
|
||||
"src/seed/media.ts",
|
||||
"media/**",
|
||||
".agents/**",
|
||||
".env",
|
||||
"node_modules/**",
|
||||
".next/**",
|
||||
"test-results/**",
|
||||
"README.md",
|
||||
"e2e/**",
|
||||
"media/**",
|
||||
"node_modules/**",
|
||||
"playwright-report/**",
|
||||
"playwright.config.ts",
|
||||
"src/payload-types.ts",
|
||||
"next-env.d.ts",
|
||||
"README.md"
|
||||
"src/seed/demo.ts",
|
||||
"src/seed/media.ts",
|
||||
"src/seed/showcase.ts",
|
||||
"test-results/**"
|
||||
],
|
||||
"generate": [
|
||||
"DESIGN.md",
|
||||
"ipal-doctor.json",
|
||||
"src/design/tokens.ts",
|
||||
"src/i18n.config.ts"
|
||||
],
|
||||
"template": [
|
||||
"package.json",
|
||||
"AGENTS.md",
|
||||
"DESIGN.md",
|
||||
"docs/DEPLOY.md",
|
||||
".env.example",
|
||||
"ipal-doctor.json",
|
||||
"src/payload.config.ts",
|
||||
"src/instrumentation.ts",
|
||||
"src/lib/content.ts",
|
||||
"src/db.ts"
|
||||
"src/db.ts",
|
||||
"src/seed/base.ts"
|
||||
],
|
||||
"variants": {
|
||||
"src/collections/Posts.ts": "posts",
|
||||
"src/collections/CaseStudies.ts": "caseStudies",
|
||||
"src/collections/entryFields.ts": "collections"
|
||||
},
|
||||
"keep": [
|
||||
"**"
|
||||
],
|
||||
"keep": ["**"],
|
||||
"rewrite": {
|
||||
"package.json": {
|
||||
"dependencies.@intecion/ipal-kit": "<exact released version>",
|
||||
"dependenciesMeta": null,
|
||||
"scripts.seed": "payload run src/seed/index.ts",
|
||||
"scripts.seed:demo": null
|
||||
},
|
||||
"src/seed/index.ts": "SEED_LAYER defaults to base; the demo imports are removed",
|
||||
"AGENTS.md": "the block between <!-- starter:decisions --> and <!-- /starter:decisions --> is replaced with the answers to the starter's questions"
|
||||
"scripts.seed:demo": null,
|
||||
"scripts.test:e2e": null,
|
||||
"devDependencies.@playwright/test": null
|
||||
}
|
||||
},
|
||||
"pages": {
|
||||
"drop": ["bloki"],
|
||||
"keep": ["design"]
|
||||
"drop": [
|
||||
"bloki"
|
||||
],
|
||||
"keep": [
|
||||
"design"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
// pnpm build:starter — packs reference/ into the starter bundle shipped in the tarball
|
||||
// (dist/starter/template.json.gz): the kept files, the manifest and the lockfile without the plugin.
|
||||
// Runs in prepublishOnly after `pnpm build`; fails when the reference site breaks a manifest rule.
|
||||
|
||||
import { mkdirSync, statSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const { bundleFlags, collectBundle, packBundle } = await import(pathToFileURL(join(root, 'dist', 'exports', 'starter.js')).href)
|
||||
|
||||
const bundle = collectBundle(join(root, 'reference'))
|
||||
const out = join(root, 'dist', 'starter', 'template.json.gz')
|
||||
mkdirSync(dirname(out), { recursive: true })
|
||||
writeFileSync(out, packBundle(bundle))
|
||||
const raw = Object.values(bundle.files).reduce((sum, text) => sum + Buffer.byteLength(text), 0) + Buffer.byteLength(bundle.lockfile)
|
||||
console.log(`starter bundle: ${Object.keys(bundle.files).length} files + lockfile, ${(raw / 1024).toFixed(0)} KB raw → ${(statSync(out).size / 1024).toFixed(0)} KB gzipped (${out.slice(root.length + 1)})`)
|
||||
console.log(`flags used by the reference site: ${bundleFlags(bundle).join(', ')}`)
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env node
|
||||
// pnpm starter:gate — the release gate of `ipal-kit create` (prepublishOnly, after build:starter).
|
||||
// Packs the plugin, creates a site from the PACKED tarball the way a developer does (pnpm dlx), then builds and
|
||||
// runs it the way Coolify does: frozen install, `pnpm generate:types && pnpm build`, `pnpm start`, MongoDB in its
|
||||
// own container. It runs the documented targeted seed in production mode, checks that a full seed is refused
|
||||
// there, and runs `ipal-doctor --strict` when the plugin ships it. Any failure exits 1 and blocks the publish.
|
||||
// pnpm starter:gate → everything, then cleans up (the work folder and the MongoDB container)
|
||||
// pnpm starter:gate --keep → leave .starter-gate/ for inspection
|
||||
// Needs Docker (MongoDB image mongo:7) and the npm registry (or a warm pnpm store). With the `nixpacks` CLI on
|
||||
// PATH it also builds the site with Coolify's build pack and runs the seed inside that image.
|
||||
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const keep = process.argv.includes('--keep')
|
||||
// a short path inside the repo: pnpm's store index uses the tarball path in a file name (ENAMETOOLONG otherwise)
|
||||
const work = join(root, '.starter-gate')
|
||||
const domain = 'release-check.example'
|
||||
const mongoName = `ipal-starter-gate-${process.pid}`
|
||||
const PORT = '3311'
|
||||
const results = []
|
||||
let mongoStarted = false
|
||||
let server = null
|
||||
|
||||
function log(line) {
|
||||
console.log(`[starter:gate] ${line}`)
|
||||
}
|
||||
|
||||
function sh(cwd, command, args, env = {}, { allowFail = false } = {}) {
|
||||
log(`$ ${[command, ...args].join(' ')}`)
|
||||
const result = spawnSync(command, args, { cwd, env: { ...process.env, ...env }, stdio: 'inherit' })
|
||||
if (result.status !== 0 && !allowFail) {throw new Error(`${command} ${args.join(' ')} → exit ${result.status}`)}
|
||||
return result.status ?? 1
|
||||
}
|
||||
|
||||
function out(command, args) {
|
||||
return spawnSync(command, args, { encoding: 'utf8' }).stdout?.trim() ?? ''
|
||||
}
|
||||
|
||||
function check(name, ok, detail = '') {
|
||||
results.push({ detail, name, ok })
|
||||
log(`${ok ? '✓' : '✗'} ${name}${detail ? ` — ${detail}` : ''}`)
|
||||
if (!ok) {throw new Error(`gate failed: ${name}`)}
|
||||
}
|
||||
|
||||
async function waitFor(url, seconds) {
|
||||
for (let i = 0; i < seconds; i++) {
|
||||
try {
|
||||
const res = await fetch(url)
|
||||
if (res.status < 500) {return res.status}
|
||||
} catch {
|
||||
// not up yet
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 1000))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const answers = {
|
||||
admin: { adminMeta: true, agency: 'intecion', twoFactor: true, whiteLabel: true },
|
||||
consent: { banner: 'detailed', consentMode: 'advanced', cookieScanner: true, crawl: true, tools: ['ga4'] },
|
||||
content: { collections: ['posts'], pages: ['Home', 'About', 'Services', 'Blog', 'Contact', 'Privacy policy', 'Cookie policy'] },
|
||||
forms: { list: ['Contact form'], recipient: '[email protected]', transport: 'smtp' },
|
||||
hosting: { canonical: 'apex', coolify: 'release gate', dns: 'the team' },
|
||||
industry: 'release check',
|
||||
languages: { default: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
|
||||
market: 'PL',
|
||||
media: 'r2',
|
||||
seo: { aiBots: 'allow', localBusiness: { type: 'ProfessionalService' } },
|
||||
siteName: 'Release Check',
|
||||
styling: { defaultTheme: 'system', fluid: 'wide', fontBody: 'Inter', fontHeading: 'Inter', primary: 'oklch(0.5 0.17 250)', radius: 'soft', theme: 'both' },
|
||||
tooling: { external: [] },
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!existsSync(join(root, 'dist', 'starter', 'template.json.gz'))) {throw new Error('run `pnpm build && pnpm build:starter` first')}
|
||||
rmSync(work, { force: true, recursive: true })
|
||||
mkdirSync(work, { recursive: true })
|
||||
|
||||
// 1. the tarball exactly as it would be published
|
||||
sh(root, 'pnpm', ['pack', '--pack-destination', work])
|
||||
const packed = readdirSync(work).find((f) => f.endsWith('.tgz'))
|
||||
const tarball = join(work, 'ipal-kit.tgz')
|
||||
sh(work, 'mv', [packed, tarball])
|
||||
|
||||
// 2. MongoDB in its own container, like the Coolify database resource
|
||||
sh(root, 'docker', ['run', '-d', '--rm', '--name', mongoName, '-p', '127.0.0.1::27017', 'mongo:7'])
|
||||
mongoStarted = true
|
||||
const mongoPort = out('docker', ['port', mongoName, '27017']).split(':').pop()
|
||||
check('MongoDB container', Boolean(mongoPort), `127.0.0.1:${mongoPort}`)
|
||||
|
||||
// 3. the developer's command, from the packed tarball
|
||||
const answersFile = join(work, 'answers.json')
|
||||
writeFileSync(answersFile, JSON.stringify(answers, null, 2))
|
||||
const started = Date.now()
|
||||
const created = sh(work, 'pnpm', ['--config.auto-install-peers=false', 'dlx', tarball, 'create', domain, '--answers', answersFile, '--plugin-spec', `file:${tarball}`], {}, { allowFail: true })
|
||||
check('ipal-kit create (install, skills, tokens, types, import map, typecheck, secret check, first commit)', created === 0, `${((Date.now() - started) / 1000).toFixed(0)} s`)
|
||||
const site = join(work, 'release-checkexample-web')
|
||||
check('first commit, nothing left uncommitted', out('git', ['-C', site, 'status', '--porcelain']) === '' && out('git', ['-C', site, 'log', '--oneline']).split('\n').length === 1)
|
||||
|
||||
// 4. what Coolify runs: frozen install from the committed lockfile, then build, then start
|
||||
const env = {
|
||||
ALLOW_LOCAL_MEDIA: '1', // no R2 in the gate (never set in Coolify)
|
||||
DATABASE_URI: `mongodb://127.0.0.1:${mongoPort}/release-checkexample_dev`,
|
||||
IPAL_COOKIE_SCAN_TOKEN: 'release-gate-token-0123456789',
|
||||
IPAL_COOKIE_SCAN_URL: 'http://127.0.0.1:9',
|
||||
IPAL_IP_HEADER: 'x-forwarded-for',
|
||||
NEXT_PUBLIC_SERVER_URL: `http://localhost:${PORT}`,
|
||||
PAYLOAD_SECRET: readFileSync(join(site, '.env'), 'utf8').match(/^PAYLOAD_SECRET=(.+)$/m)?.[1] ?? '',
|
||||
}
|
||||
sh(site, 'pnpm', ['install', '--frozen-lockfile', '--ignore-workspace'], env)
|
||||
check('Coolify install: pnpm install --frozen-lockfile', true)
|
||||
sh(site, 'pnpm', ['seed'], { ...env, NODE_ENV: 'development' })
|
||||
check('first seed of the new local _dev database (before launch)', true)
|
||||
sh(site, 'pnpm', ['generate:types'], env)
|
||||
sh(site, 'pnpm', ['build'], env)
|
||||
check('Coolify build: pnpm generate:types && pnpm build', true)
|
||||
|
||||
// 5. the documented targeted seed, in production mode, as in Coolify's Terminal
|
||||
const prod = { ...env, NODE_ENV: 'production' }
|
||||
sh(site, 'pnpm', ['seed'], { ...prod, SEED_DRY_RUN: '1', SEED_ONLY: 'pages:kontakt' })
|
||||
sh(site, 'pnpm', ['seed'], { ...prod, SEED_ONLY: 'pages:kontakt' })
|
||||
check('targeted seed in production mode: SEED_ONLY="pages:kontakt" [SEED_DRY_RUN=1] pnpm seed', true)
|
||||
// after launch: a run without SEED_ONLY on production must be refused by the plugin's guard
|
||||
const refused = sh(site, 'pnpm', ['seed'], prod, { allowFail: true })
|
||||
check('full seed on production (no SEED_ONLY) is refused', refused !== 0)
|
||||
|
||||
// 6. the production server
|
||||
log(`$ pnpm start (PORT=${PORT})`)
|
||||
server = spawn('pnpm', ['start'], { cwd: site, detached: true, env: { ...process.env, ...prod, PORT }, stdio: 'inherit' })
|
||||
const health = await waitFor(`http://127.0.0.1:${PORT}/api/health`, 90)
|
||||
check('GET /api/health', health === 200, String(health))
|
||||
const home = await fetch(`http://127.0.0.1:${PORT}/pl`)
|
||||
const headers = home.headers
|
||||
check('GET /pl', home.status === 200, String(home.status))
|
||||
check('CSP report-only, no X-Powered-By', headers.has('content-security-policy-report-only') && !headers.has('x-powered-by'))
|
||||
const llms = await (await fetch(`http://127.0.0.1:${PORT}/llms.txt`)).text()
|
||||
check('llms.txt names the site', llms.includes('Release Check'))
|
||||
|
||||
// 7. ipal-doctor, when this ipal-kit ships it
|
||||
if (existsSync(join(site, 'node_modules', '.bin', 'ipal-doctor'))) {
|
||||
const doctor = sh(site, 'pnpm', ['exec', 'ipal-doctor', '--strict', '--offline'], env, { allowFail: true })
|
||||
check('ipal-doctor --strict: zero findings', doctor === 0)
|
||||
} else {
|
||||
results.push({ detail: 'not in this ipal-kit yet', name: 'ipal-doctor --strict', ok: null })
|
||||
log('- ipal-doctor --strict — skipped: not in this ipal-kit yet')
|
||||
}
|
||||
|
||||
// 8. Coolify's build pack itself, when the nixpacks CLI is available
|
||||
if (out('sh', ['-c', 'command -v nixpacks'])) {
|
||||
const image = `ipal-starter-gate-site-${process.pid}`
|
||||
sh(site, 'nixpacks', ['build', '.', '--name', image, '--install-cmd', 'pnpm install --frozen-lockfile', '--build-cmd', 'pnpm generate:types && pnpm build', '--start-cmd', 'pnpm start'], env)
|
||||
const mongoIp = out('docker', ['inspect', '-f', '{{.NetworkSettings.IPAddress}}', mongoName])
|
||||
sh(site, 'docker', ['run', '--rm', '-e', `DATABASE_URI=mongodb://${mongoIp}:27017/release-checkexample_dev`, '-e', `PAYLOAD_SECRET=${env.PAYLOAD_SECRET}`, '-e', 'SEED_ONLY=pages:kontakt', '-e', 'SEED_DRY_RUN=1', '-e', 'NODE_ENV=production', image, 'pnpm', 'seed'])
|
||||
sh(site, 'docker', ['rmi', image], {}, { allowFail: true })
|
||||
check('targeted seed inside the Nixpacks image', true)
|
||||
} else {
|
||||
results.push({ detail: 'nixpacks CLI not on PATH; the same commands ran on the host', name: 'Nixpacks image', ok: null })
|
||||
log('- Nixpacks image — skipped: nixpacks CLI not on PATH (the same commands ran on the host)')
|
||||
}
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
if (server?.pid) {
|
||||
try {
|
||||
process.kill(-server.pid, 'SIGTERM')
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
}
|
||||
if (mongoStarted) {spawnSync('docker', ['stop', mongoName], { stdio: 'ignore' })}
|
||||
if (!keep) {rmSync(work, { force: true, recursive: true })}
|
||||
}
|
||||
|
||||
let failed = false
|
||||
try {
|
||||
await main()
|
||||
} catch (error) {
|
||||
failed = true
|
||||
console.error(`[starter:gate] ${error.message}`)
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
log(`${failed ? 'FAILED' : 'passed'}: ${results.filter((r) => r.ok).length} checks passed, ${results.filter((r) => r.ok === null).length} skipped`)
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/starter
|
||||
*
|
||||
* The building blocks of `ipal-kit create` (docs/project-starter.md): the answers schema, the variant and
|
||||
* placeholder transforms, the bundle and the renderer — Node built-ins only, no Payload. Use them to script
|
||||
* your own generator or to check a reference tree; the command itself is `pnpm dlx @intecion/ipal-kit create`.
|
||||
*/
|
||||
export { flagsFromAnswers, STARTER_TOPICS, validateAnswers } from '../modules/starter/answers.js'
|
||||
export type { AnalyticsTool, ContentCollection, StarterAnswers } from '../modules/starter/answers.js'
|
||||
export { bundleFlags, collectBundle, packBundle, unpackBundle } from '../modules/starter/bundle.js'
|
||||
export type { StarterBundle } from '../modules/starter/bundle.js'
|
||||
export { CREATE_USAGE, localEnv, normalizeDomain, parseCreateArgs, runCreateCli } from '../modules/starter/cli.js'
|
||||
export {
|
||||
fontExport,
|
||||
renderAgentsMd,
|
||||
renderDecisions,
|
||||
renderDesignMd,
|
||||
renderDoctorConfig,
|
||||
renderI18nConfig,
|
||||
renderTokens,
|
||||
rewriteFonts,
|
||||
rewritePackageJson,
|
||||
} from '../modules/starter/generate.js'
|
||||
export type { SiteContext } from '../modules/starter/generate.js'
|
||||
export { lockfileWithoutPlugin } from '../modules/starter/lockfile.js'
|
||||
export { ALWAYS_SKIPPED, assertManifest, fileRole, matchGlob } from '../modules/starter/manifest.js'
|
||||
export type { FileRole, StarterManifest } from '../modules/starter/manifest.js'
|
||||
export { askAnswers } from '../modules/starter/prompts.js'
|
||||
export { placeholderValues, renderSite } from '../modules/starter/render.js'
|
||||
export { secretFindings } from '../modules/starter/secrets.js'
|
||||
export { applyPlaceholders, applyVariants, leftoverFakes, variantFlags } from '../modules/starter/text.js'
|
||||
export type { StarterFlags } from '../modules/starter/text.js'
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* The architecture questions (AGENT.md "Ask before you build", ipal-setup stage 0) as data:
|
||||
* the shape of `--answers <file.json>`, validation, and the flags the answers turn on.
|
||||
* Nothing here has a silent default — a missing answer is an error the owner must fill in.
|
||||
*/
|
||||
import type { StarterFlags } from './text.js'
|
||||
|
||||
export type AnalyticsTool = 'clarity' | 'ga4' | 'gtm' | 'linkedIn' | 'metaPixel' | 'tiktok'
|
||||
export type ContentCollection = 'caseStudies' | 'posts'
|
||||
|
||||
export type StarterAnswers = {
|
||||
admin: {
|
||||
adminMeta: boolean
|
||||
/** Required when `adminMeta` is false — goes to ipal-doctor.json and "Project decisions". */
|
||||
adminMetaOffReason?: string
|
||||
agency: 'intecion' | 'none' | { name: string; url: string }
|
||||
twoFactor: boolean
|
||||
twoFactorOffReason?: string
|
||||
whiteLabel: boolean
|
||||
}
|
||||
consent: {
|
||||
banner: 'detailed' | 'inline' | 'modal'
|
||||
consentMode: 'advanced' | 'basic'
|
||||
cookieScanner: boolean
|
||||
cookieScannerOffReason?: string
|
||||
/** Browser crawl through the shared cookie-crawler service (needs IPAL_COOKIE_SCAN_* in Coolify). */
|
||||
crawl: boolean
|
||||
tools: AnalyticsTool[]
|
||||
}
|
||||
content: {
|
||||
collections: ContentCollection[]
|
||||
/** The site map in the owner's words, one line per page. */
|
||||
pages: string[]
|
||||
}
|
||||
forms: {
|
||||
list: string[]
|
||||
/** Inbox that receives submissions (Company → E-mail). */
|
||||
recipient: string
|
||||
transport: 'graph' | 'smtp'
|
||||
}
|
||||
hosting: {
|
||||
/** Which host the site answers on; the other one redirects. */
|
||||
canonical: 'apex' | 'www'
|
||||
/** Coolify server / project, free text. */
|
||||
coolify: string
|
||||
dns: string
|
||||
}
|
||||
industry: string
|
||||
languages: {
|
||||
default: string
|
||||
locales: { code: string; label: string }[]
|
||||
}
|
||||
market: string
|
||||
media: 'local' | 'r2'
|
||||
seo: {
|
||||
aiBots: 'allow' | 'block-training' | 'disallow'
|
||||
aiBotsReason?: string
|
||||
localBusiness: { type: string } | false
|
||||
}
|
||||
siteName: string
|
||||
styling: {
|
||||
accent?: string
|
||||
defaultTheme: 'dark' | 'light' | 'system'
|
||||
fluid: 'standard' | 'wide'
|
||||
fontBody: string
|
||||
fontHeading: string
|
||||
primary: string
|
||||
radius: 'round' | 'sharp' | 'soft'
|
||||
secondary?: string
|
||||
theme: 'both' | 'dark' | 'light'
|
||||
}
|
||||
tooling: { external: string[] }
|
||||
}
|
||||
|
||||
/** One prompt per architecture topic, in the order of AGENT.md "Ask before you build". */
|
||||
export const STARTER_TOPICS = [
|
||||
'siteName', 'market', 'industry', 'languages', 'styling', 'content', 'forms', 'consent', 'seo', 'media', 'admin', 'hosting', 'tooling',
|
||||
] as const
|
||||
|
||||
const LOCALE = /^[a-z]{2}(?:-[A-Z]{2})?$/
|
||||
const EMAIL = /^[^\s@,;]+@[^\s,;@][^\s,.;@]*\.[^\s,;@]+$/
|
||||
const TOOLS: AnalyticsTool[] = ['clarity', 'ga4', 'gtm', 'linkedIn', 'metaPixel', 'tiktok']
|
||||
|
||||
const isText = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0
|
||||
const oneOf = <T extends string>(v: unknown, list: readonly T[]): v is T => typeof v === 'string' && (list as readonly string[]).includes(v)
|
||||
|
||||
/**
|
||||
* Every problem with the answers, as readable lines (empty = valid). Limits of this version are
|
||||
* errors too, so the generator never writes a site the reference cannot back.
|
||||
*/
|
||||
export function validateAnswers(input: unknown): string[] {
|
||||
const a = (input ?? {}) as Partial<StarterAnswers>
|
||||
const errors: string[] = []
|
||||
const need = (ok: boolean, message: string) => {if (!ok) {errors.push(message)}}
|
||||
|
||||
need(isText(a.siteName), 'siteName: the site / company name (also the 2FA issuer)')
|
||||
need(isText(a.market), 'market: e.g. PL, UK, AU')
|
||||
need(isText(a.industry), 'industry: one line, e.g. "architecture studio"')
|
||||
|
||||
const langs = a.languages
|
||||
const codes = Array.isArray(langs?.locales) ? langs.locales.map((l) => l?.code) : []
|
||||
need(codes.length > 0 && codes.every((c) => typeof c === 'string' && LOCALE.test(c)), 'languages.locales: [{ code: "pl", label: "Polski" }, …]')
|
||||
need(Array.isArray(langs?.locales) && langs.locales.every((l) => isText(l?.label)), 'languages.locales: every locale needs a label')
|
||||
need(new Set(codes).size === codes.length, 'languages.locales: a code is listed twice')
|
||||
// The base seed writes Polish and English text and Polish default-locale slugs (reference/src/seed/base.ts).
|
||||
need(langs?.default === 'pl' && codes.includes('en'), 'languages: this version needs default "pl" and "en" among the locales (the base seed is Polish + English); other sites → the manual ipal-setup path')
|
||||
|
||||
const st = a.styling
|
||||
need(isText(st?.primary), 'styling.primary: the brand colour (any CSS colour, oklch recommended)')
|
||||
need(isText(st?.fontBody) && isText(st?.fontHeading), 'styling.fontBody / fontHeading: Google font names, e.g. "Inter"')
|
||||
need(oneOf(st?.theme, ['both', 'dark', 'light'] as const), 'styling.theme: light | dark | both')
|
||||
need(oneOf(st?.defaultTheme, ['dark', 'light', 'system'] as const), 'styling.defaultTheme: light | dark | system')
|
||||
need(st?.theme !== 'light' || st.defaultTheme === 'light', 'styling: a light-only site has defaultTheme "light"')
|
||||
need(st?.theme !== 'dark' || st.defaultTheme === 'dark', 'styling: a dark-only site has defaultTheme "dark"')
|
||||
need(oneOf(st?.radius, ['round', 'sharp', 'soft'] as const), 'styling.radius: sharp | soft | round')
|
||||
need(oneOf(st?.fluid, ['standard', 'wide'] as const), 'styling.fluid: standard (to 1280px) | wide (to 1920px)')
|
||||
|
||||
need(Array.isArray(a.content?.pages) && a.content.pages.length > 0, 'content.pages: the site map, one entry per page')
|
||||
need(Array.isArray(a.content?.collections) && a.content.collections.every((c) => oneOf(c, ['caseStudies', 'posts'] as const)), 'content.collections: [] or any of "posts", "caseStudies"')
|
||||
|
||||
need(Array.isArray(a.forms?.list), 'forms.list: the forms, e.g. ["Contact form"]')
|
||||
need(isText(a.forms?.recipient) && EMAIL.test(a.forms.recipient), 'forms.recipient: the inbox that receives submissions')
|
||||
need(oneOf(a.forms?.transport, ['graph', 'smtp'] as const), 'forms.transport: smtp | graph')
|
||||
|
||||
const c = a.consent
|
||||
need(Array.isArray(c?.tools) && c.tools.every((t) => oneOf(t, TOOLS)), `consent.tools: any of ${TOOLS.join(', ')} (or [])`)
|
||||
need(oneOf(c?.consentMode, ['advanced', 'basic'] as const), 'consent.consentMode: advanced | basic')
|
||||
need(oneOf(c?.banner, ['detailed', 'inline', 'modal'] as const), 'consent.banner: inline | modal | detailed')
|
||||
need(typeof c?.cookieScanner === 'boolean', 'consent.cookieScanner: true | false')
|
||||
need(c?.cookieScanner !== false || isText(c.cookieScannerOffReason), 'consent.cookieScannerOffReason: the owner\'s reason for turning the scanner off')
|
||||
need(typeof c?.crawl === 'boolean', 'consent.crawl: true | false')
|
||||
need(!c?.crawl || c.cookieScanner === true, 'consent.crawl needs consent.cookieScanner')
|
||||
|
||||
const seo = a.seo
|
||||
need(oneOf(seo?.aiBots, ['allow', 'block-training', 'disallow'] as const), 'seo.aiBots: allow | block-training | disallow')
|
||||
need(seo?.aiBots === 'allow' || isText(seo?.aiBotsReason), 'seo.aiBotsReason: the client decision behind blocking AI bots')
|
||||
need(seo?.localBusiness === false || isText(seo?.localBusiness?.type), 'seo.localBusiness: false or { type: "ProfessionalService" }')
|
||||
|
||||
need(oneOf(a.media, ['local', 'r2'] as const), 'media: r2 | local')
|
||||
|
||||
const ad = a.admin
|
||||
need(typeof ad?.twoFactor === 'boolean', 'admin.twoFactor: true | false')
|
||||
need(ad?.twoFactor !== false || isText(ad.twoFactorOffReason), 'admin.twoFactorOffReason: the owner\'s reason for turning 2FA off')
|
||||
need(typeof ad?.whiteLabel === 'boolean', 'admin.whiteLabel: true | false')
|
||||
need(typeof ad?.adminMeta === 'boolean', 'admin.adminMeta: true | false')
|
||||
need(ad?.adminMeta !== false || isText(ad.adminMetaOffReason), 'admin.adminMetaOffReason: the owner\'s reason')
|
||||
const agency = ad?.agency
|
||||
need(agency === 'intecion' || agency === 'none' || (typeof agency === 'object' && isText(agency.name) && /^https:\/\//.test(agency.url)), 'admin.agency: "intecion" | "none" | { name, url: "https://…" }')
|
||||
|
||||
need(oneOf(a.hosting?.canonical, ['apex', 'www'] as const), 'hosting.canonical: apex | www')
|
||||
need(isText(a.hosting?.coolify), 'hosting.coolify: the Coolify server / project')
|
||||
need(isText(a.hosting?.dns), 'hosting.dns: who adds the DNS records')
|
||||
|
||||
need(Array.isArray(a.tooling?.external), 'tooling.external: [] or the ext-* skills to install')
|
||||
return errors
|
||||
}
|
||||
|
||||
/** The feature flags the reference site's `@starter:if` markers test. */
|
||||
export function flagsFromAnswers(a: StarterAnswers): StarterFlags {
|
||||
const tools = new Set(a.consent.tools)
|
||||
return {
|
||||
adminMeta: a.admin.adminMeta,
|
||||
agencyCustom: typeof a.admin.agency === 'object',
|
||||
agencyNone: a.admin.agency === 'none',
|
||||
aiBotsBlockTraining: a.seo.aiBots === 'block-training',
|
||||
aiBotsDisallow: a.seo.aiBots === 'disallow',
|
||||
analytics: tools.has('ga4') || tools.has('gtm'),
|
||||
bannerDetailed: a.consent.banner === 'detailed',
|
||||
bannerInline: a.consent.banner === 'inline',
|
||||
bannerModal: a.consent.banner === 'modal',
|
||||
caseStudies: a.content.collections.includes('caseStudies'),
|
||||
clarity: tools.has('clarity'),
|
||||
collections: a.content.collections.length > 0,
|
||||
consentBasic: a.consent.consentMode === 'basic',
|
||||
cookieScanner: a.consent.cookieScanner,
|
||||
crawl: a.consent.crawl,
|
||||
defaultDark: a.styling.defaultTheme === 'dark',
|
||||
defaultLight: a.styling.defaultTheme === 'light',
|
||||
defaultSystem: a.styling.defaultTheme === 'system',
|
||||
// the reference site's own demo content, smoke tests and showcase — never in a new site
|
||||
demo: false,
|
||||
enforceCsp: false, // new sites start report-only (security.md → ROLL OUT CSP)
|
||||
graph: a.forms.transport === 'graph',
|
||||
linkedIn: tools.has('linkedIn'),
|
||||
localBusiness: a.seo.localBusiness !== false,
|
||||
metaPixel: tools.has('metaPixel'),
|
||||
posts: a.content.collections.includes('posts'),
|
||||
r2: a.media === 'r2',
|
||||
scannerWithoutCrawl: a.consent.cookieScanner && !a.consent.crawl,
|
||||
themeToggle: a.styling.theme === 'both',
|
||||
tiktok: tools.has('tiktok'),
|
||||
twoFactor: a.admin.twoFactor,
|
||||
whiteLabel: a.admin.whiteLabel,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* The starter bundle: the reference site's kept files plus its manifest and lockfile, in one gzipped
|
||||
* JSON file shipped in the plugin tarball (`dist/starter/template.json.gz`). Built at release time
|
||||
* (`pnpm build:starter`); a checkout of the repo can read `reference/` directly instead.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
import { gunzipSync, gzipSync } from 'node:zlib'
|
||||
|
||||
import { lockfileWithoutPlugin } from './lockfile.js'
|
||||
import { assertManifest, fileRole, type StarterManifest } from './manifest.js'
|
||||
import { leftoverFakes, variantFlags } from './text.js'
|
||||
|
||||
export type StarterBundle = {
|
||||
/** path → content of every file the new site may get (kept, template and variant files). */
|
||||
files: Record<string, string>
|
||||
/** The reference lockfile without the plugin (lockfile.ts). */
|
||||
lockfile: string
|
||||
manifest: StarterManifest
|
||||
schema: 1
|
||||
}
|
||||
|
||||
const MANIFEST = 'starter.manifest.json'
|
||||
const LOCKFILE = 'pnpm-lock.yaml'
|
||||
|
||||
function walk(dir: string, root: string, out: string[]) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const full = join(dir, name)
|
||||
const rel = relative(root, full).split(sep).join('/')
|
||||
// never descend into installed or built trees
|
||||
if (name === 'node_modules' || name === '.next' || name === '.git') {continue}
|
||||
if (statSync(full).isDirectory()) {walk(full, root, out)}
|
||||
else {out.push(rel)}
|
||||
}
|
||||
}
|
||||
|
||||
/** Tracked files only when the folder is in a Git checkout (no local leftovers), else every file on disk. */
|
||||
function listFiles(dir: string): string[] {
|
||||
try {
|
||||
const out = execFileSync('git', ['ls-files', '-z', '--cached', '--', '.'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
|
||||
const tracked = out.split('\0').filter(Boolean)
|
||||
if (tracked.length) {return tracked.filter((path) => existsSync(join(dir, path)))}
|
||||
} catch {
|
||||
// not a Git checkout (e.g. an unpacked tarball) — fall back to the folder
|
||||
}
|
||||
const paths: string[] = []
|
||||
walk(dir, dir, paths)
|
||||
return paths
|
||||
}
|
||||
|
||||
/** Binary files are not part of the starter (media are seeded, never copied). */
|
||||
const isText = (content: Buffer) => !content.subarray(0, 8000).includes(0)
|
||||
|
||||
/**
|
||||
* Reads the reference site into a bundle. Fails when a kept file still holds a fake value
|
||||
* (it would leak "Example Studio" into a client site) or when a file is binary.
|
||||
*/
|
||||
export function collectBundle(referenceDir: string): StarterBundle {
|
||||
const manifestPath = join(referenceDir, MANIFEST)
|
||||
if (!existsSync(manifestPath)) {throw new Error(`no ${MANIFEST} in ${referenceDir}`)}
|
||||
const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
||||
assertManifest(manifest)
|
||||
const paths = listFiles(referenceDir)
|
||||
const files: Record<string, string> = {}
|
||||
const problems: string[] = []
|
||||
for (const path of paths.sort()) {
|
||||
if (path === MANIFEST || path === LOCKFILE) {continue}
|
||||
const role = fileRole(path, manifest)
|
||||
if (role === 'drop') {continue}
|
||||
const content = readFileSync(join(referenceDir, path))
|
||||
if (!isText(content)) {
|
||||
problems.push(`${path}: binary file — drop it in the manifest`)
|
||||
continue
|
||||
}
|
||||
const text = content.toString('utf8')
|
||||
if (role === 'keep') {
|
||||
// a kept file is copied as is, so it must not carry the reference company's values
|
||||
const fakes = leftoverFakes(text, manifest.placeholders)
|
||||
if (fakes.length) {problems.push(`${path}: kept as is but contains ${fakes.join(', ')} — list it under "template"`)}
|
||||
}
|
||||
files[path] = text
|
||||
}
|
||||
if (problems.length) {throw new Error(`starter bundle:\n ${problems.join('\n ')}`)}
|
||||
const lockPath = join(referenceDir, LOCKFILE)
|
||||
if (!existsSync(lockPath)) {throw new Error(`no ${LOCKFILE} in ${referenceDir}`)}
|
||||
return { files, lockfile: lockfileWithoutPlugin(readFileSync(lockPath, 'utf8')), manifest, schema: 1 }
|
||||
}
|
||||
|
||||
/** Every flag the bundle's markers and file variants use — the generator must set each one. */
|
||||
export function bundleFlags(bundle: StarterBundle): string[] {
|
||||
const flags = new Set<string>()
|
||||
for (const text of Object.values(bundle.files)) {for (const flag of variantFlags(text)) {flags.add(flag)}}
|
||||
for (const expr of Object.values(bundle.manifest.variants ?? {})) {flags.add(expr.replace(/^!/, ''))}
|
||||
return [...flags].sort()
|
||||
}
|
||||
|
||||
export function packBundle(bundle: StarterBundle): Buffer {
|
||||
return gzipSync(Buffer.from(JSON.stringify(bundle)), { level: 9 })
|
||||
}
|
||||
|
||||
export function unpackBundle(data: Buffer): StarterBundle {
|
||||
const bundle = JSON.parse(gunzipSync(data).toString('utf8')) as StarterBundle
|
||||
if (bundle.schema !== 1) {throw new Error('starter bundle: unknown schema — use the ipal-kit version that built it')}
|
||||
return bundle
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* `ipal-kit create <domain>` — a new client site from the reference site, following every team
|
||||
* convention (docs/project-starter.md). Run with `pnpm dlx @intecion/ipal-kit@<version> create <domain>`.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, relative, resolve } from 'node:path'
|
||||
import { domainToASCII, fileURLToPath } from 'node:url'
|
||||
|
||||
import type { SiteContext } from './generate.js'
|
||||
|
||||
import { databaseNamesFor } from '../env/databaseName.js'
|
||||
import { type StarterAnswers, validateAnswers } from './answers.js'
|
||||
import { collectBundle, type StarterBundle, unpackBundle } from './bundle.js'
|
||||
import { askInTerminal } from './prompts.js'
|
||||
import { renderSite } from './render.js'
|
||||
import { secretFindings } from './secrets.js'
|
||||
|
||||
export const CREATE_USAGE = `Usage: ipal-kit create <domain> [options]
|
||||
pnpm dlx @intecion/ipal-kit@<version> create intecion.com
|
||||
|
||||
--dir <path> target folder (default ./<domain without dots>-web); must be new or empty
|
||||
--answers <file> the architecture answers as JSON (agents, CI) — no questions asked
|
||||
--external [a,b] also install the vendored ext-* skills (all, or the listed ones)
|
||||
--no-install write the files only; print the remaining steps
|
||||
--no-git no git init / first commit
|
||||
--dry-run print the decisions and the file list, write nothing
|
||||
--plugin-spec <spec> install @intecion/ipal-kit from this spec (release checks: a packed tarball)`
|
||||
|
||||
type Log = (line: string) => void
|
||||
|
||||
type CreateOptions = {
|
||||
answersFile?: string
|
||||
dir?: string
|
||||
domain: string
|
||||
dryRun: boolean
|
||||
external: null | string[]
|
||||
git: boolean
|
||||
install: boolean
|
||||
pluginSpec?: string
|
||||
}
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
// dist/modules/starter → package root
|
||||
const pkgRoot = resolve(here, '..', '..', '..')
|
||||
|
||||
function value(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name)
|
||||
if (i < 0) {return undefined}
|
||||
const next = args[i + 1]
|
||||
if (!next || next.startsWith('--')) {throw new Error(`${name} needs a value`)}
|
||||
return next
|
||||
}
|
||||
|
||||
export function parseCreateArgs(args: string[]): CreateOptions {
|
||||
const domain = args.find((arg, i) => !arg.startsWith('--') && !['--answers', '--dir', '--external', '--plugin-spec'].includes(args[i - 1] ?? ''))
|
||||
if (!domain) {throw new Error('the production domain is required, e.g. `ipal-kit create intecion.com`')}
|
||||
const ext = args.indexOf('--external')
|
||||
const extNext = ext >= 0 ? args[ext + 1] : undefined
|
||||
return {
|
||||
answersFile: value(args, '--answers'),
|
||||
dir: value(args, '--dir'),
|
||||
domain,
|
||||
dryRun: args.includes('--dry-run'),
|
||||
external: ext < 0 ? null : extNext && !extNext.startsWith('--') && extNext !== domain ? extNext.split(',').map((s) => s.trim()).filter(Boolean) : [],
|
||||
git: !args.includes('--no-git'),
|
||||
install: !args.includes('--no-install'),
|
||||
pluginSpec: value(args, '--plugin-spec'),
|
||||
}
|
||||
}
|
||||
|
||||
/** `https://www.Intecion.com/` → `intecion.com` (punycode for IDN); throws on anything that is not a domain. */
|
||||
export function normalizeDomain(input: string): string {
|
||||
const host = input.trim().toLowerCase().replace(/^[a-z][a-z\d+.-]*:\/\//, '').replace(/[/:?#].*$/, '').replace(/^www\./, '')
|
||||
const ascii = domainToASCII(host)
|
||||
if (!ascii || !/^(?:[a-z\d](?:[a-z\d-]*[a-z\d])?\.)+[a-z\d-]{2,}$/.test(ascii)) {throw new Error(`"${input}" is not a domain (e.g. intecion.com)`)}
|
||||
return ascii
|
||||
}
|
||||
|
||||
function loadBundle(): StarterBundle {
|
||||
const packed = join(pkgRoot, 'dist', 'starter', 'template.json.gz')
|
||||
if (existsSync(packed)) {return unpackBundle(readFileSync(packed))}
|
||||
// a checkout of the plugin repo: read the reference site directly
|
||||
const reference = join(pkgRoot, 'reference')
|
||||
if (existsSync(join(reference, 'starter.manifest.json'))) {return collectBundle(reference)}
|
||||
throw new Error('no starter templates in this ipal-kit (dist/starter/template.json.gz) — use a released version')
|
||||
}
|
||||
|
||||
function pluginVersion(): string {
|
||||
return (JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { version: string }).version
|
||||
}
|
||||
|
||||
function run(log: Log, cwd: string, command: string, args: string[], env: Record<string, string> = {}): boolean {
|
||||
log(`$ ${[command, ...args].join(' ')}`)
|
||||
const result = spawnSync(command, args, { cwd, env: { ...process.env, ...env }, stdio: 'inherit' })
|
||||
return result.status === 0
|
||||
}
|
||||
|
||||
function writeFiles(dir: string, files: Record<string, string>) {
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
const target = join(dir, path)
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
writeFileSync(target, content)
|
||||
}
|
||||
}
|
||||
|
||||
/** The local `.env`: `.env.example` with a fresh PAYLOAD_SECRET. Never committed (.gitignore). */
|
||||
export function localEnv(example: string): string {
|
||||
return example.replace(/^PAYLOAD_SECRET=.*$/m, `PAYLOAD_SECRET=${randomBytes(48).toString('base64url')}`)
|
||||
}
|
||||
|
||||
function committedFiles(dir: string): Record<string, string> {
|
||||
const listed = spawnSync('git', ['diff', '--cached', '--name-only', '-z'], { cwd: dir, encoding: 'utf8' }).stdout ?? ''
|
||||
const files: Record<string, string> = {}
|
||||
for (const path of listed.split('\0').filter(Boolean)) {files[path] = readFileSync(join(dir, path), 'utf8')}
|
||||
return files
|
||||
}
|
||||
|
||||
async function readAnswers(options: CreateOptions): Promise<StarterAnswers> {
|
||||
const answers = options.answersFile
|
||||
? (JSON.parse(readFileSync(resolve(options.answersFile), 'utf8')) as StarterAnswers)
|
||||
: await askInTerminal()
|
||||
if (options.external?.length && answers.tooling) {answers.tooling.external = options.external}
|
||||
return answers
|
||||
}
|
||||
|
||||
export async function runCreateCli(args: string[], log: Log = (line) => process.stdout.write(`${line}\n`)): Promise<number> {
|
||||
if (args.includes('--help') || args.includes('-h') || !args.length) {
|
||||
log(CREATE_USAGE)
|
||||
return args.length ? 0 : 1
|
||||
}
|
||||
let options: CreateOptions
|
||||
let domain: string
|
||||
try {
|
||||
options = parseCreateArgs(args)
|
||||
domain = normalizeDomain(options.domain)
|
||||
} catch (error) {
|
||||
log(`ipal-kit create: ${(error as Error).message}\n\n${CREATE_USAGE}`)
|
||||
return 1
|
||||
}
|
||||
const flat = domain.replace(/\./g, '')
|
||||
const cwd = process.cwd()
|
||||
const dir = resolve(options.dir ?? `${flat}-web`)
|
||||
if (existsSync(dir) && readdirSync(dir).length) {
|
||||
log(`ipal-kit create: ${dir} is not empty — pick a new folder with --dir`)
|
||||
return 1
|
||||
}
|
||||
if (!options.dir && existsSync(join(cwd, 'package.json'))) {
|
||||
log('ipal-kit create: this folder is a project — pass --dir ../<name>-web to create the site next to it')
|
||||
return 1
|
||||
}
|
||||
|
||||
const answers = await readAnswers(options)
|
||||
const errors = validateAnswers(answers)
|
||||
if (errors.length) {
|
||||
log(`ipal-kit create: the answers are incomplete — nothing was written:\n - ${errors.join('\n - ')}`)
|
||||
return 1
|
||||
}
|
||||
const ctx: SiteContext = {
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
dbNames: databaseNamesFor(domain),
|
||||
domain,
|
||||
pluginVersion: pluginVersion(),
|
||||
serverUrl: `https://${answers.hosting.canonical === 'www' ? 'www.' : ''}${domain}`,
|
||||
}
|
||||
let files: Record<string, string>
|
||||
try {
|
||||
files = renderSite(loadBundle(), answers, ctx)
|
||||
} catch (error) {
|
||||
log(`ipal-kit create: ${(error as Error).message}`)
|
||||
return 1
|
||||
}
|
||||
if (options.pluginSpec) {
|
||||
const pkg = JSON.parse(files['package.json'] ?? '{}') as { dependencies: Record<string, string> }
|
||||
pkg.dependencies['@intecion/ipal-kit'] = options.pluginSpec
|
||||
files['package.json'] = `${JSON.stringify(pkg, null, 2)}\n`
|
||||
}
|
||||
if (options.dryRun) {
|
||||
log(`Would create ${dir} (${Object.keys(files).length} files) for ${domain}:`)
|
||||
for (const path of Object.keys(files).sort()) {log(` ${path}`)}
|
||||
log(`\nDatabases: ${ctx.dbNames.dev} (local) / ${ctx.dbNames.prod} (Coolify)`)
|
||||
return 0
|
||||
}
|
||||
|
||||
writeFiles(dir, files)
|
||||
writeFileSync(join(dir, '.env'), localEnv(files['.env.example'] ?? ''))
|
||||
log(`Wrote ${Object.keys(files).length} files to ${relative(cwd, dir) || '.'}`)
|
||||
|
||||
const failed: string[] = []
|
||||
const step = (name: string, command: string, stepArgs: string[], env?: Record<string, string>) => {
|
||||
if (!run(log, dir, command, stepArgs, env)) {failed.push(name)}
|
||||
}
|
||||
if (options.install) {
|
||||
step('install', 'pnpm', ['install', '--ignore-workspace'])
|
||||
if (!failed.length) {
|
||||
step('skills', 'pnpm', ['exec', 'ipal-skills', ...(answers.tooling.external.length ? ['--external', answers.tooling.external.join(',')] : [])])
|
||||
step('tokens (contrast check)', 'pnpm', ['exec', 'ipal-tokens'])
|
||||
step('types', 'pnpm', ['generate:types'])
|
||||
step('import map', 'pnpm', ['generate:importmap'])
|
||||
step('typecheck', 'pnpm', ['typecheck'])
|
||||
if (existsSync(join(dir, 'node_modules', '.bin', 'ipal-doctor'))) {step('ipal-doctor', 'pnpm', ['exec', 'ipal-doctor', '--strict', '--offline'])}
|
||||
else {log('ipal-doctor is not in this ipal-kit version yet — run it once it ships.')}
|
||||
}
|
||||
}
|
||||
if (options.git && !failed.length) {
|
||||
step('git init', 'git', ['init', '-q', '-b', 'main'])
|
||||
step('git add', 'git', ['add', '-A'])
|
||||
const findings = secretFindings(committedFiles(dir))
|
||||
if (findings.length) {
|
||||
log(`Not committed — possible secrets:\n ${findings.join('\n ')}`)
|
||||
failed.push('secret check')
|
||||
} else {
|
||||
step('first commit', 'git', ['commit', '-q', '-m', `chore: create site with ipal-kit create ${ctx.pluginVersion}`])
|
||||
}
|
||||
}
|
||||
log(report(answers, ctx, dir, options, failed))
|
||||
return failed.length ? 1 : 0
|
||||
}
|
||||
|
||||
function report(a: StarterAnswers, ctx: SiteContext, dir: string, options: CreateOptions, failed: string[]): string {
|
||||
const lines = [
|
||||
'',
|
||||
failed.length ? `Created with problems in: ${failed.join(', ')} — fix them, then rerun the step.` : `Created ${ctx.domain} in ${dir}.`,
|
||||
'',
|
||||
'Next:',
|
||||
...(options.install ? [] : [' pnpm install && pnpm exec ipal-skills && pnpm exec ipal-tokens && pnpm generate:types && pnpm generate:importmap']),
|
||||
` 1. Local MongoDB with the database ${ctx.dbNames.dev} (DATABASE_URI in .env), then: pnpm dev`,
|
||||
` 2. pnpm seed (system pages, navigation, the forms to ${a.forms.recipient} — before launch only), then /admin → first user + 2FA`,
|
||||
' 3. Panel steps and the full checklist: .agents/skills/ipal-setup/SKILL.md §11; architecture answers: AGENTS.md',
|
||||
` 4. Deploy: docs/DEPLOY.md — Coolify app from the repo, MongoDB resource ${ctx.dbNames.prod}, DNS records for ${ctx.domain}`,
|
||||
...(a.consent.crawl ? [' 5. Coolify env: IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN (shared cookie-crawler)'] : []),
|
||||
]
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* Files and sections the starter writes from the answers instead of copying them from the reference
|
||||
* site: the language list, the brand tokens and DESIGN.md, the AGENTS.md decisions, ipal-doctor.json,
|
||||
* the fonts in the root layout and the package.json rewrite.
|
||||
*/
|
||||
import type { StarterAnswers } from './answers.js'
|
||||
|
||||
export type SiteContext = {
|
||||
/** `YYYY-MM-DD`, the day the site is created. */
|
||||
date: string
|
||||
dbNames: { dev: string; prod: string }
|
||||
domain: string
|
||||
/** The exact ipal-kit version written into package.json. */
|
||||
pluginVersion: string
|
||||
serverUrl: string
|
||||
}
|
||||
|
||||
const q = (value: string) => `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
|
||||
|
||||
export function renderI18nConfig(a: StarterAnswers): string {
|
||||
const locales = a.languages.locales.map((l) => ` { code: ${q(l.code)}, label: ${q(l.label)} },`).join('\n')
|
||||
return `import type { I18nConfig } from '@intecion/ipal-kit'
|
||||
|
||||
/** The ONLY source of languages (AGENT.md §3). Every language has a URL prefix: ${a.languages.locales.map((l) => `/${l.code}/…`).join(', ')}. */
|
||||
export const i18nConfig = {
|
||||
defaultLocale: ${q(a.languages.default)},
|
||||
locales: [
|
||||
${locales}
|
||||
],
|
||||
} as const satisfies I18nConfig
|
||||
|
||||
export type Locale = (typeof i18nConfig.locales)[number]['code']
|
||||
`
|
||||
}
|
||||
|
||||
const RADIUS = { round: { card: '1.25rem', control: '999px' }, sharp: { card: '0.25rem', control: '0.25rem' }, soft: { card: '0.75rem', control: '0.5rem' } }
|
||||
|
||||
export function renderTokens(a: StarterAnswers): string {
|
||||
const s = a.styling
|
||||
const light = [` primary: ${q(s.primary)},`]
|
||||
if (s.secondary) {light.push(` secondary: ${q(s.secondary)},`)}
|
||||
if (s.accent) {light.push(` accent: ${q(s.accent)},`)}
|
||||
const radius = RADIUS[s.radius]
|
||||
return `// src/design/tokens.ts — the ONLY file edited to rebrand the site (docs/design-tokens.md).
|
||||
// After every change: \`pnpm tokens\` → writes src/design/tokens.css (commit it) and prints the WCAG contrast check.
|
||||
// Leave out anything the brand does not change: the neutral defaults in @intecion/ipal-kit/tokens.css apply.
|
||||
import { defineTokens } from '@intecion/ipal-kit/tokens'
|
||||
|
||||
export const tokens = defineTokens({
|
||||
theme: ${q(s.theme)}, // must match Site settings → Theme
|
||||
fluid: ${q(s.fluid)},
|
||||
color: {
|
||||
light: {
|
||||
${light.join('\n')}
|
||||
},
|
||||
dark: {
|
||||
// brand roles carry over from light; set a lighter primary here if the contrast report fails
|
||||
},
|
||||
},
|
||||
radius: { card: ${q(radius.card)}, control: ${q(radius.control)} }, // "${s.radius}"
|
||||
})
|
||||
`
|
||||
}
|
||||
|
||||
export function renderDesignMd(a: StarterAnswers): string {
|
||||
const s = a.styling
|
||||
const radius = RADIUS[s.radius]
|
||||
const toggle = s.theme === 'both' ? 'yes' : 'no'
|
||||
return `# DESIGN.md — ${a.siteName}
|
||||
|
||||
The human source of the look. Its machine form is \`src/design/tokens.ts\`; the two must agree
|
||||
(\`ipal-doctor\` compares them). Values go into \`tokens.ts\`, never into components.
|
||||
Sections are fixed: fill every one, write "default" where the brand keeps the standard.
|
||||
|
||||
## 1. Brand in one sentence
|
||||
[TO FILL: what the site is, for whom, the feeling]. Industry: ${a.industry}. Market: ${a.market}.
|
||||
The one memorable element (where the boldness goes): [TO FILL]. Everything else stays quiet.
|
||||
|
||||
## 2. Colour
|
||||
| Role (\`--ipal-*\`) | Light | Dark | Used for |
|
||||
|---|---|---|---|
|
||||
| primary | ${s.primary} | (carried over) | main buttons, key accents |
|
||||
| secondary | ${s.secondary ?? 'default'} | default | second button |
|
||||
| accent | ${s.accent ?? 'default (= primary)'} | | badges, highlights |
|
||||
| bg / surface / surface-muted | default | default | page, cards, alternate sections |
|
||||
|
||||
Contrast (paste \`pnpm exec ipal-tokens --report\`; every ✗ fixed before launch):
|
||||
\`\`\`
|
||||
[TO FILL: report]
|
||||
\`\`\`
|
||||
|
||||
## 3. Type
|
||||
Body: ${s.fontBody} (\`--font-family-body\`). Headings: ${s.fontHeading} (\`--font-family-heading\`).
|
||||
Max 2 families × 2–3 weights, \`subsets: ['latin', 'latin-ext']\`. Scale overrides (\`fs\`): none.
|
||||
|
||||
## 4. Shape and depth
|
||||
Radius: "${s.radius}" — control ${radius.control}, card ${radius.card}, media default. Depth: [TO FILL].
|
||||
|
||||
## 5. Layout
|
||||
Scale: ${s.fluid === 'wide' ? 'fluid-wide (to 1920px)' : 'fluid (to 1280px)'}. Container default, narrow default (legal, articles), measure 68ch.
|
||||
Section rhythm: py-section; compact bands py-section-sm.
|
||||
|
||||
## 6. Motion
|
||||
Durations: default (fast 150 / base 250 / slow 400 ms). Reduced motion: every duration token is 0 ms.
|
||||
|
||||
## 7. Imagery and icons
|
||||
Photo style: [TO FILL]. Focal points set in Media. Icons: lucide set.
|
||||
|
||||
## 8. Theme
|
||||
${s.theme === 'both' ? 'light and dark' : `${s.theme} only`}, default ${s.defaultTheme} (Site settings → Theme), toggle ${toggle}.
|
||||
|
||||
## 9. Deviations from the standard
|
||||
- none
|
||||
`
|
||||
}
|
||||
|
||||
const yesNo = (v: boolean) => (v ? 'on' : 'off')
|
||||
|
||||
function agencyText(agency: StarterAnswers['admin']['agency']): string {
|
||||
if (agency === 'intecion') {return 'Intecion technology credit (default)'}
|
||||
if (agency === 'none') {return 'no agency credit (`agency: false`)'}
|
||||
return `agency credit ${agency.name} (${agency.url})`
|
||||
}
|
||||
|
||||
/** The "Project decisions" lines — one per architecture topic, the owner's answers only. */
|
||||
export function renderDecisions(a: StarterAnswers, ctx: SiteContext): string {
|
||||
const lines = [
|
||||
`- Languages: ${a.languages.locales.map((l) => l.code).join(', ')} (default ${a.languages.default}), every language with a URL prefix; \`/\` redirects to \`/${a.languages.default}\`.`,
|
||||
`- Styling: the ipal-kit token standard (\`src/design/tokens.ts\` → \`pnpm tokens\`); primary ${a.styling.primary}${a.styling.secondary ? `, secondary ${a.styling.secondary}` : ''}${a.styling.accent ? `, accent ${a.styling.accent}` : ''}; ${a.styling.fontBody} (body) + ${a.styling.fontHeading} (headings); radius ${a.styling.radius}; ${a.styling.fluid === 'wide' ? 'fluid-wide' : 'fluid'}; theme ${a.styling.theme}, default ${a.styling.defaultTheme}.`,
|
||||
`- Pages and content: ${a.content.pages.join('; ')}. Collections: ${a.content.collections.length ? a.content.collections.join(', ') : 'none'}.`,
|
||||
`- Forms: ${a.forms.list.length ? a.forms.list.join(', ') : 'none'}; submissions to ${a.forms.recipient}; e-mail via ${a.forms.transport === 'graph' ? 'Microsoft Graph' : 'SMTP from Site integrations'}; Turnstile on.`,
|
||||
`- Analytics and consent: ${a.consent.tools.length ? a.consent.tools.join(', ') : 'no analytics tools'}; Consent Mode ${a.consent.consentMode}; banner \`settings="${a.consent.banner}"\`; consent log on; cookie scanner ${yesNo(a.consent.cookieScanner)}${a.consent.cookieScanner ? `, crawl ${yesNo(a.consent.crawl)}` : ` — ${a.consent.cookieScannerOffReason}`}.`,
|
||||
`- SEO/GEO: market ${a.market}; ${a.seo.localBusiness ? `local business (${a.seo.localBusiness.type} JSON-LD from the Company global)` : 'no local business'}; llms.txt, llms-full.txt, Markdown and MCP on; AI bots ${a.seo.aiBots}${a.seo.aiBots === 'allow' ? '' : ` — ${a.seo.aiBotsReason}`}.`,
|
||||
`- Database and media: MongoDB only; database names from \`databaseNamesFor('${ctx.domain}')\` → \`${ctx.dbNames.dev}\` / \`${ctx.dbNames.prod}\`; media ${a.media === 'r2' ? 'on Cloudflare R2 in production (R2_PUBLIC_URL empty = served by the app), local disk in dev' : 'on local disk — a Coolify persistent volume in production'}.`,
|
||||
`- Admin: 2FA ${a.admin.twoFactor ? `on (issuer "${a.siteName}")` : `off — ${a.admin.twoFactorOffReason}`}; white-label ${yesNo(a.admin.whiteLabel)}; adminMeta ${a.admin.adminMeta ? 'on' : `off — ${a.admin.adminMetaOffReason}`}; ${agencyText(a.admin.agency)}.`,
|
||||
`- Hosting: Coolify (${a.hosting.coolify}) — build and check locally, Coolify builds the app from the repo with its default build pack, MongoDB is a separate Coolify resource on the same Docker network; no Dockerfile (docs/DEPLOY.md). Canonical ${ctx.serverUrl}${a.hosting.canonical === 'www' ? ' (apex redirects to www)' : ' (www redirects to apex)'}. DNS: ${a.hosting.dns}.`,
|
||||
`- CSP: report-only at the start; switch to \`mode: 'enforce'\` in next.config.ts once the \`[csp]\` reports are clean (security.md → ROLL OUT CSP).`,
|
||||
'- Approved exception: the `/design` styleguide has its labels in code (token names, a technical page, noindex) — the "texts from the panel" rule does not apply to it.',
|
||||
'- Approved exception: `ALLOW_LOCAL_MEDIA=1` (instrumentation.ts, next.config.ts) lets a production build run without R2 for local checks and CI only; never set in Coolify.',
|
||||
`- Agent tooling: skills in \`.agents/skills\`${a.tooling.external.length ? `; external skills ${a.tooling.external.join(', ')}` : '; no external skills'}.`,
|
||||
`- Created with \`ipal-kit create\` ${ctx.pluginVersion} on ${ctx.date}.`,
|
||||
]
|
||||
const skip = auditSkips(a)
|
||||
if (skip.length) {lines.push(`- ipal-audit-skip: ${skip.map((s) => s.key).join(', ')} — ${skip.map((s) => s.reason).join('; ')}`)}
|
||||
return `## Project decisions\n${lines.join('\n')}\n`
|
||||
}
|
||||
|
||||
/** Modules the owner turned off: the `ipal-audit-skip` keys and the matching ipal-doctor rules. */
|
||||
function auditSkips(a: StarterAnswers): { doctor?: string; key: string; reason: string }[] {
|
||||
const out: { doctor?: string; key: string; reason: string }[] = []
|
||||
if (!a.admin.twoFactor) {out.push({ doctor: '2fa', key: 'twofactor', reason: a.admin.twoFactorOffReason ?? '' })}
|
||||
if (a.media === 'local') {out.push({ key: 'r2', reason: 'media on a Coolify persistent volume (owner\'s choice)' })}
|
||||
if (a.seo.aiBots !== 'allow') {out.push({ key: 'aibots', reason: a.seo.aiBotsReason ?? '' })}
|
||||
return out
|
||||
}
|
||||
|
||||
/** AGENTS.md: the reference header and site map replaced, the decisions block filled from the answers. */
|
||||
export function renderAgentsMd(reference: string, a: StarterAnswers, ctx: SiteContext): string {
|
||||
const start = '<!-- starter:decisions -->'
|
||||
const end = '<!-- /starter:decisions -->'
|
||||
const from = reference.indexOf(start)
|
||||
const to = reference.indexOf(end)
|
||||
const rules = reference.indexOf('## Rules')
|
||||
const map = reference.indexOf('## Site map')
|
||||
if (from < 0 || to < from || rules < 0 || map < rules || map > from) {
|
||||
throw new Error('reference AGENTS.md: expected "## Rules", "## Site map" and the <!-- starter:decisions --> block, in that order')
|
||||
}
|
||||
const header = `# AGENTS.md
|
||||
|
||||
**Project:** ${a.siteName} · ${ctx.domain} · market ${a.market} · industry ${a.industry}
|
||||
**Languages:** ${a.languages.locales.map((l) => (l.code === a.languages.default ? `${l.code} (default)` : l.code)).join(', ')} · **Media:** ${a.media === 'r2' ? 'R2' : 'local disk (Coolify volume)'} · **Email:** ${a.forms.transport === 'graph' ? 'Microsoft Graph' : 'SMTP from Site integrations'}
|
||||
|
||||
`
|
||||
const siteMap = `## Site map\n${a.content.pages.map((p) => `- ${p}`).join('\n')}\n\n`
|
||||
return header + reference.slice(rules, map) + siteMap + start + '\n' + renderDecisions(a, ctx) + reference.slice(to)
|
||||
}
|
||||
|
||||
/** ipal-doctor.json: the domain, not launched yet, and every deliberate difference silenced with its reason. */
|
||||
export function renderDoctorConfig(a: StarterAnswers, ctx: SiteContext): string {
|
||||
const until = new Date(`${ctx.date}T00:00:00Z`)
|
||||
until.setUTCDate(until.getUTCDate() + 28)
|
||||
const rules: Record<string, { off: true; reason: string; until?: string }> = {
|
||||
csp: { off: true, reason: 'report-only at the start; switch to enforce once the [csp] reports are clean (security.md → ROLL OUT CSP)', until: until.toISOString().slice(0, 10) },
|
||||
}
|
||||
for (const skip of auditSkips(a)) {
|
||||
if (skip.doctor) {rules[skip.doctor] = { off: true, reason: skip.reason }}
|
||||
}
|
||||
if (!a.consent.cookieScanner) {rules['cookie-scanner'] = { off: true, reason: a.consent.cookieScannerOffReason ?? '' }}
|
||||
if (!a.admin.adminMeta) {rules['admin-meta'] = { off: true, reason: a.admin.adminMetaOffReason ?? '' }}
|
||||
else if (a.admin.agency === 'none') {rules['admin-meta'] = { off: true, reason: 'no agency credit (owner\'s choice)' }}
|
||||
return `${JSON.stringify({ domain: ctx.domain, launched: false, rules }, null, 2)}\n`
|
||||
}
|
||||
|
||||
/** `Open Sans` → `Open_Sans` (the next/font/google export name). */
|
||||
export function fontExport(name: string): string {
|
||||
return name.trim().replace(/\s+/g, '_')
|
||||
}
|
||||
|
||||
/** Points the root layout's two next/font calls (`const body = X(…)`, `const heading = Y(…)`) at the answered fonts. */
|
||||
export function rewriteFonts(layout: string, a: StarterAnswers): string {
|
||||
const body = fontExport(a.styling.fontBody)
|
||||
const heading = fontExport(a.styling.fontHeading)
|
||||
const importLine = /^import \{[^}]*\} from 'next\/font\/google'$/m
|
||||
const bodyCall = /^const body = \w+\(/m
|
||||
const headingCall = /^const heading = \w+\(/m
|
||||
if (!importLine.test(layout) || !bodyCall.test(layout) || !headingCall.test(layout)) {
|
||||
throw new Error('reference layout: expected the next/font/google import and `const body = …(` / `const heading = …(`')
|
||||
}
|
||||
const names = [...new Set([body, heading])].sort()
|
||||
return layout
|
||||
.replace(importLine, `import { ${names.join(', ')} } from 'next/font/google'`)
|
||||
.replace(bodyCall, `const body = ${body}(`)
|
||||
.replace(headingCall, `const heading = ${heading}(`)
|
||||
}
|
||||
|
||||
/**
|
||||
* The manifest's package.json rewrite: `"section.key": value` sets one entry, `null` removes it.
|
||||
* The value `<exact released version>` becomes the plugin version.
|
||||
*/
|
||||
export function rewritePackageJson(text: string, rules: Record<string, null | string>, ctx: SiteContext, a: StarterAnswers): string {
|
||||
const pkg = JSON.parse(text) as Record<string, unknown>
|
||||
for (const [path, value] of Object.entries(rules)) {
|
||||
const dot = path.indexOf('.')
|
||||
if (dot < 0) {
|
||||
if (value === null) {delete pkg[path]}
|
||||
else {pkg[path] = value}
|
||||
continue
|
||||
}
|
||||
const section = path.slice(0, dot)
|
||||
const key = path.slice(dot + 1)
|
||||
const target = (pkg[section] ?? {}) as Record<string, unknown>
|
||||
if (value === null) {delete target[key]}
|
||||
else {target[key] = value === '<exact released version>' ? ctx.pluginVersion : value}
|
||||
if (Object.keys(target).length) {pkg[section] = target}
|
||||
else {delete pkg[section]}
|
||||
}
|
||||
pkg.description = `${a.siteName} — ${ctx.domain} (Payload CMS 3 + Next 16 on @intecion/ipal-kit)`
|
||||
return `${JSON.stringify(pkg, null, 2)}\n`
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The lockfile a new site starts from: the reference site's `pnpm-lock.yaml` (lockfile v9) without
|
||||
* `@intecion/ipal-kit` itself. The reference links the plugin from the repo (`file:..`), and the
|
||||
* released tarball's integrity hash does not exist while that tarball is being built. So the starter
|
||||
* ships every other package locked; `pnpm install` keeps those entries and resolves only the plugin
|
||||
* (an exact version in package.json, whose own dependencies are exact too — D15).
|
||||
*/
|
||||
const PLUGIN = '@intecion/ipal-kit'
|
||||
|
||||
const indentOf = (line: string) => line.length - line.trimStart().length
|
||||
|
||||
/** The key of a YAML map line: `'@scope/name@file:..(x)':` → `@scope/name@file:..(x)`, `name:` → `name`. */
|
||||
function keyOf(line: string): string {
|
||||
const text = line.trim()
|
||||
if (text.startsWith("'")) {return text.slice(1, text.indexOf("'", 1))}
|
||||
return text.replace(/:.*$/, '')
|
||||
}
|
||||
|
||||
/** Removes every map entry at `indent` whose key `isTarget` accepts, with its nested lines. */
|
||||
function dropEntries(lines: string[], indent: number, isTarget: (key: string) => boolean): string[] {
|
||||
const out: string[] = []
|
||||
let skipping = false
|
||||
for (const line of lines) {
|
||||
const blank = line.trim() === ''
|
||||
if (skipping) {
|
||||
if (blank || indentOf(line) > indent) {continue}
|
||||
skipping = false
|
||||
}
|
||||
if (!blank && indentOf(line) === indent) {
|
||||
if (isTarget(keyOf(line))) {
|
||||
skipping = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
out.push(line)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference lockfile without the plugin: its importer entry and `dependenciesMeta`
|
||||
* (`injected`), and its `packages` / `snapshots` entries. Everything else is untouched.
|
||||
*/
|
||||
export function lockfileWithoutPlugin(lock: string): string {
|
||||
if (!/^lockfileVersion: '9\.\d'/m.test(lock)) {throw new Error('starter lockfile: expected pnpm lockfile v9')}
|
||||
let lines = lock.split('\n')
|
||||
// importers → . → dependencies → '@intecion/ipal-kit' (6 spaces), and dependenciesMeta of it
|
||||
lines = dropEntries(lines, 6, (key) => key === PLUGIN)
|
||||
lines = dropEntries(lines, 4, (key) => key === 'dependenciesMeta')
|
||||
// packages: / snapshots: entries (2 spaces), e.g. '@intecion/ipal-kit@file:..(hash)'
|
||||
lines = dropEntries(lines, 2, (key) => key.startsWith(`${PLUGIN}@`))
|
||||
const result = lines.join('\n').replace(/\n{3,}/g, '\n\n')
|
||||
if (result.includes(`${PLUGIN}@`) || result.includes(`'${PLUGIN}':`)) {throw new Error('starter lockfile: the plugin is still referenced')}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* `reference/starter.manifest.json` — how the reference site becomes a new project.
|
||||
* The reference site owns this file; the starter only reads it.
|
||||
*/
|
||||
export type StarterManifest = {
|
||||
/** Paths left out of the new site (globs, relative to reference/). */
|
||||
drop: string[]
|
||||
/** Files the starter writes itself from the answers instead of copying them (e.g. `src/i18n.config.ts`). */
|
||||
generate?: string[]
|
||||
keep: string[]
|
||||
/** token → the reference site's fake value, e.g. `{{domain}}` → `example-studio.pl`. */
|
||||
placeholders: Record<string, string>
|
||||
rewrite?: {
|
||||
'package.json'?: Record<string, null | string>
|
||||
}
|
||||
schema: number
|
||||
/** Files copied with the placeholders replaced. */
|
||||
template: string[]
|
||||
/** Whole files that exist only with a flag on, e.g. `{ "src/collections/Posts.ts": "posts" }` (`!flag` allowed). */
|
||||
variants?: Record<string, string>
|
||||
}
|
||||
|
||||
/** Paths every bundle skips, whatever the manifest says (installed, built or local-only files). */
|
||||
export const ALWAYS_SKIPPED = ['node_modules/**', '.next/**', '.env', '.env.local', '**/.DS_Store', '*.tsbuildinfo']
|
||||
|
||||
function globToRegExp(glob: string): RegExp {
|
||||
let source = ''
|
||||
for (let i = 0; i < glob.length; i++) {
|
||||
const char = glob[i]
|
||||
if (char === '*' && glob[i + 1] === '*') {
|
||||
// `**/` matches zero or more folders; a trailing `**` matches everything below
|
||||
source += glob[i + 2] === '/' ? '(?:.*/)?' : '.*'
|
||||
i += glob[i + 2] === '/' ? 2 : 1
|
||||
} else if (char === '*') {
|
||||
source += '[^/]*'
|
||||
} else if (char === '?') {
|
||||
source += '[^/]'
|
||||
} else {
|
||||
source += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${source}$`)
|
||||
}
|
||||
|
||||
/** Glob match on a `/`-separated relative path: `*`, `**`, `?`. */
|
||||
export function matchGlob(path: string, glob: string): boolean {
|
||||
return globToRegExp(glob).test(path)
|
||||
}
|
||||
|
||||
export type FileRole = 'drop' | 'generate' | 'keep' | 'template'
|
||||
|
||||
/** What happens to one path: drop wins, then generate, then template, then keep. */
|
||||
export function fileRole(path: string, manifest: StarterManifest): FileRole {
|
||||
const any = (globs: string[] | undefined) => (globs ?? []).some((glob) => matchGlob(path, glob))
|
||||
if (any(ALWAYS_SKIPPED) || any(manifest.drop)) {return 'drop'}
|
||||
if (any(manifest.generate)) {return 'generate'}
|
||||
if (any(manifest.template)) {return 'template'}
|
||||
return any(manifest.keep) ? 'keep' : 'drop'
|
||||
}
|
||||
|
||||
/** Checks the manifest's shape before anything is built from it. */
|
||||
export function assertManifest(value: unknown): asserts value is StarterManifest {
|
||||
const m = value as null | Partial<StarterManifest>
|
||||
const problems: string[] = []
|
||||
if (!m || typeof m !== 'object') {throw new Error('starter.manifest.json: not an object')}
|
||||
if (m.schema !== 1) {problems.push(`schema ${String(m.schema)} (this ipal-kit reads schema 1)`)}
|
||||
for (const key of ['drop', 'keep', 'template'] as const) {
|
||||
if (!Array.isArray(m[key])) {problems.push(`"${key}" must be a list of globs`)}
|
||||
}
|
||||
if (!m.placeholders || typeof m.placeholders !== 'object') {problems.push('"placeholders" must map {{token}} → fake value')}
|
||||
if (problems.length) {throw new Error(`starter.manifest.json: ${problems.join('; ')}`)}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* The architecture questions asked in the terminal, all before a single file is written.
|
||||
* Enter takes the shown recommendation — an explicit choice, recorded as the owner's answer.
|
||||
* Agents pass the same answers as JSON with `--answers` instead.
|
||||
*/
|
||||
import { createInterface } from 'node:readline/promises'
|
||||
|
||||
import type { AnalyticsTool, ContentCollection, StarterAnswers } from './answers.js'
|
||||
|
||||
type Ask = (question: string) => Promise<string>
|
||||
|
||||
function asker(ask: Ask) {
|
||||
const text = async (question: string, recommended?: string): Promise<string> => {
|
||||
for (;;) {
|
||||
const answer = (await ask(`${question}${recommended ? ` [${recommended}]` : ''}: `)).trim()
|
||||
if (answer) {return answer}
|
||||
if (recommended !== undefined) {return recommended}
|
||||
}
|
||||
}
|
||||
const choice = async <T extends string>(question: string, options: readonly T[], recommended: T): Promise<T> => {
|
||||
for (;;) {
|
||||
const answer = await text(`${question} (${options.join(' / ')})`, recommended)
|
||||
if ((options as readonly string[]).includes(answer)) {return answer as T}
|
||||
}
|
||||
}
|
||||
const yes = async (question: string, recommended: boolean) => (await choice(question, ['yes', 'no'] as const, recommended ? 'yes' : 'no')) === 'yes'
|
||||
const list = async (question: string, recommended: string): Promise<string[]> =>
|
||||
(await text(`${question} (comma-separated, "none" for none)`, recommended)).split(',').map((s) => s.trim()).filter((s) => s && s !== 'none')
|
||||
return { choice, list, text, yes }
|
||||
}
|
||||
|
||||
/** Asks every topic of AGENT.md "Ask before you build" and returns the answers (not yet validated). */
|
||||
export async function askAnswers(ask: Ask): Promise<StarterAnswers> {
|
||||
const { choice, list, text, yes } = asker(ask)
|
||||
const siteName = await text('1. Site / company name (also the 2FA issuer)')
|
||||
const market = await text(' Market', 'PL')
|
||||
const industry = await text(' Industry, one line')
|
||||
const extra = await list('2. Languages besides pl (default) and en, as code:Label', 'none')
|
||||
const locales = [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }, ...extra.map((e) => {
|
||||
const [code = '', label = code] = e.split(':').map((s) => s.trim())
|
||||
return { code, label }
|
||||
})]
|
||||
const primary = await text('3. Brand primary colour (any CSS colour)')
|
||||
const secondary = await text(' Secondary colour ("none")', 'none')
|
||||
const accent = await text(' Accent colour ("none")', 'none')
|
||||
const fontBody = await text(' Body font (Google font name)', 'Inter')
|
||||
const fontHeading = await text(' Heading font (Google font name)', fontBody)
|
||||
const theme = await choice(' Theme', ['both', 'light', 'dark'] as const, 'both')
|
||||
const defaultTheme = theme === 'both' ? await choice(' Default theme', ['system', 'light', 'dark'] as const, 'system') : theme
|
||||
const radius = await choice(' Corner style', ['sharp', 'soft', 'round'] as const, 'soft')
|
||||
const fluid = await choice(' Scale (standard = to 1280px, wide = to 1920px)', ['wide', 'standard'] as const, 'wide')
|
||||
const pages = await list('4. Pages (site map)', 'Home, About, Services, Contact, Privacy policy, Cookie policy')
|
||||
const collections = (await list(' Collections with their own URLs: posts, caseStudies', 'none')) as ContentCollection[]
|
||||
const forms = await list('5. Forms', 'Contact form')
|
||||
const recipient = await text(' Inbox that receives submissions')
|
||||
const transport = await choice(' E-mail transport', ['smtp', 'graph'] as const, 'smtp')
|
||||
const tools = (await list('6. Analytics: ga4, gtm, metaPixel, linkedIn, tiktok, clarity', 'ga4')) as AnalyticsTool[]
|
||||
const consentMode = await choice(' Consent Mode', ['advanced', 'basic'] as const, 'advanced')
|
||||
const banner = await choice(' Cookie settings window', ['detailed', 'modal', 'inline'] as const, 'detailed')
|
||||
const cookieScanner = await yes(' Cookie scanner', true)
|
||||
const cookieScannerOffReason = cookieScanner ? undefined : await text(' Why off (owner\'s reason)')
|
||||
const crawl = cookieScanner ? await yes(' Browser crawl through the shared cookie-crawler service', true) : false
|
||||
const localBusiness = await yes('7. Local business (address, opening hours in JSON-LD)', true)
|
||||
const businessType = localBusiness ? await text(' schema.org type', 'ProfessionalService') : ''
|
||||
const aiBots = await choice(' AI crawlers', ['allow', 'block-training', 'disallow'] as const, 'allow')
|
||||
const aiBotsReason = aiBots === 'allow' ? undefined : await text(' Client decision behind it')
|
||||
const media = await choice('8. Media', ['r2', 'local'] as const, 'r2')
|
||||
const twoFactor = await yes('9. 2FA for the panel', true)
|
||||
const twoFactorOffReason = twoFactor ? undefined : await text(' Why off (owner\'s reason)')
|
||||
const whiteLabel = await yes(' White-label (client brand in the panel)', true)
|
||||
const agencyChoice = await choice(' Agency credit', ['intecion', 'none', 'other'] as const, 'intecion')
|
||||
const agency = agencyChoice === 'other' ? { name: await text(' Agency name'), url: await text(' Agency URL (https://…)') } : agencyChoice
|
||||
const adminMeta = await yes(' Panel link preview (adminMeta)', true)
|
||||
const adminMetaOffReason = adminMeta ? undefined : await text(' Why off (owner\'s reason)')
|
||||
const canonical = await choice('10. Canonical host', ['apex', 'www'] as const, 'apex')
|
||||
const coolify = await text(' Coolify server / project')
|
||||
const dns = await text(' Who adds the DNS records', 'the team')
|
||||
const external = await list('11. External skills (ext-react-best-practices, ext-composition-patterns, ext-accessibility, ext-frontend-design, ext-payload)', 'none')
|
||||
const optional = (value: string) => (value === 'none' ? undefined : value)
|
||||
return {
|
||||
admin: { adminMeta, adminMetaOffReason, agency, twoFactor, twoFactorOffReason, whiteLabel },
|
||||
consent: { banner, consentMode, cookieScanner, cookieScannerOffReason, crawl, tools },
|
||||
content: { collections, pages },
|
||||
forms: { list: forms, recipient, transport },
|
||||
hosting: { canonical, coolify, dns },
|
||||
industry,
|
||||
languages: { default: 'pl', locales },
|
||||
market,
|
||||
media,
|
||||
seo: { aiBots, aiBotsReason, localBusiness: localBusiness ? { type: businessType } : false },
|
||||
siteName,
|
||||
styling: { accent: optional(accent), defaultTheme, fluid, fontBody, fontHeading, primary, radius, secondary: optional(secondary), theme },
|
||||
tooling: { external },
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the questions on stdin/stdout. */
|
||||
export async function askInTerminal(): Promise<StarterAnswers> {
|
||||
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
||||
try {
|
||||
process.stdout.write('Architecture questions (AGENT.md "Ask before you build"). Enter = the recommendation in [brackets].\n\n')
|
||||
return await askAnswers((q) => rl.question(q))
|
||||
} finally {
|
||||
rl.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Turns the bundle and the owner's answers into the new site's files (path → content), in memory.
|
||||
* Pure: nothing is written here, so every rule is unit-testable.
|
||||
*/
|
||||
import { flagsFromAnswers, type StarterAnswers } from './answers.js'
|
||||
import { bundleFlags, type StarterBundle } from './bundle.js'
|
||||
import {
|
||||
renderAgentsMd,
|
||||
renderDesignMd,
|
||||
renderDoctorConfig,
|
||||
renderI18nConfig,
|
||||
renderTokens,
|
||||
rewriteFonts,
|
||||
rewritePackageJson,
|
||||
type SiteContext,
|
||||
} from './generate.js'
|
||||
import { fileRole } from './manifest.js'
|
||||
import { applyPlaceholders, applyVariants, leftoverFakes, type StarterFlags } from './text.js'
|
||||
|
||||
/** Files the starter writes from the answers; the manifest lists them under `generate`. */
|
||||
const GENERATORS: Record<string, (a: StarterAnswers, ctx: SiteContext) => string> = {
|
||||
'DESIGN.md': (a) => renderDesignMd(a),
|
||||
'ipal-doctor.json': renderDoctorConfig,
|
||||
'src/design/tokens.ts': (a) => renderTokens(a),
|
||||
'src/i18n.config.ts': (a) => renderI18nConfig(a),
|
||||
}
|
||||
|
||||
const LAYOUT = 'src/app/(frontend)/[locale]/layout.tsx'
|
||||
|
||||
/** The value of every placeholder token the starter knows. */
|
||||
export function placeholderValues(a: StarterAnswers, ctx: SiteContext): Record<string, string> {
|
||||
const flat = ctx.domain.replace(/\./g, '')
|
||||
const agency = typeof a.admin.agency === 'object' ? a.admin.agency : null
|
||||
return {
|
||||
'{{agencyName}}': agency?.name ?? '',
|
||||
'{{agencyUrl}}': agency?.url ?? '',
|
||||
'{{businessType}}': a.seo.localBusiness ? a.seo.localBusiness.type : 'Organization',
|
||||
'{{dbBase}}': ctx.dbNames.dev.replace(/_dev$/, ''),
|
||||
'{{domain}}': ctx.domain,
|
||||
'{{formRecipient}}': a.forms.recipient,
|
||||
'{{issuer}}': a.siteName,
|
||||
'{{mcpName}}': `${flat}-site`,
|
||||
'{{projectName}}': `${flat}-web`,
|
||||
'{{serverUrl}}': ctx.serverUrl,
|
||||
'{{siteName}}': a.siteName,
|
||||
}
|
||||
}
|
||||
|
||||
function isOn(expr: string, flags: StarterFlags): boolean {
|
||||
return expr.startsWith('!') ? flags[expr.slice(1)] !== true : flags[expr] === true
|
||||
}
|
||||
|
||||
export function renderSite(bundle: StarterBundle, a: StarterAnswers, ctx: SiteContext): Record<string, string> {
|
||||
const { manifest } = bundle
|
||||
const flags = flagsFromAnswers(a)
|
||||
const unknown = bundleFlags(bundle).filter((flag) => !(flag in flags))
|
||||
if (unknown.length) {throw new Error(`the reference site uses flags this ipal-kit does not set: ${unknown.join(', ')}`)}
|
||||
const values = placeholderValues(a, ctx)
|
||||
const missing = Object.keys(manifest.placeholders).filter((token) => !(token in values))
|
||||
if (missing.length) {throw new Error(`the manifest uses placeholders this ipal-kit does not fill: ${missing.join(', ')}`)}
|
||||
|
||||
// a fake value the site legitimately shares (e.g. the business type "ProfessionalService") is not a leftover
|
||||
const fakes = Object.fromEntries(Object.entries(manifest.placeholders).filter(([token, fake]) => !(values[token] ?? '').includes(fake)))
|
||||
const out: Record<string, string> = {}
|
||||
const problems: string[] = []
|
||||
for (const [path, source] of Object.entries(bundle.files)) {
|
||||
const role = fileRole(path, manifest)
|
||||
if (role === 'drop' || role === 'generate') {continue}
|
||||
const only = manifest.variants?.[path]
|
||||
if (only && !isOn(only, flags)) {continue}
|
||||
let text = applyVariants(source, flags, path)
|
||||
if (role === 'template') {text = applyPlaceholders(text, manifest.placeholders, values)}
|
||||
if (path === 'AGENTS.md') {text = renderAgentsMd(text, a, ctx)}
|
||||
if (path === 'package.json') {text = rewritePackageJson(text, manifest.rewrite?.['package.json'] ?? {}, ctx, a)}
|
||||
if (path === LAYOUT) {text = rewriteFonts(text, a)}
|
||||
const left = leftoverFakes(text, fakes)
|
||||
if (left.length) {problems.push(`${path}: still contains ${left.join(', ')}`)}
|
||||
out[path] = text
|
||||
}
|
||||
for (const path of manifest.generate ?? []) {
|
||||
const generate = GENERATORS[path]
|
||||
if (!generate) {
|
||||
problems.push(`${path}: listed under "generate" but this ipal-kit has no generator for it`)
|
||||
continue
|
||||
}
|
||||
out[path] = generate(a, ctx)
|
||||
}
|
||||
if (problems.length) {throw new Error(`rendering the site:\n ${problems.join('\n ')}`)}
|
||||
out['pnpm-lock.yaml'] = bundle.lockfile
|
||||
out['.ipal/starter.json'] = `${JSON.stringify({ answers: a, createdAt: ctx.date, domain: ctx.domain, ipalKit: ctx.pluginVersion }, null, 2)}\n`
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* The last check before the first commit: no `.env`, no assigned secret, no private key.
|
||||
* `.env.example` may hold names and public test values (Cloudflare's Turnstile test keys).
|
||||
*/
|
||||
// `NAME=value` where a `_`-separated part of NAME is SECRET / TOKEN / PASSWORD (or …_KEY after ACCESS / PRIVATE / SECRET),
|
||||
// and the value has 8+ characters and is not a placeholder (`<…>`, `[…]`, `${…}`, `…`). `TOKENS_BIN=` is not a secret.
|
||||
const ASSIGNMENT = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*['"]?(?![<[{$…]|\.\.\.)[^\s'"#]{8,}/gm
|
||||
const SECRET_NAME = /(?:^|_)(?:SECRET|TOKEN|PASSWORD|(?:ACCESS|PRIVATE|SECRET)_KEY)(?:_|$)/
|
||||
|
||||
function assignedSecret(text: string): null | string {
|
||||
for (const match of text.matchAll(ASSIGNMENT)) {
|
||||
if (SECRET_NAME.test(match[1] ?? '')) {return match[1] ?? null}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY-----/
|
||||
|
||||
export function secretFindings(files: Record<string, string>): string[] {
|
||||
const findings: string[] = []
|
||||
for (const [path, text] of Object.entries(files)) {
|
||||
const name = path.split('/').pop() ?? path
|
||||
if (name === '.env' || (name.startsWith('.env.') && name !== '.env.example')) {
|
||||
findings.push(`${path}: env files with values are never committed`)
|
||||
continue
|
||||
}
|
||||
if (PRIVATE_KEY.test(text)) {findings.push(`${path}: contains a private key`)}
|
||||
const secret = name === '.env.example' ? null : assignedSecret(text)
|
||||
if (secret) {findings.push(`${path}: assigns a secret (${secret}=…)`)}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Text transforms the starter applies to reference files: in-file variants and placeholders.
|
||||
* Both are plain string work, so the reference site stays a normal, runnable project.
|
||||
*/
|
||||
|
||||
/** Feature flags of one generated site (`posts`, `twoFactor`, `crawl`, …). A missing flag is off. */
|
||||
export type StarterFlags = Record<string, boolean>
|
||||
|
||||
// A marker is a whole line: `// @starter:if x`, `{/* @starter:if !x */}`, `# @starter:if x`, `<!-- @starter:if x -->`.
|
||||
const MARKER = /^\s*(?:\/\/|#|\{\/\*|\/\*|<!--)\s*@starter:(if|else|endif)(?:\s+([!\w-]+))?\s*(?:(?:\*\/\}|\*\/|-->)\s*)?$/
|
||||
|
||||
/** `x` is on when the flag is true; `!x` when it is false. */
|
||||
function test(expr: string, flags: StarterFlags): boolean {
|
||||
const negate = expr.startsWith('!')
|
||||
const value = flags[negate ? expr.slice(1) : expr] === true
|
||||
return negate ? !value : value
|
||||
}
|
||||
|
||||
// An alternative the reference site does not run itself is written commented out: `//: code`, `#: KEY=`.
|
||||
const ALTERNATIVE = /^(\s*)(?:\/\/|#): ?/
|
||||
|
||||
/**
|
||||
* Keeps or removes the lines between `@starter:if <flag>` / `@starter:else` / `@starter:endif`
|
||||
* and removes the marker lines themselves. Blocks nest; a line stays when every enclosing block
|
||||
* keeps it. Inside kept blocks, `//: ` / `#: ` lines are uncommented — that is how the reference
|
||||
* site carries code it does not run itself (e.g. `twoFactor: false`). An unbalanced marker throws.
|
||||
*/
|
||||
export function applyVariants(text: string, flags: StarterFlags, file = 'file'): string {
|
||||
const out: string[] = []
|
||||
const stack: { keep: boolean; line: number; seenElse: boolean }[] = []
|
||||
text.split('\n').forEach((line, index) => {
|
||||
const match = MARKER.exec(line)
|
||||
if (!match) {
|
||||
if (!stack.length) {out.push(line)}
|
||||
else if (stack.every((block) => block.keep)) {out.push(line.replace(ALTERNATIVE, '$1'))}
|
||||
return
|
||||
}
|
||||
const [, kind, expr] = match
|
||||
const at = `${file}:${index + 1}`
|
||||
const top = stack[stack.length - 1]
|
||||
if (kind === 'if') {
|
||||
if (!expr) {throw new Error(`@starter:if without a flag at ${at}`)}
|
||||
stack.push({ keep: test(expr, flags), line: index + 1, seenElse: false })
|
||||
} else if (kind === 'else') {
|
||||
if (!top || top.seenElse) {throw new Error(`stray @starter:else at ${at}`)}
|
||||
top.keep = !top.keep
|
||||
top.seenElse = true
|
||||
} else {
|
||||
if (!top) {throw new Error(`stray @starter:endif at ${at}`)}
|
||||
stack.pop()
|
||||
}
|
||||
})
|
||||
const open = stack[stack.length - 1]
|
||||
if (open) {throw new Error(`@starter:if at ${file}:${open.line} has no @starter:endif`)}
|
||||
return out.join('\n')
|
||||
}
|
||||
|
||||
/** Every flag a text's markers mention (without `!`). */
|
||||
export function variantFlags(text: string): string[] {
|
||||
const found = new Set<string>()
|
||||
for (const line of text.split('\n')) {
|
||||
const match = MARKER.exec(line)
|
||||
if (match?.[1] === 'if' && match[2]) {found.add(match[2].replace(/^!/, ''))}
|
||||
}
|
||||
return [...found]
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces each fake value of the reference site with the new site's value.
|
||||
* `values` maps token → new value, `fakes` maps token → the reference's fake value.
|
||||
* Longest fake first, so `example-studiopl-web` wins over `example-studiopl`.
|
||||
*/
|
||||
export function applyPlaceholders(text: string, fakes: Record<string, string>, values: Record<string, string>): string {
|
||||
const pairs = Object.entries(fakes)
|
||||
.filter(([token]) => token in values)
|
||||
.sort(([, a], [, b]) => b.length - a.length)
|
||||
let result = text
|
||||
for (const [token, fake] of pairs) {result = result.split(fake).join(values[token] ?? fake)}
|
||||
return result
|
||||
}
|
||||
|
||||
/** The fake values still present in a text (the generator fails on any). */
|
||||
export function leftoverFakes(text: string, fakes: Record<string, string>): string[] {
|
||||
return [...new Set(Object.values(fakes))].filter((fake) => text.includes(fake))
|
||||
}
|
||||
@@ -24,6 +24,7 @@ const ENTRIES: Record<string, string> = {
|
||||
'/rsc': 'src/exports/rsc.ts',
|
||||
'/seed': 'src/exports/seed.ts',
|
||||
'/server': 'src/exports/server.ts',
|
||||
'/starter': 'src/exports/starter.ts',
|
||||
'/templates': 'src/exports/templates.ts',
|
||||
'/tokens': 'src/exports/tokens.ts',
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
applyPlaceholders,
|
||||
applyVariants,
|
||||
bundleFlags,
|
||||
collectBundle,
|
||||
fileRole,
|
||||
flagsFromAnswers,
|
||||
leftoverFakes,
|
||||
localEnv,
|
||||
lockfileWithoutPlugin,
|
||||
matchGlob,
|
||||
normalizeDomain,
|
||||
packBundle,
|
||||
parseCreateArgs,
|
||||
renderDoctorConfig,
|
||||
renderI18nConfig,
|
||||
renderSite,
|
||||
rewriteFonts,
|
||||
secretFindings,
|
||||
type SiteContext,
|
||||
type StarterAnswers,
|
||||
type StarterManifest,
|
||||
unpackBundle,
|
||||
validateAnswers,
|
||||
} from '../src/exports/starter.js'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const reference = path.join(root, 'reference')
|
||||
|
||||
function answers(patch: (a: StarterAnswers) => void = () => {}): StarterAnswers {
|
||||
const a: StarterAnswers = {
|
||||
admin: { adminMeta: true, agency: 'intecion', twoFactor: true, whiteLabel: true },
|
||||
consent: { banner: 'detailed', consentMode: 'advanced', cookieScanner: true, crawl: false, tools: ['ga4'] },
|
||||
content: { collections: ['posts'], pages: ['Home', 'Contact'] },
|
||||
forms: { list: ['Contact form'], recipient: '[email protected]', transport: 'smtp' },
|
||||
hosting: { canonical: 'apex', coolify: 'coolify-1', dns: 'the team' },
|
||||
industry: 'bakery',
|
||||
languages: { default: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
|
||||
market: 'PL',
|
||||
media: 'r2',
|
||||
seo: { aiBots: 'allow', localBusiness: { type: 'Bakery' } },
|
||||
siteName: 'Acme Bakery',
|
||||
styling: { defaultTheme: 'system', fluid: 'wide', fontBody: 'Inter', fontHeading: 'Space Grotesk', primary: 'oklch(0.5 0.17 30)', radius: 'soft', theme: 'both' },
|
||||
tooling: { external: [] },
|
||||
}
|
||||
patch(a)
|
||||
return a
|
||||
}
|
||||
|
||||
const ctx: SiteContext = {
|
||||
date: '2026-11-02',
|
||||
dbNames: { dev: 'acme-testpl_dev', prod: 'acme-testpl_prod' },
|
||||
domain: 'acme-test.pl',
|
||||
pluginVersion: '1.15.0',
|
||||
serverUrl: 'https://acme-test.pl',
|
||||
}
|
||||
|
||||
describe('starter: variants', () => {
|
||||
const flags = { a: true, b: false }
|
||||
|
||||
it('keeps or drops blocks, with else, negation and every comment style', () => {
|
||||
const text = ['x', '// @starter:if a', 'A', '// @starter:else', 'notA', '// @starter:endif', '# @starter:if !b', 'notB', '# @starter:endif', '{/* @starter:if b */}', 'B', '{/* @starter:endif */}', '<!-- @starter:if a -->', 'mdA', '<!-- @starter:endif -->'].join('\n')
|
||||
expect(applyVariants(text, flags)).toBe(['x', 'A', 'notB', 'mdA'].join('\n'))
|
||||
})
|
||||
|
||||
it('uncomments `//: ` and `#: ` lines inside a kept block only, and nests', () => {
|
||||
const text = ['// @starter:if !b', ' //: twoFactor: false,', ' #: GRAPH_SENDER=', ' // @starter:if a', ' //: inner: true,', ' // @starter:endif', '// @starter:endif', '//: outside stays a comment'].join('\n')
|
||||
expect(applyVariants(text, flags)).toBe([' twoFactor: false,', ' GRAPH_SENDER=', ' inner: true,', '//: outside stays a comment'].join('\n'))
|
||||
})
|
||||
|
||||
it('throws on unbalanced markers', () => {
|
||||
expect(() => applyVariants('// @starter:if a\nx', flags, 'f.ts')).toThrow(/f\.ts:1 has no @starter:endif/)
|
||||
expect(() => applyVariants('// @starter:endif', flags)).toThrow(/stray/)
|
||||
expect(() => applyVariants('// @starter:if a\n// @starter:else\n// @starter:else\n// @starter:endif', flags)).toThrow(/stray @starter:else/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('starter: placeholders and manifest', () => {
|
||||
const fakes = { '{{dbBase}}': 'example-studiopl', '{{domain}}': 'example-studio.pl', '{{projectName}}': 'example-studiopl-web' }
|
||||
|
||||
it('replaces the longest fake first and reports leftovers', () => {
|
||||
const text = 'example-studiopl-web example-studiopl_dev example-studio.pl'
|
||||
expect(applyPlaceholders(text, fakes, { '{{dbBase}}': 'acme', '{{domain}}': 'acme.pl', '{{projectName}}': 'acmepl-web' })).toBe('acmepl-web acme_dev acme.pl')
|
||||
expect(leftoverFakes('nothing here', fakes)).toEqual([])
|
||||
expect(leftoverFakes('see example-studio.pl', fakes)).toEqual(['example-studio.pl'])
|
||||
})
|
||||
|
||||
it('matches globs and resolves file roles (drop > generate > template > keep)', () => {
|
||||
expect(matchGlob('e2e/smoke.spec.ts', 'e2e/**')).toBe(true)
|
||||
expect(matchGlob('src/a/b.ts', 'src/*.ts')).toBe(false)
|
||||
expect(matchGlob('x/.DS_Store', '**/.DS_Store')).toBe(true)
|
||||
const manifest = { drop: ['e2e/**'], generate: ['DESIGN.md'], keep: ['**'], placeholders: {}, schema: 1, template: ['package.json'] } as StarterManifest
|
||||
expect(fileRole('e2e/x.ts', manifest)).toBe('drop')
|
||||
expect(fileRole('node_modules/x/index.js', manifest)).toBe('drop')
|
||||
expect(fileRole('DESIGN.md', manifest)).toBe('generate')
|
||||
expect(fileRole('package.json', manifest)).toBe('template')
|
||||
expect(fileRole('src/proxy.ts', manifest)).toBe('keep')
|
||||
})
|
||||
})
|
||||
|
||||
describe('starter: answers', () => {
|
||||
it('accepts a complete set and names every missing answer', () => {
|
||||
expect(validateAnswers(answers())).toEqual([])
|
||||
const errors = validateAnswers({})
|
||||
expect(errors.length).toBeGreaterThan(15)
|
||||
expect(errors.join('\n')).toMatch(/siteName/)
|
||||
})
|
||||
|
||||
it('needs the owner\'s reason for every module turned off', () => {
|
||||
const a = answers((x) => {
|
||||
x.admin.twoFactor = false
|
||||
x.consent.cookieScanner = false
|
||||
x.seo.aiBots = 'disallow'
|
||||
})
|
||||
expect(validateAnswers(a).join('\n')).toMatch(/twoFactorOffReason[\s\S]*cookieScannerOffReason[\s\S]*aiBotsReason|twoFactorOffReason/)
|
||||
expect(validateAnswers(a)).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('keeps to what the base seed backs: default pl, en present', () => {
|
||||
expect(validateAnswers(answers((x) => { x.languages.default = 'en' }))).toHaveLength(1)
|
||||
expect(validateAnswers(answers((x) => { x.languages.locales.push({ code: 'de', label: 'Deutsch' }) }))).toEqual([])
|
||||
})
|
||||
|
||||
it('turns answers into the flags the reference markers test', () => {
|
||||
const flags = flagsFromAnswers(answers((x) => { x.consent.tools = ['metaPixel'] }))
|
||||
expect(flags).toMatchObject({ analytics: false, demo: false, enforceCsp: false, metaPixel: true, posts: true, scannerWithoutCrawl: true, twoFactor: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('starter: generated files', () => {
|
||||
it('writes the languages, fonts and the doctor config', () => {
|
||||
expect(renderI18nConfig(answers())).toContain("defaultLocale: 'pl'")
|
||||
const layout = "import { Fraunces, Inter } from 'next/font/google'\nconst body = Inter({ x })\nconst heading = Fraunces({ y })"
|
||||
expect(rewriteFonts(layout, answers())).toBe("import { Inter, Space_Grotesk } from 'next/font/google'\nconst body = Inter({ x })\nconst heading = Space_Grotesk({ y })")
|
||||
const doctor = JSON.parse(renderDoctorConfig(answers((x) => {
|
||||
x.admin.twoFactor = false
|
||||
x.admin.twoFactorOffReason = 'SSO in front of the panel'
|
||||
}), ctx)) as { rules: Record<string, { reason: string; until?: string }> }
|
||||
expect(doctor.rules.csp?.until).toBe('2026-11-30')
|
||||
expect(doctor.rules['2fa']?.reason).toBe('SSO in front of the panel')
|
||||
})
|
||||
|
||||
it('removes the plugin from the lockfile and nothing else', () => {
|
||||
const lock = [
|
||||
"lockfileVersion: '9.0'", '', 'importers:', '', ' .:', ' dependencies:', " '@intecion/ipal-kit':", ' specifier: file:..', ' version: file:..(abc)',
|
||||
' next:', ' specifier: 16.4.3', ' version: 16.4.3', ' dependenciesMeta:', " '@intecion/ipal-kit':", ' injected: true', '',
|
||||
'packages:', '', " '@intecion/ipal-kit@file:..':", ' resolution: {directory: .., type: directory}', '', ' [email protected]:', ' resolution: {integrity: x}', '',
|
||||
'snapshots:', '', " '@intecion/ipal-kit@file:..(abc)':", ' dependencies:', ' next: 16.4.3', '', ' [email protected]: {}', '',
|
||||
].join('\n')
|
||||
const out = lockfileWithoutPlugin(lock)
|
||||
expect(out).not.toContain('ipal-kit')
|
||||
expect(out).not.toContain('dependenciesMeta')
|
||||
expect(out).toContain(" [email protected]:\n resolution: {integrity: x}")
|
||||
expect(out).toContain(' [email protected]: {}')
|
||||
})
|
||||
|
||||
it('finds secrets but not placeholders or the env example', () => {
|
||||
expect(secretFindings({ '.env': 'X=1' })).toHaveLength(1)
|
||||
expect(secretFindings({ 'src/a.ts': 'PAYLOAD_SECRET=abcdefghijklmnop' })).toHaveLength(1)
|
||||
expect(secretFindings({ '.env.example': 'TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA', 'docs/x.md': 'PAYLOAD_SECRET=<random-string-min-32-chars>' })).toEqual([])
|
||||
expect(localEnv('PAYLOAD_SECRET=\nX=1')).toMatch(/^PAYLOAD_SECRET=[\w-]{60,}\nX=1$/)
|
||||
})
|
||||
|
||||
it('parses the command line and the domain', () => {
|
||||
expect(normalizeDomain('https://www.Acme-Test.pl/')).toBe('acme-test.pl')
|
||||
expect(() => normalizeDomain('localhost')).toThrow(/not a domain/)
|
||||
expect(parseCreateArgs(['acme.pl', '--answers', 'a.json', '--external', '--no-git'])).toMatchObject({ answersFile: 'a.json', domain: 'acme.pl', external: [], git: false, install: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('starter: the reference site', () => {
|
||||
const bundle = collectBundle(reference)
|
||||
|
||||
it('round-trips through the packed bundle and uses only flags the starter sets', () => {
|
||||
expect(unpackBundle(packBundle(bundle)).files).toEqual(bundle.files)
|
||||
const known = Object.keys(flagsFromAnswers(answers()))
|
||||
expect(bundleFlags(bundle).filter((flag) => !known.includes(flag))).toEqual([])
|
||||
})
|
||||
|
||||
it('renders a site with no reference values, demo files or plugin link', () => {
|
||||
const files = renderSite(bundle, answers(), ctx)
|
||||
const all = Object.entries(files)
|
||||
for (const [file, text] of all) {
|
||||
expect(`${file}: ${/example-studio|Example Studio|E2E_ADMIN/.exec(text)?.[0] ?? ''}`).toBe(`${file}: `)
|
||||
}
|
||||
expect(Object.keys(files).some((f) => f.startsWith('e2e/') || f.endsWith('/demo.ts') || f.startsWith('.agents/'))).toBe(false)
|
||||
const pkg = JSON.parse(files['package.json'] ?? '') as { dependencies: Record<string, string>; scripts: Record<string, string> }
|
||||
expect(pkg.dependencies['@intecion/ipal-kit']).toBe('1.15.0')
|
||||
expect(pkg.scripts['test:e2e']).toBeUndefined()
|
||||
expect(files['next.config.ts']).toContain("mode: 'report-only'")
|
||||
expect(files['src/payload.config.ts']).toContain("twoFactor: { issuer: 'Acme Bakery', plugin: payloadTotp }")
|
||||
expect(files['src/payload.config.ts']).toContain('cookieScanner: true,')
|
||||
expect(files['src/lib/content.ts']).toContain("type: 'Bakery'")
|
||||
expect(files['.env.example']).toContain('DATABASE_URI=mongodb://127.0.0.1:27017/acme-testpl_dev')
|
||||
expect(files['AGENTS.md']).toMatch(/## Project decisions\n- Languages: pl, en/)
|
||||
expect(files['src/seed/base.ts']).toContain("email: '[email protected]'")
|
||||
expect(files['pnpm-lock.yaml']).not.toContain('@intecion/ipal-kit')
|
||||
})
|
||||
|
||||
it('drops what the owner turned off', () => {
|
||||
const files = renderSite(bundle, answers((x) => {
|
||||
x.admin.twoFactor = false
|
||||
x.admin.twoFactorOffReason = 'SSO'
|
||||
x.content.collections = []
|
||||
x.media = 'local'
|
||||
x.seo.localBusiness = false
|
||||
}), ctx)
|
||||
expect(files['src/collections/Posts.ts']).toBeUndefined()
|
||||
expect(files['src/collections/entryFields.ts']).toBeUndefined()
|
||||
expect(files['src/payload.config.ts']).toContain('twoFactor: false,')
|
||||
expect(files['src/payload.config.ts']).not.toMatch(/payloadTotp|Posts/)
|
||||
expect(files['src/blocks/configs.ts']).not.toContain('entryList')
|
||||
expect(files['src/instrumentation.ts']).toContain('storage: false,')
|
||||
expect(files['src/lib/content.ts']).not.toMatch(/buildLocalBusinessJsonLd|getPayload/)
|
||||
expect(files['AGENTS.md']).toContain('ipal-audit-skip: twofactor, r2')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user