diff --git a/.gitignore b/.gitignore index 569f95f..0f4cfee 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,4 @@ next-env.d.ts # pnpm starter:gate work folder .starter-gate/ +.legacy-site-*/ diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index a637f48..045cc0e 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -775,6 +775,13 @@ done until the reference site uses it. Before `npm version`: `pnpm test:e2e` (Playwright's global setup runs `e2e/create-test-admin.ts` first: test admins reset, stored 2FA attempt counts cleared, so the result does not depend on what ran before; the fresh-site spec on an EMPTY database: `E2E_SKIP_ADMIN_SETUP=1`). +- [ ] **`pnpm legacy:site` green — required through 1.x.** The reference site as it was at `v1.16.7` (the last + release before the rename to IAPL: `ipalKit()`, `ipal-tokens`, `ipal-doctor.json`, `ipal-*` skills), unpacked + and installed against this build without one edit: the old commands run, the doctor reports no error, the + committed import map and `tokens.css` are still current, `tsc` passes, and it builds with webpack and with + Turbopack. This is the proof that an existing site upgrades with no change (`scripts/legacy-site-check.mjs`; + no database needed). With it: `test/legacyNames.test.ts` (every old name) and `test/legacyNameForms.test.ts` + (no new name is born with the old spelling). - [ ] **`pnpm e2e:built` green — required, no release without it.** It builds the reference site with webpack AND with Turbopack (with the late-staff fixture, `E2E_LATE_STAFF=1`) and runs, on each built site: the account rules of staff collections the project or a later plugin adds (`e2e/late-staff.spec.ts`), and "no package manifest among @@ -807,6 +814,7 @@ The site uses the plugin as `file:..` with `dependenciesMeta.injected`, so the p | package contract | `test/exports.test.ts` | every `@intecion/ipal-kit/…` path from the docs exists in `exports` | | docs ↔ code | `test/docsConsistency.test.ts` | names imported in the docs exist in the entry points / `lib/content`; every public export is described in the docs | | e2e | `pnpm test:e2e` (Playwright) | `pnpm test` = `test:int` + `test:e2e` | +| a site from before the rename | `pnpm legacy:site` (`scripts/legacy-site-check.mjs`); `test/legacyNames.test.ts`, `test/legacyNameForms.test.ts` | the `v1.16.7` reference site, unedited, on this build: old commands, doctor, import map, types, both bundlers; every old name still works; no new `ipal` name | | built site, both bundlers | `pnpm e2e:built` (`scripts/e2e-built.mjs`, the reference site) | what only a production bundle shows: nothing decided by a function's name, nothing private among the public files (§8.1) | Rules: **every fixed bug = a regression test** (check that it fails on the old code); diff --git a/package.json b/package.json index f39d47d..b21db25 100644 --- a/package.json +++ b/package.json @@ -118,6 +118,7 @@ "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/", "dev": "next dev dev --turbo", "e2e:built": "node scripts/e2e-built.mjs", + "legacy:site": "node scripts/legacy-site-check.mjs", "dev:generate-importmap": "pnpm dev:payload generate:importmap", "dev:generate-types": "pnpm dev:payload generate:types", "dev:payload": "cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload", diff --git a/scripts/legacy-site-check.mjs b/scripts/legacy-site-check.mjs new file mode 100644 index 0000000..afdceaa --- /dev/null +++ b/scripts/legacy-site-check.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/** + * pnpm legacy:site — a site written for the last release BEFORE the rename to IAPL works on this build, unedited. + * + * The reference site as it was at a tag (default v1.16.7: `ipalKit()`, `ipal-tokens`, `ipal-doctor.json`, `ipal-*` + * skills, the old pointer block) is unpacked next to the plugin and installed against the plugin built from this + * tree. Nothing in it is changed. Then: + * 1. the old commands run: `ipal-tokens --check`, `ipal-doctor` (no error; the warnings are printed); + * 2. `payload generate:importmap` leaves the committed import map byte for byte as it was; + * 3. `tsc --noEmit`: the old names still type-check; + * 4. a production build with webpack and one with Turbopack. + * + * Needs: the plugin built (`pnpm build`; --skip-plugin-build when dist is current), the tag in the local repository. + * The builds need no database (pages that read it are built on demand), but DATABASE_URI must be set to something. + * Options: --tag=v1.16.7 · --only=webpack|turbopack · --skip-build (steps 1–3 only) · --keep (leave the folder). + * The folder (.legacy-site-, git-ignored) is removed at the end unless --keep. + */ +import { spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const args = process.argv.slice(2) +const opt = (name, fallback) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback +const tag = opt('tag', 'v1.16.7') +const only = opt('only') +const bundlers = ['webpack', 'turbopack'].filter((b) => !only || b === only) +const site = path.join(root, `.legacy-site-${tag.replace(/[^\w.-]/g, '_')}`) +const env = { + ...process.env, + DATABASE_URI: process.env.DATABASE_URI ?? 'mongodb://127.0.0.1:27017/example-studiopl_dev', + NEXT_PUBLIC_SERVER_URL: process.env.NEXT_PUBLIC_SERVER_URL ?? 'http://localhost:3000', + NEXT_TELEMETRY_DISABLED: '1', + PAYLOAD_SECRET: process.env.PAYLOAD_SECRET ?? 'legacy-site-check-secret-0123456789abcdef', +} + +const results = [] +const sh = (label, command, commandArgs, { capture = false, cwd = site, allowFail = false } = {}) => { + console.log(`\n[legacy:site] ${label}`) + const res = spawnSync(command, commandArgs, { cwd, encoding: 'utf8', env, maxBuffer: 256 * 1024 * 1024, stdio: capture ? ['ignore', 'pipe', 'inherit'] : 'inherit' }) + if (res.status !== 0 && !allowFail) { + console.error(`\n[legacy:site] ✗ FAILED: ${label}`) + finish(1) + } + return res +} +const finish = (code) => { + if (!args.includes('--keep')) {rmSync(site, { force: true, recursive: true })} + for (const line of results) {console.log(`[legacy:site] ${line}`)} + process.exit(code) +} + +if (spawnSync('git', ['rev-parse', '--verify', '--quiet', `${tag}^{commit}`], { cwd: root }).status !== 0) { + console.error(`[legacy:site] tag ${tag} is not in this repository (git fetch --tags)`) + process.exit(2) +} +if (!args.includes('--skip-plugin-build')) {sh('build the plugin', 'pnpm', ['build'], { cwd: root })} +if (!existsSync(path.join(root, 'dist/index.js'))) { + console.error('[legacy:site] dist/ is missing — run pnpm build') + process.exit(2) +} + +rmSync(site, { force: true, recursive: true }) +mkdirSync(site, { recursive: true }) +// reference/ of the tag, unpacked as a direct child of the plugin root: its "file:.." dependency is this tree. +const archive = spawnSync('sh', ['-c', `git archive ${tag} reference | tar -x --strip-components=1 -C "${site}"`], { cwd: root, stdio: 'inherit' }) +if (archive.status !== 0) {finish(1)} +const config = readFileSync(path.join(site, 'src/payload.config.ts'), 'utf8') +if (!/\bipalKit\s*\(/.test(config)) { + console.error(`[legacy:site] ${tag}: the reference site does not call ipalKit() — pick a tag from before 1.17.0`) + finish(2) +} + +sh('install the old site against this build', 'pnpm', ['install', '--ignore-workspace', '--no-frozen-lockfile']) +const installed = JSON.parse(readFileSync(path.join(site, 'node_modules/@intecion/ipal-kit/package.json'), 'utf8')).version +results.push(`site of ${tag}, plugin ${installed} from this tree`) + +sh('old command: ipal-tokens --check', 'pnpm', ['exec', 'ipal-tokens', '--check']) +results.push('ipal-tokens --check: ok') + +const doctor = sh('old command: ipal-doctor (static, offline)', 'pnpm', ['exec', 'ipal-doctor', '.', '--offline', '--json'], { allowFail: true, capture: true }) +let report +try { + report = JSON.parse(doctor.stdout) +} catch { + console.error(doctor.stdout) + console.error('[legacy:site] ✗ ipal-doctor did not print JSON') + finish(1) +} +const open = report.findings.filter((f) => !f.silenced) +const count = (severity) => open.filter((f) => f.severity === severity) +for (const f of open.filter((x) => x.severity !== 'info')) {console.log(` ${f.severity}: ${f.rule} — ${f.message}`)} +results.push(`ipal-doctor: ${count('error').length} error(s), ${count('warning').length} warning(s) [${[...new Set(count('warning').map((f) => f.rule))].join(', ')}], ${count('info').length} info [${[...new Set(count('info').map((f) => f.rule))].join(', ')}]`) +if (count('error').length) { + console.error('[legacy:site] ✗ the doctor reports an error on a site that had none') + finish(1) +} + +const mapFile = path.join(site, 'src/app/(payload)/admin/importMap.js') +const mapBefore = readFileSync(mapFile, 'utf8') +sh('payload generate:importmap', 'pnpm', ['generate:importmap']) +if (readFileSync(mapFile, 'utf8') !== mapBefore) { + console.error('[legacy:site] ✗ the generated import map differs from the one the old site has committed') + finish(1) +} +results.push('import map: unchanged') + +sh('tsc --noEmit (old names against the new types)', 'pnpm', ['typecheck']) +results.push('typecheck: ok') + +if (!args.includes('--skip-build')) { + for (const bundler of bundlers) { + rmSync(path.join(site, '.next'), { force: true, recursive: true }) + sh(`production build, ${bundler}`, 'pnpm', ['exec', 'cross-env', 'NODE_OPTIONS=--max-old-space-size=3072', 'next', 'build', ...(bundler === 'webpack' ? ['--webpack'] : [])]) + results.push(`build (${bundler}): ok`) + } +} +console.log('\n[legacy:site] ✓ the old site works on this build') +finish(0) diff --git a/src/modules/doctor/rules/env.ts b/src/modules/doctor/rules/env.ts index 43a39e8..dfb1faf 100644 --- a/src/modules/doctor/rules/env.ts +++ b/src/modules/doctor/rules/env.ts @@ -1,6 +1,7 @@ import type { DoctorRule, RuleFinding } from '../types.js' import { databaseNameFromUri, databaseNamesFor } from '../../env/databaseName.js' +import { legacyEnvName } from '../../shared/envName.js' import { configFile } from '../project.js' import { stripComments } from '../util.js' @@ -77,12 +78,13 @@ export const envRules: DoctorRule[] = [ const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IAPL_IP_HEADER'] if (/buildR2Storage/.test(cfg) && !ctx.auditSkips.has('r2')) {want.push('R2_BUCKET', 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_PUBLIC_URL')} if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IAPL_COOKIE_SCAN_URL', 'IAPL_COOKIE_SCAN_TOKEN')} - const missing = want.filter((v) => !(v in ctx.env.example!)) + // a plugin variable under its spelling from before 1.17.0 (IPAL_…) is there too + const missing = want.filter((v) => !(v in ctx.env.example!) && !((legacyEnvName(v) ?? v) in ctx.env.example!)) if (missing.length) {out.push({ file: '.env.example', fix: 'add the names (empty or placeholder values)', message: `.env.example lacks ${missing.join(', ')}`, severity: 'warning' })} // A real-looking credential in a committed file. const creds = (ctx.env.example.DATABASE_URI ?? '').match(/^[a-z+]+:\/\/([^@/]+)@/i)?.[1] if (creds && !PLACEHOLDER.test(creds)) {out.push({ file: '.env.example', fix: 'replace with USER:PASS', message: 'DATABASE_URI in .env.example carries credentials', severity: 'error' })} - for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IAPL_DOCTOR_TOKEN']) { + for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IAPL_DOCTOR_TOKEN', 'IPAL_DOCTOR_TOKEN']) { const value = ctx.env.example[key] if (value && value.length >= 16 && !PLACEHOLDER.test(value)) {out.push({ file: '.env.example', fix: `leave ${key} empty`, message: `${key} in .env.example has a value`, severity: 'error' })} } diff --git a/src/modules/doctor/rules/seeds.ts b/src/modules/doctor/rules/seeds.ts index 6342dc6..3d78a60 100644 --- a/src/modules/doctor/rules/seeds.ts +++ b/src/modules/doctor/rules/seeds.ts @@ -32,7 +32,7 @@ export const seedRules: DoctorRule[] = [ for (const [name, command] of Object.entries(ctx.pkg.scripts ?? {})) { if (!/seed/i.test(name)) {continue} if (/fresh|reset/i.test(name)) {out.push({ file: 'package.json', fix: 'remove it — seeds never delete (seeding.md)', message: `script "${name}" re-creates content from scratch`, severity: 'error' })} - if (/IAPL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IAPL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })} + if (/I(?:AP|PA)L_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IAPL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })} const entry = command.match(/(?:^|\s)([\w./@-]+\.[cm]?[jt]s)(?:\s|$)/)?.[1]?.replace(/^\.\//, '') if (!entry) {continue} if (!ctx.exists(entry)) {out.push({ file: 'package.json', message: `script "${name}" runs ${entry}, which does not exist`, severity: 'warning' }); continue} @@ -45,7 +45,7 @@ export const seedRules: DoctorRule[] = [ if (ctx.launched && /createSeeder\s*\(/.test(code) && !/\bonly\s*:/.test(code)) {out.push({ file: entry, fix: 'run it with SEED_ONLY="pages:,global:" or pass only: [...] (seeding.md → after launch)', message: `script "${name}" has no record list — after launch every run needs SEED_ONLY`, severity: 'warning' })} } for (const file of ['.env.example', '.env.production']) { - if (/^\s*IAPL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IAPL_SEED_ALLOW_FULL=1`, severity: 'error' })} + if (/^\s*I(?:AP|PA)L_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IAPL_SEED_ALLOW_FULL=1`, severity: 'error' })} } return out }, diff --git a/src/modules/tokens/cli.ts b/src/modules/tokens/cli.ts index 40bc4db..0c832af 100644 --- a/src/modules/tokens/cli.ts +++ b/src/modules/tokens/cli.ts @@ -46,6 +46,9 @@ async function loadTokens(file: string): Promise { } } +/** The two header lines of a generated file that name the command (`ipal-tokens` before 1.17.0). */ +const LEGACY_HEADER = /^ \* (?:GENERATED by `ipal-tokens` from|`pnpm exec ipal-tokens`\.) .*$/gm + /** The `iapl-tokens` command. Returns the exit code. */ export async function runTokensCli(args: string[], { cwd = process.cwd(), log = (line: string) => process.stdout.write(`${line}\n`) }: { cwd?: string; log?: Log } = {}): Promise { if (args.includes('--help') || args.includes('-h')) { @@ -64,7 +67,8 @@ export async function runTokensCli(args: string[], { cwd = process.cwd(), log = const current = existsSync(output) ? readFileSync(output, 'utf8') : null let code = 0 if (args.includes('--check')) { - if (current !== css) { + // A file written before 1.17.0 names the command `ipal-tokens` in its header: the same tokens, not out of date. + if (current !== css && current?.replace(LEGACY_HEADER, (line) => line.replace('ipal-tokens', 'iapl-tokens')) !== css) { log(`✗ ${relative(cwd, output)} is out of date — run \`pnpm exec iapl-tokens\``) code = 1 } else {log(`✓ ${relative(cwd, output)} is up to date`)} diff --git a/test/designTokens.test.ts b/test/designTokens.test.ts index d3425c4..0839d23 100644 --- a/test/designTokens.test.ts +++ b/test/designTokens.test.ts @@ -194,6 +194,20 @@ describe('iapl-tokens CLI', () => { expect(lines.join('\n')).toMatch(/out of date/) }) + test('a file generated before 1.17.0 (header names `ipal-tokens`) is up to date; a changed value is not', async () => { + writeFileSync(path.join(dir, 'tokens.json'), JSON.stringify({ color: { light: { primary: '#1d4ed8' } } })) + const args = ['--in', 'tokens.json', '--out', 'out/tokens.css'] + expect(await runTokensCli(args, { cwd: dir, log })).toBe(0) + const file = path.join(dir, 'out/tokens.css') + const old = readFileSync(file, 'utf8').replaceAll('iapl-tokens', 'ipal-tokens') + expect(old).toContain('GENERATED by `ipal-tokens`') + writeFileSync(file, old) + expect(await runTokensCli([...args, '--check'], { cwd: dir, log })).toBe(0) + expect(readFileSync(file, 'utf8')).toBe(old) // --check writes nothing + writeFileSync(file, old.replace('#1d4ed8', '#000000')) + expect(await runTokensCli([...args, '--check'], { cwd: dir, log })).toBe(1) + }) + test('fails on a contrast error unless --warn-only', async () => { writeFileSync(path.join(dir, 'tokens.json'), JSON.stringify({ color: { light: { primary: '#ffeb3b' } } })) const args = ['--in', 'tokens.json', '--out', 'tokens.css'] diff --git a/test/fixtures/legacyNameForms.json b/test/fixtures/legacyNameForms.json new file mode 100644 index 0000000..1d5af11 --- /dev/null +++ b/test/fixtures/legacyNameForms.json @@ -0,0 +1,113 @@ +[ + "--ipal-*", + "2Fipal-kit", + "IPAL", + "IPAL_", + "IPAL_BREAKPOINTS", + "IPAL_COOKIE_SCAN_TOKEN", + "IPAL_COOKIE_SCAN_URL", + "IPAL_COPY_BASELINE", + "IPAL_CRAWLER_SITES", + "IPAL_DEV_2FA", + "IPAL_DOCTOR_IMPORT_MAP", + "IPAL_DOCTOR_TOKEN", + "IPAL_IP_HEADER", + "IPAL_NOINDEX", + "IPAL_SEED_ALLOW_FULL", + "IPAL_SEED_ALLOW_PROD_UPDATE", + "IPAL_TEST_MONGO_URI", + "IPAL_TEST_POSTGRES_URI", + "IPAL_TEST_SHAPE", + "IPAL_TOKENS", + "IpalEnvFeatures", + "IpalGlobalSlug", + "IpalOptions", + "IpalTokenName", + "X-Ipal-Cookie-Crawler", + "__ipal-other__", + "__ipal-outsider__", + "_ipalSyncingCrossLocale", + "data-ipal*", + "ipal", + "ipal-", + "ipal-a", + "ipal-audit-skip", + "ipal-b", + "ipal-badge*", + "ipal-bar", + "ipal-blocks", + "ipal-consent-*", + "ipal-cookie-approval", + "ipal-cookie-crawler", + "ipal-cookie-scan", + "ipal-cookie-scan-names", + "ipal-cs-", + "ipal-doctor", + "ipal-eject-", + "ipal-ext-*", + "ipal-f-*", + "ipal-forms-mailbox", + "ipal-graph", + "ipal-group", + "ipal-importmap-", + "ipal-kit", + "ipal-kit-", + "ipal-label", + "ipal-lightbox-caption", + "ipal-linkedin-insight", + "ipal-locale", + "ipal-mail-dispatcher", + "ipal-old", + "ipal-pad", + "ipal-panel-smtp", + "ipal-polish-", + "ipal-primary", + "ipal-release", + "ipal-row", + "ipal-safe-back", + "ipal-sandbox", + "ipal-second-factor-guard", + "ipal-sites-", + "ipal-skills", + "ipal-starter-gate-*", + "ipal-stats*", + "ipal-test-*", + "ipal-theme", + "ipal-tokens", + "ipal-tokens-not-installed", + "ipal-totp-view", + "ipal-two-factor-*", + "ipal-value", + "ipalAccountRules", + "ipalAccounts", + "ipalBlock", + "ipalCookieApproval", + "ipalCookieReview", + "ipalCookieScan", + "ipalCookieSiteCheck", + "ipalEnvRules", + "ipalFillLocales", + "ipalFirstRegister", + "ipalFirstUser", + "ipalFormFiles", + "ipalIntegrationStatus", + "ipalKit", + "ipalLibrary", + "ipalMigration", + "ipalSafeBack", + "ipalSeed", + "ipalSkipAutoFill", + "ipalSkipIndexNow", + "ipalStats", + "ipalT", + "ipalTestBoundary", + "ipalTotpClientProps", + "ipalTotpView", + "ipalVar", + "ipalWriteOnly", + "ipal_vid", + "missing-forms-in-ipalkit", + "missing-ipal-ip-header-in-env-example", + "names-iapl-and-ipal-kit", + "nav-ipal-stats" +] diff --git a/test/legacyNameForms.test.ts b/test/legacyNameForms.test.ts new file mode 100644 index 0000000..2edd2e3 --- /dev/null +++ b/test/legacyNameForms.test.ts @@ -0,0 +1,64 @@ +/** + * The spellings with `ipal` that are still in the repository, as a closed list. + * + * Since 1.17.0 the plugin is IAPL (docs/dev/rename-iapl-plan.md). What keeps the old letters is either + * a name a site depends on (the package, routes, CSS tokens, `custom.ipal`, context flags, the cookie, + * the kv key), an alias kept for 1.x, or a test's own scratch name. A NEW name must not be born with the + * old letters: this test fails when a form appears that is not in test/fixtures/legacyNameForms.json. + * + * - meant to write `iapl`? fix the spelling (the two differ by two swapped letters); + * - a real addition to the list (rare)? UPDATE_LEGACY_FORMS=1 pnpm vitest run test/legacyNameForms.test.ts + * and say why in the commit. + * + * Not searched: past changelog entries, the proposals in docs/dev, the vendored external skills, the + * lockfiles, the reference site's copy of the skills, and the two tests about the old names. + */ +import { execFileSync } from 'node:child_process' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { expect, test } from 'vitest' + +const root = path.resolve(import.meta.dirname, '..') +const FIXTURE = path.join(root, 'test/fixtures/legacyNameForms.json') +const SKIP = /^docs\/CHANGELOG\.md$|^docs\/dev\/.*proposal\.md$|^docs\/dev\/rename-iapl-plan\.md$|^docs\/agent\/external\/|pnpm-lock\.yaml$|package-lock\.json$|^reference\/\.agents\/|^test\/legacyName|^test\/fixtures\/legacyNameForms\.json$/ +const TEXT = /\.(?:md|ts|tsx|mjs|js|json|css|scss|sh|yml|yaml|html|txt)$|^[^.]+$|\/Dockerfile$|\.npmrc$|\.env\.example$/ + +/** Families counted as one form: design tokens, data hooks, element ids and scratch names with a varying tail. */ +const FAMILIES: Array<[RegExp, string]> = [ + [/^--ipal-/, '--ipal-*'], + [/^data-ipal/, 'data-ipal*'], + [/^ipal-test-/, 'ipal-test-*'], + [/^ipal-stats/, 'ipal-stats*'], + [/^ipal-badge/, 'ipal-badge*'], + [/^ipal-f-/, 'ipal-f-*'], + [/^ipal-consent-/, 'ipal-consent-*'], + [/^ipal-two-factor-/, 'ipal-two-factor-*'], + [/^ipal-ext-/, 'ipal-ext-*'], + [/^ipal-starter-gate-/, 'ipal-starter-gate-*'], +] + +function forms(): string[] { + const files = execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }).split('\0').filter((f) => f && !SKIP.test(f) && TEXT.test(f)) + const found = new Set() + for (const file of files) { + const full = path.join(root, file) + if (!existsSync(full)) {continue} + for (const m of readFileSync(full, 'utf8').matchAll(/[\w-]*ipal[\w-]*/gi)) { + found.add(FAMILIES.find(([pattern]) => pattern.test(m[0]))?.[1] ?? m[0]) + } + } + return [...found].sort() +} + +test('no new name carries the old spelling', () => { + const now = forms() + if (process.env.UPDATE_LEGACY_FORMS === '1') {writeFileSync(FIXTURE, `${JSON.stringify(now, null, 2)}\n`)} + const allowed = JSON.parse(readFileSync(FIXTURE, 'utf8')) as string[] + expect(now.filter((form) => !allowed.includes(form)), 'new forms with "ipal" — see the comment at the top of this test').toEqual([]) +}) + +test('the list holds nothing that is gone', () => { + const now = forms() + const allowed = JSON.parse(readFileSync(FIXTURE, 'utf8')) as string[] + expect(allowed.filter((form) => !now.includes(form)), 'forms no longer in the repository — remove them from the list').toEqual([]) +}) diff --git a/test/legacyNames.test.ts b/test/legacyNames.test.ts index b663100..6fec521 100644 --- a/test/legacyNames.test.ts +++ b/test/legacyNames.test.ts @@ -199,6 +199,22 @@ describe('the doctor on a project that was not touched', () => { expect((await run(dir, ['legacy-names'])).findings.filter((f) => f.severity === 'warning')).toEqual([]) }) + test('IPAL_* names in .env.example satisfy env-example; IPAL_SEED_ALLOW_FULL=1 is still caught', async () => { + const example = 'DATABASE_URI=\nPAYLOAD_SECRET=\nNEXT_PUBLIC_SERVER_URL=\nIPAL_IP_HEADER=\nIPAL_COOKIE_SCAN_URL=\nIPAL_COOKIE_SCAN_TOKEN=\n' + const config = "export default { plugins: [ipalKit({ cookieScanner: { crawl: true } })] }\n" + const ok = site({ '.env.example': example, 'src/payload.config.ts': config }) + expect((await run(ok, ['env-example'])).findings.filter((f) => f.rule === 'env-example')).toEqual([]) + const bad = site({ + '.env.example': `${example}IPAL_SEED_ALLOW_FULL=1\nIPAL_DOCTOR_TOKEN=0123456789abcdef0123456789abcdef\n`, + 'package.json': { name: 'x', scripts: { 'seed:all': 'IPAL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } }, + 'src/payload.config.ts': config, + }) + const messages = (await run(bad, ['env-example', 'seed-named'])).findings.map((f) => f.message).join('\n') + expect(messages).toMatch(/IPAL_DOCTOR_TOKEN in \.env\.example has a value/) + expect(messages).toMatch(/\.env\.example sets IAPL_SEED_ALLOW_FULL=1/) + expect(messages).toMatch(/script "seed:all" switc/) + }) + test('storage-names: the cookie the page sets must be the one the scanner declares', async () => { const layout = (props: string) => `import { PageStats } from '@intecion/ipal-kit/client'\nexport default function L() { return }\n` const config = (names: string) => `import { iapl } from '@intecion/ipal-kit'\nexport default { plugins: [iapl({ ${names} })] }\n`