diff --git a/.github/scripts/api-navigation.test.mjs b/.github/scripts/api-navigation.test.mjs index 8a693e3f..b0545831 100644 --- a/.github/scripts/api-navigation.test.mjs +++ b/.github/scripts/api-navigation.test.mjs @@ -16,7 +16,7 @@ function fixture(t) { mkdirSync(join(root, '.github/scripts'), { recursive: true }); mkdirSync(join(root, 'api-reference')); mkdirSync(join(root, 'guides')); - for (const file of ['api-navigation.mjs', 'generate-sitemap.mjs', 'check-redirect-destinations.mjs', 'detect-new-endpoints.mjs', 'yaml-lite.mjs', 'clean-openapi.mjs', 'sync-api-group-tags.mjs']) { + for (const file of ['api-navigation.mjs', 'generate-sitemap.mjs', 'check-redirect-destinations.mjs', 'detect-new-endpoints.mjs', 'prune-removed-endpoints.mjs', 'yaml-lite.mjs', 'clean-openapi.mjs', 'sync-api-group-tags.mjs']) { copyFileSync(join(scripts, file), join(root, '.github/scripts', file)); } const spec = { @@ -178,3 +178,51 @@ test('group badges follow all child operations and stale badges fail validation assert.match(missing.stderr, /operation missing from schema/); assert.deepEqual(JSON.parse(readFileSync(join(root, 'docs.json'), 'utf8')), docs); }); + +test('endpoints that leave the spec lose their page and redirect to the next page in their group', (t) => { + const { root, spec, docs, run } = fixture(t); + writeFileSync(join(root, 'previous.json'), JSON.stringify(spec)); + mkdirSync(join(root, 'api-reference/old')); + writeFileSync(join(root, 'api-reference/old/get-old.mdx'), '---\nopenapi: get /old/\n---\n'); + docs.navigation.tabs[0].pages[0].pages.push({ group: 'Old', pages: ['api-reference/old/get-old'] }, { group: 'Placeholder', pages: [] }); + writeFileSync(join(root, 'docs.json'), JSON.stringify(docs)); + delete spec.paths['/probe']; + writeFileSync(join(root, 'api-reference/openapi.json'), JSON.stringify(spec)); + + const summary = join(root, 'pruned.md'); + const result = spawnSync(process.execPath, [join(root, '.github/scripts/prune-removed-endpoints.mjs'), 'previous.json'], { + cwd: root, encoding: 'utf8', env: { ...process.env, PRUNED_ENDPOINTS_FILE: summary }, + }); + assert.equal(result.status, 0, result.stderr); + const updated = JSON.parse(readFileSync(join(root, 'docs.json'), 'utf8')); + const groups = updated.navigation.tabs[0].pages[0].pages; + assert.deepEqual(groups.map((g) => g.group), ['Usage', 'Placeholder'], 'only the group this run emptied is dropped'); + assert.deepEqual(groups[0].pages, ['guides/example']); + assert.ok(!existsSync(join(root, 'api-reference/old/get-old.mdx'))); + assert.deepEqual(updated.redirects, [ + { source: '/api-reference/old/get-old', destination: '/api-reference/overview' }, + { source: href, destination: '/guides/example' }, + { source: '/reference/getprobe', destination: '/guides/example' }, + ]); + const lines = readFileSync(summary, 'utf8').trim().split('\n'); + assert.equal(lines.length, 2); + assert.match(lines[0], /GET \/probe/); + + // The rest of the sync job runs cleanly on the pruned menu. + assert.equal(run('detect-new-endpoints.mjs').status, 0); + assert.equal(run('generate-sitemap.mjs').status, 0); + writeFileSync(join(root, 'api-reference/overview.mdx'), '---\ntitle: Overview\n---\n'); + const redirects = run('check-redirect-destinations.mjs'); + assert.equal(redirects.status, 0, redirects.stderr); + + const again = run('prune-removed-endpoints.mjs', 'previous.json'); + assert.equal(again.status, 0, again.stderr); + assert.deepEqual(JSON.parse(readFileSync(join(root, 'docs.json'), 'utf8')), updated); +}); + +test('pruning leaves the menu alone while every endpoint is in the spec', (t) => { + const { root, docs, run } = fixture(t); + const result = run('prune-removed-endpoints.mjs', 'api-reference/openapi.json'); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(readFileSync(join(root, 'docs.json'), 'utf8')), docs); +}); diff --git a/.github/scripts/prune-removed-endpoints.mjs b/.github/scripts/prune-removed-endpoints.mjs new file mode 100644 index 00000000..fe466314 --- /dev/null +++ b/.github/scripts/prune-removed-endpoints.mjs @@ -0,0 +1,180 @@ +#!/usr/bin/env node + +/** + * prune-removed-endpoints.mjs + * + * Remove API reference pages for endpoints that are no longer in the spec, + * so the spec sync job does not stop on them. Runs after the new spec has + * been written to api-reference/openapi.json and before + * detect-new-endpoints.mjs. + * + * For each menu entry whose endpoint is gone, it: + * - removes the entry from docs.json, + * - deletes the MDX stub, if the page was one, + * - redirects the old URL to the first remaining page of the same menu + * group (or the API reference overview), and points existing redirects + * that ended at the old URL to the same place. + * + * Schema-generated pages take their URL from x-mint.href, which only the + * previous spec still has. It is read from git (HEAD), or from the path + * given as the first argument. + * + * Env vars: + * DRY_RUN=1 — log what would change, don't write files + * PRUNED_ENDPOINTS_FILE=... — append one Markdown list line per removed + * endpoint, for the PR description + */ + +import { appendFileSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { join } from 'node:path'; +import { OPENAPI_ENDPOINT, readOpenApiSpec } from './api-navigation.mjs'; + +const DRY_RUN = process.env.DRY_RUN === '1'; +const ROOT = process.cwd(); +const SPEC_FILE = 'api-reference/openapi.json'; +const DOCS_JSON_PATH = join(ROOT, 'docs.json'); +const FALLBACK_DESTINATION = '/api-reference/overview'; +const MDX_ENDPOINT = /^openapi:\s*(get|post|put|patch|delete)\s+(\/\S+)\s*$/im; + +function normalisePath(p) { + return p.length > 1 ? p.replace(/\/+$/, '') : p; +} + +// Look an operation up regardless of trailing-slash convention. +function findOperation(spec, path, method) { + const wanted = normalisePath(path); + for (const [specPath, methods] of Object.entries(spec.paths ?? {})) { + if (normalisePath(specPath) === wanted && methods?.[method]) return methods[method]; + } + return undefined; +} + +function loadPreviousSpec(argPath) { + if (argPath) return readOpenApiSpec(argPath); + try { + return JSON.parse(execFileSync('git', ['show', `HEAD:${SPEC_FILE}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })); + } catch { + // No history to compare with: schema-generated pages lose their redirect, + // but MDX pages still get one from their own path. + return { paths: {} }; + } +} + +const hrefOf = (operation) => operation?.['x-mint']?.href; +const toUrl = (slug) => `/${slug.replace(/^\/+|\/+$/g, '')}`; + +// Describe a menu entry: which endpoint it documents and the URL it serves. +function describeEntry(page) { + const native = page.match(OPENAPI_ENDPOINT); + if (native) { + const [, source, verb, path] = native; + return { kind: 'native', source, method: verb.toLowerCase(), path }; + } + const file = join(ROOT, `${page}.mdx`); + if (!page.startsWith('api-reference/') || !existsSync(file)) return null; + const match = readFileSync(file, 'utf8').match(MDX_ENDPOINT); + if (!match) return null; + return { kind: 'mdx', file, method: match[1].toLowerCase(), path: match[2], url: toUrl(page) }; +} + +// The URL a remaining menu entry is served at, or null if it has none. +function urlOfEntry(page, spec) { + if (typeof page !== 'string') return null; + const native = page.match(OPENAPI_ENDPOINT); + if (!native) return toUrl(page); + const href = hrefOf(findOperation(spec, native[3], native[2].toLowerCase())); + return href ? toUrl(href) : null; +} + +// A group whose last page this run removed would show as an empty menu +// heading. Groups that were already empty are left as they are. +function dropEmptiedGroups(node, emptied) { + if (Array.isArray(node)) return node.forEach((child) => dropEmptiedGroups(child, emptied)); + if (!node || typeof node !== 'object') return; + for (const value of Object.values(node)) { + dropEmptiedGroups(value, emptied); + if (!Array.isArray(value)) continue; + const kept = value.filter((child) => !(child && typeof child === 'object' && emptied.has(child.pages))); + value.splice(0, value.length, ...kept); + } +} + +function pruneRemovedEndpoints({ docs, spec, previousSpec }) { + const removed = []; + const emptied = new Set(); + + function walk(node) { + if (Array.isArray(node)) return node.forEach(walk); + if (!node || typeof node !== 'object') return; + for (const [key, value] of Object.entries(node)) { + if (key !== 'pages' || !Array.isArray(value)) { walk(value); continue; } + const gone = []; + for (const page of value) { + if (typeof page !== 'string') { walk(page); continue; } + const entry = describeEntry(page); + if (!entry) continue; + // Other spec files are not synced by this job; leave them alone. + if (entry.kind === 'native' && entry.source !== SPEC_FILE) continue; + if (findOperation(spec, entry.path, entry.method)) continue; + const oldHref = hrefOf(findOperation(previousSpec, entry.path, entry.method)); + const url = entry.kind === 'mdx' ? entry.url : oldHref ? toUrl(oldHref) : null; + gone.push({ page, ...entry, url }); + } + if (!gone.length) continue; + const remaining = value.filter((page) => !gone.some((g) => g.page === page)); + value.splice(0, value.length, ...remaining); + if (!remaining.length) emptied.add(value); + const destination = remaining.map((page) => urlOfEntry(page, spec)).find(Boolean) ?? FALLBACK_DESTINATION; + for (const g of gone) removed.push({ ...g, destination }); + } + } + walk(docs.navigation); + if (emptied.size) dropEmptiedGroups(docs.navigation, emptied); + + docs.redirects ??= []; + for (const r of removed) { + if (!r.url) continue; + for (const redirect of docs.redirects) { + if (redirect.destination.split('#')[0] === r.url) redirect.destination = r.destination; + } + if (!docs.redirects.some((redirect) => redirect.source === r.url)) { + docs.redirects.unshift({ source: r.url, destination: r.destination }); + } + } + return removed; +} + +function main() { + const docs = JSON.parse(readFileSync(DOCS_JSON_PATH, 'utf8')); + const spec = readOpenApiSpec(join(ROOT, SPEC_FILE)); + const previousSpec = loadPreviousSpec(process.argv[2]); + const removed = pruneRemovedEndpoints({ docs, spec, previousSpec }); + + if (!removed.length) { + console.log('✅ Every API reference page still has its endpoint in the spec.'); + return; + } + + console.log(`🗑 ${removed.length} endpoint(s) left the spec:\n`); + const lines = []; + for (const r of removed) { + const key = `${r.method.toUpperCase()} ${r.path}`; + const where = r.url ? `${r.url} → ${r.destination}` : 'no old URL known, no redirect added'; + console.log(` - ${key}: ${where}`); + lines.push(r.url + ? `- \`${key}\`: removed \`${r.url}\`, redirected to \`${r.destination}\`` + : `- \`${key}\`: removed from the menu (no old URL known, no redirect added)`); + if (r.kind === 'mdx' && !DRY_RUN) rmSync(r.file); + } + + if (!DRY_RUN) writeFileSync(DOCS_JSON_PATH, JSON.stringify(docs, null, 2) + '\n'); + if (process.env.PRUNED_ENDPOINTS_FILE) appendFileSync(process.env.PRUNED_ENDPOINTS_FILE, lines.join('\n') + '\n'); +} + +try { + main(); +} catch (err) { + console.error('❌ Fatal error:', err); + process.exit(1); +} diff --git a/.github/workflows/update-api-spec.yml b/.github/workflows/update-api-spec.yml index 29b59272..a4a64057 100644 --- a/.github/workflows/update-api-spec.yml +++ b/.github/workflows/update-api-spec.yml @@ -51,6 +51,13 @@ jobs: - name: Fetch latest API specification run: ./update-api-spec.sh + # Endpoints can also leave the spec. Their menu entries would otherwise + # stop every later step, so they are removed and redirected first. + - name: Remove pages of endpoints that left the spec + env: + PRUNED_ENDPOINTS_FILE: ${{ runner.temp }}/pruned-endpoints.md + run: node .github/scripts/prune-removed-endpoints.mjs + - name: Generate pages for any new endpoints run: node .github/scripts/detect-new-endpoints.mjs @@ -66,6 +73,7 @@ jobs: - name: Create or update API spec PR if anything changed env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PRUNED_ENDPOINTS_FILE: ${{ runner.temp }}/pruned-endpoints.md run: | set -euo pipefail @@ -83,6 +91,10 @@ jobs: SPEC_CHANGED=1 fi NEW_PAGES=$(git diff --cached --name-only --diff-filter=A | grep -c '^api-reference/.*\.mdx$' || true) + REMOVED=0 + if [ -s "$PRUNED_ENDPOINTS_FILE" ]; then + REMOVED=$(grep -c '^- ' "$PRUNED_ENDPOINTS_FILE" || true) + fi DOCS_JSON_CHANGED=0 if git diff --cached --name-only | grep -q '^docs\.json$'; then DOCS_JSON_CHANGED=1 @@ -114,8 +126,17 @@ jobs: echo "" echo "- Spec changed: $([ "$SPEC_CHANGED" = "1" ] && echo yes || echo no)" echo "- New endpoint pages: $NEW_PAGES" + echo "- Removed endpoint pages: $REMOVED" echo "- \`docs.json\` updated: $([ "$DOCS_JSON_CHANGED" = "1" ] && echo yes || echo no)" echo "" + if [ "$REMOVED" -gt 0 ]; then + echo "## Endpoints that left the spec" + echo "" + echo "Their pages were removed and their old URLs redirected to the next page in the same menu group. Auto-merge is off for this PR. Check that each redirect target fits and that no page still links to a removed URL, then merge." + echo "" + cat "$PRUNED_ENDPOINTS_FILE" + echo "" + fi echo "This PR reuses the \`$BRANCH\` branch so future runs update this PR instead of opening duplicates." echo "" echo "---" @@ -147,12 +168,18 @@ jobs: echo "Created $PR_URL" fi + # Removed endpoints need a person to check the redirects, so they + # turn auto-merge off, also if an earlier run turned it on. + if [ "$REMOVED" -gt 0 ]; then + gh pr merge "$PR_URL" --disable-auto || true + echo "::warning::$REMOVED endpoint(s) left the spec. Auto-merge is off for $PR_URL until someone reviews it." # Try to enable auto-merge, but do not create another PR if GitHub # requires manual approval before pull_request workflows can run. - if ! gh pr merge "$PR_URL" --squash --auto --delete-branch; then + elif ! gh pr merge "$PR_URL" --squash --auto --delete-branch; then echo "::notice::Could not enable auto-merge for $PR_URL. The stable branch will be updated by the next run instead of opening another PR." fi + # Only a successful run pings, so a failed run shows up in Checkly as a + # missed heartbeat. - name: Ping Checkly - if: always() run: curl -fsS --retry 3 https://ping.checklyhq.com/ad576f21-3f3e-4a6a-b8e4-67fd0f6ed92d