Files
ipal-kit/src/modules/doctor/rules/layout.ts
T
Radosław SmolińskiandClaude Fable 5.2 425fac14fb IAPL rename: the old names keep working, and a second cookie name and counter key for new sites
- exports: ipalKit, IpalOptions, ipalEnvRules, IpalEnvFeatures, ipalT, ipalVar, IPAL_TOKENS,
  IPAL_BREAKPOINTS, IpalTokenName, IpalGlobalSlug are aliases of the iapl names
- env: IAPL_* is read first, IPAL_* as fallback (readEnv; EnvRule.aliases for assertEnv);
  the crawler service reads IPAL_CRAWLER_SITES too
- doctor: reads ipal-doctor.json when it is the only one, the old pointer block, ipal-audit-skip
  and old skill folders; new rule legacy-names (info) and storage-names (warning)
- iapl-skills: installs iapl-*, removes the 16 old folders by exact name, rewrites the old
  pointer block in place; a project's own ipal-* skill stays
- storageNames: 'ipal' (default) | 'iapl': the cookie the scanner declares and the 2FA counter's
  kv prefix; <PageStats visitorCookie>, IAPL_VISITOR_COOKIE, verifyLimit.keyPrefix
- test/legacyNames.test.ts: 24 tests for all of the above

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:31:13 +01:00

257 lines
14 KiB
TypeScript

