/** * 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 = { '': 'src/index.ts', '/admin': 'src/exports/admin.ts', '/blocks': 'src/exports/blocks.ts', '/blocks/rsc': 'src/exports/blocks-rsc.ts', '/client': 'src/exports/client.ts', '/doctor': 'src/exports/doctor.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', '/starter': 'src/exports/starter.ts', '/templates': 'src/exports/templates.ts', '/tokens': 'src/exports/tokens.ts', } /** Names an entry file exports — `export { a, b as c } from …`, `export type { … }`. */ function exportsOf(file: string): { runtime: Set; types: Set } { const src = read(file).replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '') const runtime = new Set() const types = new Set() 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 { 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])) } // Third-party skills vendored as-is (docs/agent/external) — test/externalSkills.test.ts checks them. const VENDORED = path.join('docs', 'agent', 'external') function docFiles(dir = 'docs'): string[] { return readdirSync(path.join(root, dir)).flatMap((name) => { const rel = path.join(dir, name) if (rel === VENDORED) {return []} 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 IaplOptions = {')) 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 IAPL_* env var named in the docs is read by the code', () => { // The plugin, or a script/template shipped in the skills (e.g. IAPL_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') // docs/dev/rename-iapl-plan.md is the rename's inventory: it also lists the repository's own test variables. const named = new Set([...docs, 'README.md'].filter((f) => f !== 'docs/dev/rename-iapl-plan.md').flatMap((f) => [...read(f).matchAll(/\bI(?:AP|PA)L_[A-Z0-9_]+/g)].map((m) => m[0]))) // IPAL_ (the spelling before 1.17.0) is read through its IAPL_ twin: src/modules/shared/envName.ts expect([...named].filter((name) => !code.includes(name.replace(/^IPAL_/, 'IAPL_')))).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('no client-component example imports the main entry', () => { // '@intecion/ipal-kit' reaches server-only modules: a 'use client' file that imports it does not build with webpack. const offending: string[] = [] for (const file of docs) { const blocks = file.endsWith('.md') ? [...read(file).matchAll(/```[a-z]*\n([\s\S]*?)```/g)].map((m) => m[1]) : [read(file)] for (const block of blocks) { if (/^['"]use client['"]/m.test(block) && /^import (?!type\b)[^'"]*?from ['"]@intecion\/ipal-kit['"]/m.test(block)) {offending.push(file)} } } expect(offending).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 IAPL 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 iapl-* 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) => [...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', 'IaplOptions'), ...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/iaplEnvRules.ts', 'IaplEnvFeatures'), ...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('the working rules reach every skill that builds the site', () => { const agent = read('docs/agent/AGENT.md') for (const heading of ['## Ask before you build', '## IAPL first', '## Code rules']) {expect(agent).toContain(heading)} const skills = ['iapl-setup', 'iapl-site', 'iapl-block', 'iapl-collection', 'iapl-form'] const missing = skills.filter((name) => { const text = read(`docs/agent/skills/${name}/SKILL.md`) return !text.includes('IAPL first') || !text.includes('Code rules') || !text.includes('iapl-plugin-gap') }) expect(missing).toEqual([]) // Both entry skills start with the architecture questions and wait for the answers. expect(read('docs/agent/skills/iapl-setup/SKILL.md')).toContain('## 0. Architecture questions') expect(read('docs/agent/skills/iapl-site/SKILL.md')).toContain('Architecture questions') }) 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 { const seen = new Map() 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] : [] }) }