Files
ipal-kit/test/docsConsistency.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 4bb9c663fd Cookie scanner, phase 2: browser crawl through a shared scanner service
cookieScanner.crawl (opt-in) adds "Crawl site" to the Cookie review box. The
site asks the shared scanner service (services/cookie-crawler: Node +
Playwright, Dockerfile, deployed once on Coolify) to crawl its sitemap pages
twice, with no consent and after "Accept all". The service posts cookies,
storage keys and third-party hosts back to POST /api/ipal/cookie-crawl/results
(bearer token, running job only). No browser in the site.

Findings land as drafts through the same merge rules. Anything stored before
consent that is not necessary, and tracker requests before consent, are
violations, flagged on the review entries from the latest crawl only. The
cookie-crawl global keeps the latest result (no history). A dashboard warning
(CookieCrawlAlert) and an opt-in e-mail through the project's mail adapter
follow a crawl with violations or new unknown cookies. Scheduled crawls: a
Coolify scheduled task with the token. ipalEnvRules({ cookieCrawl: true }).

Also: the six older real-Payload tests no longer leave an orphaned
payload generate:types process (typescript.autoGenerate: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:14:01 +01:00

294 lines
14 KiB
TypeScript

/**
* Docs ↔ code, both ways — so the instructions agents follow never drift from
* the package:
* 1. every name a doc imports from '@intecion/ipal-kit[/entry]' or '@/lib/content'
* exists there (a renamed/removed API breaks this test, not a client project);
* 2. every public runtime export is described somewhere in docs/ (an API
* nobody knows about gets re-implemented in projects).
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
const root = path.resolve(import.meta.dirname, '..')
const read = (p: string) => readFileSync(path.join(root, p), 'utf8')
const ENTRIES: Record<string, string> = {
'': 'src/index.ts',
'/admin': 'src/exports/admin.ts',
'/client': 'src/exports/client.ts',
'/env': 'src/exports/env.ts',
'/next/middleware': 'src/exports/next-middleware.ts',
'/rsc': 'src/exports/rsc.ts',
'/seed': 'src/exports/seed.ts',
'/server': 'src/exports/server.ts',
}
/** Names an entry file exports — `export { a, b as c } from …`, `export type { … }`. */
function exportsOf(file: string): { runtime: Set<string>; types: Set<string> } {
const src = read(file).replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
const runtime = new Set<string>()
const types = new Set<string>()
for (const m of src.matchAll(/export\s+(type\s+)?\{([^}]*)\}/g)) {
for (const raw of m[2].split(',')) {
const item = raw.trim()
if (!item) {continue}
const isType = Boolean(m[1]) || item.startsWith('type ')
const name = item.replace(/^type\s+/, '').split(/\s+as\s+/).pop()!.trim()
;(isType ? types : runtime).add(name)
}
}
return { runtime, types }
}
/** Keys returned by createContentHelpers — what `@/lib/content` can re-export. */
function contentHelperNames(): Set<string> {
const src = read('src/modules/frontend/createContentHelpers.ts')
const block = src.slice(src.lastIndexOf(' return {'))
return new Set([...block.slice(0, block.indexOf('}')).matchAll(/^\s+(\w+),?$/gm)].map((m) => m[1]))
}
function docFiles(dir = 'docs'): string[] {
return readdirSync(path.join(root, dir)).flatMap((name) => {
const rel = path.join(dir, name)
return statSync(path.join(root, rel)).isDirectory() ? docFiles(rel) : /\.(?:md|ts|tsx|mjs)$/.test(name) ? [rel] : []
})
}
const docs = docFiles()
const exported = Object.fromEntries(Object.entries(ENTRIES).map(([sub, file]) => [sub, exportsOf(file)]))
describe('docs ↔ code', () => {
test('every name imported in the docs exists in the entry it is imported from', () => {
const helpers = contentHelperNames()
const missing: string[] = []
for (const file of docs) {
const text = read(file)
for (const m of text.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s+from\s+'(@intecion\/ipal-kit(?:\/[a-z/-]+)?|@\/lib\/content)'/g)) {
const source = m[2]
for (const raw of m[1].split(',')) {
const name = raw.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0].trim()
if (!name || name.startsWith('…') || name === '...') {continue}
if (source === '@/lib/content') {
if (!helpers.has(name)) {missing.push(`${file}: ${name} from @/lib/content`)}
continue
}
const entry = exported[source.replace('@intecion/ipal-kit', '')]
if (!entry) {continue} // unknown subpath — exports.test.ts reports it
if (!entry.runtime.has(name) && !entry.types.has(name)) {missing.push(`${file}: ${name} from ${source}`)}
}
}
// `export { x as GET } from '@/lib/content'` in route examples
for (const m of text.matchAll(/export\s+\{([^}]*)\}\s+from\s+'@\/lib\/content'/g)) {
for (const raw of m[1].split(',')) {
const name = raw.trim().split(/\s+as\s+/)[0].trim()
if (name && !helpers.has(name)) {missing.push(`${file}: export ${name} from @/lib/content`)}
}
}
}
expect(missing).toEqual([])
})
test('every public runtime export is described in the docs', () => {
// Constants and building blocks the plugin wires itself — documented through what uses them.
const internal = new Set([
'A11Y_DEFAULT', 'ACCEPT_ALL_CONSENT', 'buildConsentLogCollection', 'buildConsentLogEndpoint', 'buildFormsPlugin', 'buildIndexNowHook',
'buildIntegrationStatusBanner', 'buildIntegrationStatusField', 'checkboxGroupBlock', 'CONSENT_LOG_SLUG', 'CONSENT_MAX_AGE',
'CONSENT_VERSION', 'DEFAULT_CONSENT', 'DEFAULT_SITEMAP_CREDIT', 'INDEXNOW_KEY_ENV', 'INDEXNOW_KEY_PATH',
'injectAutoFillMeta', 'IntecionCredit', 'IntegrationStatusBanner', 'MARKDOWN_PREFIX', 'matchAcceptLanguage',
'readConsentRecord', 'recordIntegrationStatus', 'REJECT_ALL_CONSENT', 'serializeA11y',
'serializeConsent', 'SITE_INTEGRATIONS_SLUG', 'SITE_SETTINGS_SLUG', 'SITEMAP_STYLE_PARAM', 'stepBlock', 'TestEmailButton',
])
const all = docs.map(read).join('\n')
const undocumented: string[] = []
for (const [sub, { runtime }] of Object.entries(exported)) {
for (const name of runtime) {
if (internal.has(name)) {continue}
if (!new RegExp(`\\b${name}\\b`).test(all)) {undocumented.push(`${name} (@intecion/ipal-kit${sub})`)}
}
}
expect(undocumented).toEqual([])
})
test('every top-level plugin option is documented', () => {
const src = read('src/types.ts')
const body = src.slice(src.indexOf('export type IpalOptions = {'))
const keys = [...body.matchAll(/^ {2}(\w+)\??:/gm)].map((m) => m[1])
expect(keys.length).toBeGreaterThan(10)
const all = docs.map(read).join('\n')
expect(keys.filter((key) => !new RegExp(`\\b${key}\\b`).test(all))).toEqual([])
})
test('every IPAL_* env var named in the docs is read by the code', () => {
// The plugin, or a script/template shipped in the skills (e.g. IPAL_SEED_ALLOW_PROD_UPDATE).
const shipped = docs.filter((f) => f.startsWith('docs/agent/skills/') && /\.(?:mjs|ts|tsx)$/.test(f))
const code = [...srcFiles(), ...shipped].map(read).join('\n')
const named = new Set([...docs, 'README.md'].flatMap((f) => [...read(f).matchAll(/\bIPAL_[A-Z0-9_]+/g)].map((m) => m[0])))
expect([...named].filter((name) => !code.includes(name))).toEqual([])
})
test('relative links between docs point at existing files', () => {
const broken: string[] = []
for (const file of [...docs, 'README.md'].filter((f) => f.endsWith('.md'))) {
for (const m of read(file).matchAll(/\]\((?!https?:|mailto:|#)([^)\s#]+)(?:#([^)]*))?\)/g)) {
const target = path.join(path.dirname(file), m[1])
if (!existsSync(path.join(root, target))) {broken.push(`${file}: ${m[1]}`); continue}
if (m[2] && target.endsWith('.md') && !anchorsOf(target).has(decodeURIComponent(m[2]))) {broken.push(`${file}: ${m[1]}#${m[2]}`)}
}
}
expect(broken).toEqual([])
})
test('every module page is listed in docs/README.md', () => {
const index = read('docs/README.md')
const pages = readdirSync(path.join(root, 'docs')).filter((n) => n.endsWith('.md') && !['CHANGELOG.md', 'README.md'].includes(n))
expect(pages.filter((p) => !index.includes(`(./${p})`))).toEqual([])
})
test('AGENT.md § references point at existing sections', () => {
const headings = new Set([...read('docs/agent/AGENT.md').matchAll(/^#{2,3} (\d+[a-z]?(?:\.\d+[a-z]?)*)\.? /gm)].map((m) => m[1]))
const missing: string[] = []
for (const file of docs) {
for (const m of read(file).matchAll(/AGENT\.md ?§ ?(\d+[a-z]?(?:\.\d+[a-z]?)*)/g)) {
const id = m[1]
// §0b.4 may point at a numbered rule inside §0b — the parent section is enough.
if (!headings.has(id) && !headings.has(id.replace(/\.[^.]+$/, ''))) {missing.push(`${file}: §${id}`)}
}
}
expect(missing).toEqual([])
})
test('frontend.md describes every key @/lib/content can export', () => {
const page = read('docs/frontend.md')
expect([...contentHelperNames()].filter((name) => !new RegExp(`\\b${name}\\b`).test(page))).toEqual([])
})
test('install commands never tell projects to add packages ipal-kit already depends on', () => {
const own = Object.keys(JSON.parse(read('package.json')).dependencies)
const offending: string[] = []
for (const file of ['README.md', 'docs/dev/PROGRAMISTA.md']) {
for (const m of read(file).matchAll(/pnpm add ([^\n`\\]+(?:\\\n[^\n`\\]+)*)/g)) {
const pkgs = m[1].split(/[\s\\]+/).map((p) => p.replace(/@[^@/]*$/, ''))
for (const dep of own) {if (pkgs.includes(dep)) {offending.push(`${file}: ${dep}`)}}
}
}
expect(offending).toEqual([])
})
test('agent skills have frontmatter whose name matches the folder', () => {
const dir = path.join(root, 'docs/agent/skills')
const bad = readdirSync(dir).filter((name) => {
const text = read(`docs/agent/skills/${name}/SKILL.md`)
return !new RegExp(`^---\\nname: ${name}\\ndescription: .+\\n`, 'm').test(text)
})
expect(bad).toEqual([])
})
})
/**
* The docs are written in English. Polish may stay only as sample data: inside code
* blocks, inline code or quoted strings (e.g. a 'pl' seed value, a slug, a file name).
*/
describe('docs are in English', () => {
test('no Polish prose outside code and quoted sample data', () => {
// Diacritics, or common Polish words for text written without them.
const polish = /[ąćęłńóśźż]|\b(?:albo|czy|dla|gdy|jest|lub|nie|oraz|przez|tylko)\b/i
const offending: string[] = []
for (const file of [...docs, 'README.md'].filter((f) => f.endsWith('.md'))) {
const prose = read(file)
.replace(/```[\s\S]*?```/g, '')
.replace(/`[^`\n]*`/g, '')
.replace(/"[^"\n]*"|'[^'\n]*'|„[^”\n]*”/g, '')
prose.split('\n').forEach((line) => {
if (polish.test(line)) {offending.push(`${file}: ${line.trim().slice(0, 80)}`)}
})
}
expect(offending).toEqual([])
})
})
/**
* The agent guide (AGENT.md + the ipal-* skills copied into projects) is all an agent in a
* consumer project reads. Every export, option and env var must be findable there, or the
* agent re-implements what the plugin already does.
*/
describe('agent guide covers the whole plugin', () => {
const guide = [read('docs/agent/AGENT.md'), ...walk('docs/agent/skills').map(read)].join('\n')
const missingFrom = (names: Iterable<string>) => [...new Set(names)].filter((n) => !new RegExp(`\\b${n}\\b`).test(guide)).sort()
test('every export of every entry (runtime and types)', () => {
const missing = Object.entries(exported).flatMap(([sub, { runtime, types }]) =>
missingFrom([...runtime, ...types]).map((name) => `${name} (@intecion/ipal-kit${sub})`),
)
expect(missing).toEqual([])
})
test('every plugin option, including nested option keys', () => {
const typeKeys = (file: string, name: string) => {
const src = read(file)
const start = src.indexOf(`export type ${name} = {`)
expect(start, `${name} in ${file}`).toBeGreaterThanOrEqual(0)
const body = src.slice(start, src.indexOf('\n}', start))
return [...body.matchAll(/^\s+(\w+)\??:/gm)].map((m) => m[1])
}
const keys = [
...typeKeys('src/types.ts', 'IpalOptions'),
...typeKeys('src/modules/access/types.ts', 'AccessOption'),
...typeKeys('src/modules/content/types.ts', 'ContentCollectionOption'),
...typeKeys('src/modules/content/types.ts', 'ContentOption'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieScannerOptions'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieCrawlOptions'),
...typeKeys('src/modules/env/ipalEnvRules.ts', 'IpalEnvFeatures'),
...typeKeys('src/modules/forms/types.ts', 'FormsOption'),
...typeKeys('src/modules/i18n/types.ts', 'I18nConfig'),
...typeKeys('src/modules/i18n/types.ts', 'LocaleDefinition'),
...typeKeys('src/modules/pages/types.ts', 'PagesOption'),
...typeKeys('src/modules/seo/types.ts', 'SeoOption'),
...typeKeys('src/modules/stats/collection.ts', 'StatsOptions'),
]
expect(keys.length).toBeGreaterThan(50)
expect(missingFrom(keys)).toEqual([])
})
test('every env var the code reads', () => {
const code = srcFiles().map(read).join('\n')
const env = [
...[...code.matchAll(/process\.env\.([A-Z][\dA-Z_]+)/g)].map((m) => m[1]),
// names held in constants, e.g. TURNSTILE_SECRET_ENV = 'TURNSTILE_SECRET_KEY'
...[...code.matchAll(/_ENV\s*=\s*'([A-Z][\dA-Z_]+)'/g)].map((m) => m[1]),
]
expect(env.length).toBeGreaterThan(10)
expect(missingFrom(env)).toEqual([])
})
test('every @/lib/content helper', () => {
expect(missingFrom(contentHelperNames())).toEqual([])
})
})
function walk(dir: string): string[] {
return readdirSync(path.join(root, dir)).flatMap((name) => {
const rel = path.join(dir, name)
return statSync(path.join(root, rel)).isDirectory() ? walk(rel) : [rel]
})
}
/** GitHub-style heading anchors of a Markdown file (code blocks skipped, duplicates get -1, -2 …). */
function anchorsOf(file: string): Set<string> {
const seen = new Map<string, number>()
const text = read(file).replace(/```[\s\S]*?```/g, '')
return new Set([...text.matchAll(/^#{1,6} (.+)$/gm)].map((m) => {
const slug = m[1].trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-')
const n = seen.get(slug) ?? 0
seen.set(slug, n + 1)
return n ? `${slug}-${n}` : slug
}))
}
function srcFiles(dir = 'src'): string[] {
return readdirSync(path.join(root, dir)).flatMap((name) => {
const rel = path.join(dir, name)
return statSync(path.join(root, rel)).isDirectory() ? srcFiles(rel) : /\.tsx?$/.test(name) ? [rel] : []
})
}