import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { configFile } from '../project.js'
import { lt, stripComments } from '../util.js'
/** Top-level entries of src/ the convention allows (AGENT.md §3 + the starter, reference site and token drafts). */
export const DEFAULT_SRC_ALLOW = [
'access',
'app',
'blocks',
'collections',
'components',
'content.config.ts',
'db.ts',
'design',
'env.rules.ts',
'fields',
'fonts',
'globals',
'hooks',
'i18n.config.ts',
'instrumentation.ts',
'lib',
'migrations',
'payload-types.ts',
'payload.config.ts',
'proxy.ts',
'seed',
'utilities',
]
/** The project renders blocks through the library registry — then components/ui/ only holds overrides. */
export const usesBlockRegistry = (ctx: DoctorContext) => /createBlockRegistry\s*\(/.test(stripComments(ctx.read(`${ctx.src}blocks/registry.ts`)))
/** Where the site's pages live: the route group (any name) and whether it has a `[locale]` segment. */
export type FrontendLayout = {
/** Other folders that look like the frontend too (set `layout.frontend` to choose). */
ambiguous: string[]
/** Folder relative to src/, e.g. `app/(site)`, `app/(frontend)` or `app` (no route group). */
dir: string
/** `layout.frontend` names a folder that does not exist. */
missingOverride?: string
multi: boolean
}
const PAGE = ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
const has = (ctx: DoctorContext, dir: string, names: string[]) => names.some((n) => ctx.exists(`${ctx.src}${dir}/${n}`))
/**
* The frontend folder, found by structure rather than by name (a route group's name never reaches the URL):
* `iapl-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
* holding the catch-all page — one with a `[locale]` page first. No match → `app/(frontend)` (the convention).
*/
export function findFrontend(ctx: DoctorContext): FrontendLayout {
const override = ctx.config.layout?.frontend?.trim()
if (override) {
const dir = override.replace(/^\.?\//, '').replace(/^src\//, '').replace(/\/+$/, '')
return { ambiguous: [], dir, missingOverride: ctx.exists(`${ctx.src}${dir}`) ? undefined : override, multi: ctx.exists(`${ctx.src}${dir}/[locale]`) }
}
const groups = ['app', ...ctx.list(`${ctx.src}app`).filter((n) => /^\(.+\)$/.test(n) && n !== '(payload)').map((n) => `app/${n}`)]
const localized = groups.filter((g) => has(ctx, `${g}/[locale]/[[...slug]]`, PAGE))
const single = groups.filter((g) => has(ctx, `${g}/[[...slug]]`, PAGE))
const best = localized.length ? localized : single
if (!best.length) {return { ambiguous: [], dir: 'app/(frontend)', multi: ctx.exists(`${ctx.src}app/(frontend)/[locale]`) }}
const dir = best.includes('app/(frontend)') ? 'app/(frontend)' : best[0]
return { ambiguous: best.filter((g) => g !== dir), dir, multi: localized.length > 0 }
}
/** Files AGENT.md §3 expects — each as its accepted names — with the `iapl-audit-skip` key that drops it. */
function requiredFiles(ctx: DoctorContext, frontend: FrontendLayout): Array<[string[], string?]> {
const fe = frontend.multi ? `${frontend.dir}/[locale]` : frontend.dir
const ts = (base: string) => [`${base}.ts`, `${base}.tsx`]
const tsx = (base: string) => [`${base}.tsx`, `${base}.ts`, `${base}.jsx`, `${base}.js`]
const route = (dir: string) => [`${dir}/route.ts`, `${dir}/route.js`]
return [
[ts('proxy')],
[ts('i18n.config')],
[ts('instrumentation')],
[ts('payload.config')],
[ts('lib/content')],
[tsx('app/manifest')],
[tsx('app/robots')],
[route('app/sitemap.xml')],
[route('app/llms.txt'), 'llms'],
[route('app/llms-full.txt'), 'llms-full'],
[route(frontend.multi ? 'app/md/[locale]/[[...slug]]' : 'app/md/[[...slug]]'), 'markdown'],
[route('app/api/mcp'), 'mcp'],
[route('app/api/health')],
[route('app/indexnow-key.txt'), 'indexnow'],
[tsx(`${fe}/layout`)],
[ts(`${fe}/actions`)],
[tsx(`${fe}/not-found`)],
// the lazy 404's server action: .tsx when its fallback holds JSX (pages.md)
[ts(`${fe}/notFoundView`)],
[tsx(`${fe}/[[...slug]]/page`)],
[ts('blocks/registry')],
[ts('collections/Pages')],
[ts('collections/Media')],
[['components/layout']],
[ts('components/forms/formClasses')],
// components/ui/: blocks-ui-required (only without createBlockRegistry)
]
}
const PASCAL = /^[A-Z][A-Za-z0-9]*$/
const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+)*$/
export const layoutRules: DoctorRule[] = [
{
id: 'layout-required',
check: (ctx) => {
if (!ctx.src) {return [{ message: 'no src/ folder (AGENT.md §3)', severity: 'error' }]}
const frontend = findFrontend(ctx)
const out: RuleFinding[] = []
if (frontend.missingOverride) {
out.push({ file: 'iapl-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
}
if (frontend.ambiguous.length) {
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in iapl-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
}
const missing = requiredFiles(ctx, frontend).filter(([names, key]) => !(key && ctx.auditSkips.has(key)) && !names.some((n) => ctx.exists(`${ctx.src}${n}`)))
if (missing.length) {
out.push({ fix: 'the iapl-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
}
return out
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'layout-forbidden',
check: (ctx) => {
const files = ['middleware.ts', `${ctx.src}middleware.ts`, ...['lib/pages.ts', 'lib/locales.ts', 'lib/navigation.ts', 'fields/link.ts', 'fields/sectionHeader.ts', 'fields/sectionSettings.ts'].map((f) => `${ctx.src}${f}`)]
const found = [...new Set(files)].filter((f) => ctx.exists(f))
return found.length
? [{ fix: 'delete — Next 16 uses proxy.ts; the plugin has resolveRoute, getConfiguredLocales, resolveNav, buildLinkField and the section fields', message: `files the plugin replaces: ${found.join(', ')}`, severity: 'error' }]
: []
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'layout-extra',
check: (ctx) => {
if (!ctx.src) {return []}
const allow = new Set([...(ctx.config.layout?.allow ?? []), ...DEFAULT_SRC_ALLOW])
const extra = ctx.list('src').filter((n) => !allow.has(n) && !n.startsWith('.'))
return extra.length
? [{ fix: 'move into the convention, or add to iapl-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }]
: []
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'naming',
check: (ctx) => {
const out: RuleFinding[] = []
const bad: string[] = []
// Block folders PascalCase; files in blocks/ (registry.ts, configs.ts) are helpers — camelCase is fine.
for (const name of ctx.list(`${ctx.src}blocks`)) {
if (!name.includes('.') && !PASCAL.test(name)) {bad.push(`blocks/${name}`)}
}
// A collection / global file (it has a slug) PascalCase; helper files next to them camelCase.
for (const dir of ['collections', 'globals']) {
for (const name of ctx.list(`${ctx.src}${dir}`)) {
const file = `${ctx.src}${dir}/${name}`
if (!/\.tsx?$/.test(name)) {continue}
const isConfig = /\bslug\s*:/.test(ctx.read(file)) && /(?:CollectionConfig|GlobalConfig)\b/.test(ctx.read(file))
if (isConfig && !PASCAL.test(name.replace(/\.tsx?$/, ''))) {bad.push(`${dir}/${name}`)}
}
}
for (const name of ctx.list('scripts')) {
if (/\.[cm]?[jt]s$/.test(name) && !KEBAB.test(name)) {bad.push(`scripts/${name}`)}
}
if (bad.length) {out.push({ fix: 'rename (blocks, collections, globals: PascalCase; scripts: kebab-case)', message: `names off the convention: ${bad.join(', ')}`, severity: 'warning' })}
const barrels = ['blocks', 'components'].flatMap((d) => (ctx.exists(`${ctx.src}${d}/index.ts`) ? [`${ctx.src}${d}/index.ts`] : []))
if (barrels.length) {out.push({ fix: 'delete — import files directly (§6.12)', message: `barrel files: ${barrels.join(', ')}`, severity: 'warning' })}
return out
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'importmap',
check: (ctx) => {
if (!ctx.importMap) {return [{ fix: 'pnpm payload generate:importmap', message: 'no importMap.js under app/(payload)/<admin>/', severity: 'error' }]}
const out: RuleFinding[] = []
const im = ctx.read(ctx.importMap)
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
const v = ctx.pluginVersion
const need: string[] = []
if (/payloadTotp/.test(cfg)) {
need.push('@clocklimited/payload-2fa/rsc#TOTPSetup')
if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')}
// "2FA setup required": the status / reset control on the account and the dashboard notice — when the
// installed plugin has them and the config does not switch them (or the mode) off. Without them the
// panel shows no "Reopen setup": the documented way out of a blocked account is missing.
const adminExports = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
const modeOff = /requireSetup\s*:\s*false|guard\s*:\s*false/.test(cfg)
if (/\bTwoFactorStatusField\b/.test(adminExports) && !modeOff && !/statusField\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorStatusField')}
if (/\bTwoFactorAlert\b/.test(adminExports) && !modeOff && !/dashboardNotice\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorAlert')}
// the back-link check in front of the 2FA screens (twoFactor.safeBack) — when the installed plugin has it
if (/\bSafeTotpView\b/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')) && !/safeBack\s*:\s*false/.test(cfg)) {
need.push('@intecion/ipal-kit/admin#SafeTotpView')
}
}
// A view the project registers itself with the 2FA package's own component is not behind the back-link check.
// Only as a view's component (`Component: '<path>'` or `Component: { path: '<path>' }`): the same path as the
// value of `ipalTotpView` or of an `admin.dependencies` entry is the fix, not the problem.
if (/\bComponent\s*:\s*(?:\{[^{}]*?\bpath\s*:\s*)?['"`]@clocklimited\/payload-2fa\/rsc#TOTP(?:Setup|Verify)\b/.test(cfg)) {
out.push({
file: configFile(ctx) ?? undefined,
fix: "register it through wrapTotpViews (or Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<that path>' } } plus the path in admin.dependencies) — security.md \"Your own 2FA screen\"",
message: "the config registers the 2FA package's own setup / verify view as a view component: it sends the browser to an unchecked `back` link after the code",
severity: 'warning',
})
}
if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')}
if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')}
if (!lt(v, '1.14.5') && !/adminMeta\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#AdminIcon')}
const missing = need.filter((n) => !im.includes(n))
if (missing.length) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: `import map lacks ${missing.join(', ')}`, severity: 'error' })}
// Entries that name exports the installed plugin no longer has (a removed admin component → blank admin).
const adminIndex = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
if (adminIndex) {
const names = [...new Set([...im.matchAll(/['"]@intecion\/ipal-kit\/admin#(\w+)['"]/g)].map((m) => m[1]))]
const gone = names.filter((n) => !new RegExp(`\\b${n}\\b`).test(adminIndex))
if (gone.length) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: `import map names exports the installed plugin no longer has: ${gone.join(', ')}`, severity: 'error' })}
}
if (ctx.deep?.importMapCurrent === false) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: 'the committed import map differs from a freshly generated one', severity: 'error' })}
return out
},
docs: 'docs/agent/skills/iapl-reference/SKILL.md',
group: 'layout',
source: 'static',
},
{
id: 'tsconfig-skills',
check: (ctx) => {
const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => /^(?:iapl|ipal)-/.test(n)))
if (!dirs.length || !ctx.exists('tsconfig.json')) {return []}
const exclude = ctx.read('tsconfig.json').replace(/\s/g, '').match(/"exclude":\[([^\]]*)\]/)?.[1] ?? ''
const missing = dirs.filter((d) => !new RegExp(`"(?:\\./)?${d.replace('.', '\\.')}(?:/[^"]*)?"`).test(exclude))
return missing.length ? [{ file: 'tsconfig.json', fix: `"exclude": ["node_modules", "${missing.join('", "')}"]`, message: `tsconfig.json does not exclude ${missing.join(', ')} — skill templates break tsc / next build`, severity: 'error' }] : []
},
docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor',
group: 'layout',
source: 'static',
},
]