Files
supabase/e2e/docs/utils/resolve-docs-scope.ts
T
Alexis Aguilar c1330ca99f ci(docs): scan every docs guide for accessibility issues daily (#54339)
## Problem

Since #53899, Docs E2E skips the accessibility scan on every CI run,
because the scan is slow and only covers the pages a diff names. Nothing
checks docs accessibility automatically, and a change to a shared
component can break pages that no pull request lists.

## Solution

A new **Docs Accessibility Scan** workflow scans every MDX guide on
production once a day.

- `.github/workflows/docs-a11y-scan.yml` runs `pnpm e2e:docs:all --grep
@a11y` against `https://supabase.com` at 05:17 UTC, off the top of the
hour when GitHub can delay or drop scheduled runs, and on demand through
`workflow_dispatch`. Its concurrency group includes the ref, so a manual
run on a branch can't cancel the scheduled run on `master`. It uploads
the Playwright report when the scan fails.
- `docs-master-alert.yml` now watches the new workflow, so a failed run
posts to the docs alerts Slack channel the same way the Production Smoke
Tests do.
- The shared alert no longer names the latest `master` commit and its
author. That commit often didn't cause the failure: a scheduled or
manual run tests whatever is deployed, and a workflow that was already
failing keeps failing on later commits. The alert now names the
workflow, says whether a push, schedule, or manual run failed, and links
the run. This applies to every workflow the alert watches.
- The scope resolver skips guides that `static-redirects.json` sends
elsewhere, in both the pull request scope and the full run. A redirected
guide has no docs article to scan, so it could never pass. Today that's
only `getting-started/features`. Docs E2E's sparse checkout now includes
`apps/docs/lib/redirects` so the resolver can read the file. One helper
lists every guide with no docs article to test (nav-disabled and
redirected), and both resolvers use it.
- The README says where and when the scans run, which checks fail the
scan, and how to start one by hand. It also lists guides with no MDX
file, such as the CLI and self-hosting config pages, as a known
limitation: the full run only resolves MDX guides, so the scan skips
them.

The full run doesn't need sharding. A list over 20 pages already runs on
3 workers, and the whole site took 15.3 minutes against production,
inside the job's 45-minute timeout.

## Known failures

A full run against production on 2026-11-30 failed on 5 guides with real
accessibility issues: 4 `duplicate-id` and 1 `heading-order`. Until
[DOCS-1817](https://linear.app/supabase/issue/DOCS-1817/fix-the-accessibility-issues-the-daily-docs-scan-finds-on-5-guides)
fixes them, each daily run fails and posts an alert.

## Follow-ups

-
[DOCS-1831](https://linear.app/supabase/issue/DOCS-1831/trace-each-docs-accessibility-scan-failure-to-the-commit-that):
keep a list of open failures in every docs alert, each with the commit
that introduced it, or its possible commits marked unconfirmed.

## Review instructions

1. Run `pnpm -C e2e/docs test` and confirm all 15 tests pass, including
the two redirect tests.
2. Confirm a change to a redirected guide resolves to no pages:
   ```bash
printf 'apps/docs/content/guides/getting-started/features.mdx\n' | pnpm
-C e2e/docs resolve-docs-scope
   ```
   Expect `skip=true`.
3. Run the scan the way the workflow does, on one passing guide and one
guide from DOCS-1817:
   ```bash
cd e2e/docs && PLAYWRIGHT_BASE_URL=https://supabase.com
DOCS_E2E_PAGE_PATHS=/docs/guides/auth,/docs/guides/resources pnpm exec
playwright test --grep @a11y
   ```
Expect `/docs/guides/auth` to pass and `/docs/guides/resources` to fail
on `heading-order`.
4. Check the alert payload. Copy the `run` script from
`docs-master-alert.yml`, replace the `curl` call with `echo "$PAYLOAD"`,
and run it with `TRIGGER` set to `push`, then `schedule`. Expect no
commit or author in either, and the run type in the workflow line.
5. After merge, start the workflow with `gh workflow run
docs-a11y-scan.yml` and confirm it finishes in about 15 to 20 minutes.

Verified locally: unit tests, mutation probes on both redirect tests,
typecheck, actionlint on the changed workflows, the alert payload for
push, scheduled, and manual runs, the resolver on a sparse checkout like
the workflow's, and a full-site scan against production. A scheduled
workflow only runs from `master`, so the workflow itself hasn't run on
GitHub yet.

Resolves
[DOCS-1816](https://linear.app/supabase/issue/DOCS-1816/run-the-docs-e2e-accessibility-scan-on-a-schedule-across-the-whole)
Resolves
[DOCS-1826](https://linear.app/supabase/issue/DOCS-1826/word-docs-slack-alerts-for-scheduled-workflow-failures-without-blaming)

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
2026-12-01 14:24:35 -07:00

313 lines
10 KiB
TypeScript

import { readdir, readFile } from 'node:fs/promises'
import { basename, join, relative } from 'node:path'
import { normalizeRepoPath } from '../../shared/paths.ts'
export const FEDERATED_SECTIONS = [
'graphql',
'database/extensions/wrappers',
'ai/python',
'deployment/terraform',
'deployment/ci',
] as const
const GUIDES_PREFIX = 'apps/docs/content/guides/'
const PARTIALS_PREFIX = 'apps/docs/content/_partials/'
const DOCS_GUIDES_URL_PREFIX = '/docs/guides/'
const FEDERATED_CONTENT_SOURCES_DIR = 'apps/docs/scripts/federated-content/sources'
const STATIC_REDIRECTS_FILE = 'apps/docs/lib/redirects/static-redirects.json'
export const GUIDE_LIST_COMPONENT =
'apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideListItems.tsx'
export const GUIDE_LIST_COMPONENT_PAGES = [
'/docs/guides/getting-started/api-keys',
'/docs/guides/getting-started/quickstarts/nextjs',
'/docs/guides/integrations/build-a-supabase-oauth-integration/oauth-scopes',
]
// the nav disables these guides, so the docs app returns 404 for their html page
const NAV_DISABLED_PAGES = new Set(['/docs/guides/ai-tools/agent-feedback'])
// guides with no docs article to test: nav-disabled guides, and guides that redirect elsewhere
async function loadUntestablePages(repoRoot: string): Promise<Set<string>> {
const redirects: unknown = JSON.parse(
await readFile(join(repoRoot, STATIC_REDIRECTS_FILE), 'utf8')
)
if (!Array.isArray(redirects)) {
throw new Error(`${STATIC_REDIRECTS_FILE} should be an array of redirects.`)
}
const redirectedPages = redirects.flatMap((redirect) =>
typeof redirect?.source === 'string' ? [redirect.source] : []
)
return new Set([...NAV_DISABLED_PAGES, ...redirectedPages])
}
const PARTIAL_PATH_RE = /<\$Partial\b[\s\S]*?\bpath\s*=\s*"([^"]+)"[\s\S]*?\/?>/g
const SOURCE_SECTION_RE = /\bsection:\s*'([^']+)'/g
async function assertFederatedSectionsInSync(repoRoot: string): Promise<void> {
const sourcesDir = join(repoRoot, FEDERATED_CONTENT_SOURCES_DIR)
const sourceFiles = (await readdir(sourcesDir)).filter((file) => file.endsWith('.ts'))
const actualSections = new Set<string>()
for (const file of sourceFiles) {
const source = await readFile(join(sourcesDir, file), 'utf8')
const matches = [...source.matchAll(SOURCE_SECTION_RE)].map((match) => match[1])
const distinctMatches = new Set(matches)
if (distinctMatches.size > 1) {
throw new Error(
`${FEDERATED_CONTENT_SOURCES_DIR}/${file} declares multiple distinct 'section:' ` +
`values (${[...distinctMatches].join(', ')}); expected exactly one per source file.`
)
}
if (distinctMatches.size === 1) actualSections.add(matches[0])
}
const expectedSections = new Set<string>(FEDERATED_SECTIONS)
const missing = [...actualSections].filter((section) => !expectedSections.has(section))
const stale = [...expectedSections].filter((section) => !actualSections.has(section))
if (missing.length > 0 || stale.length > 0) {
const details = [
missing.length > 0 ? `missing from FEDERATED_SECTIONS: ${missing.join(', ')}` : null,
stale.length > 0 ? `no longer a federated-content source: ${stale.join(', ')}` : null,
]
.filter(Boolean)
.join('; ')
throw new Error(
`FEDERATED_SECTIONS in e2e/docs/utils/resolve-docs-scope.ts is out of sync with ` +
`${FEDERATED_CONTENT_SOURCES_DIR}/*.ts (${details}). Update FEDERATED_SECTIONS to match.`
)
}
}
export type ResolveDocsScopeOptions = {
changedFiles: string[]
repoRoot: string
}
export type ResolveDocsScopeResult = {
pages: string[]
skip: boolean
}
function isFederatedGuideSlug(slug: string): boolean {
return FEDERATED_SECTIONS.some((section) => slug === section || slug.startsWith(`${section}/`))
}
function isHiddenMdx(filePath: string): boolean {
return basename(filePath).startsWith('_')
}
export function changedFileToPagePath(filePath: string): string | null {
const normalized = normalizeRepoPath(filePath)
if (normalized.startsWith(GUIDES_PREFIX) && normalized.endsWith('.mdx')) {
if (isHiddenMdx(normalized)) return null
const slug = normalized.slice(GUIDES_PREFIX.length, -'.mdx'.length)
if (!slug || isFederatedGuideSlug(slug)) return null
return `${DOCS_GUIDES_URL_PREFIX}${slug}`
}
return null
}
function partialRelPathFromChangedFile(filePath: string): string | null {
const normalized = normalizeRepoPath(filePath)
if (!normalized.startsWith(PARTIALS_PREFIX) || !normalized.endsWith('.mdx')) {
return null
}
if (normalized.includes('/_fixtures/')) return null
const rel = normalized.slice(PARTIALS_PREFIX.length)
if (!rel || basename(rel).startsWith('_')) return null
return rel
}
function normalizePartialRef(pathAttr: string): string | null {
if (!pathAttr || pathAttr.startsWith('/') || pathAttr.startsWith('http')) {
return null
}
if (!pathAttr.endsWith('.md') && !pathAttr.endsWith('.mdx')) {
return null
}
return normalizeRepoPath(pathAttr).replace(/^\.\//, '')
}
function extractPartialRefs(source: string): string[] {
const refs: string[] = []
PARTIAL_PATH_RE.lastIndex = 0
let match: RegExpExecArray | null
while ((match = PARTIAL_PATH_RE.exec(source)) !== null) {
const normalized = normalizePartialRef(match[1])
if (normalized) refs.push(normalized)
}
return refs
}
async function walkMdxFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true })
const files: string[] = []
for (const entry of entries) {
const fullPath = join(dir, entry.name)
if (entry.isDirectory()) {
if (entry.name.startsWith('_')) continue
files.push(...(await walkMdxFiles(fullPath)))
continue
}
if (!entry.isFile()) continue
if (!entry.name.endsWith('.mdx')) continue
if (entry.name.startsWith('_')) continue
files.push(fullPath)
}
return files
}
type PartialIndex = {
includedByPartials: Map<string, Set<string>>
pagePartials: Map<string, Set<string>>
}
async function buildPartialIndex(repoRoot: string): Promise<PartialIndex> {
const includedByPartials = new Map<string, Set<string>>()
const pagePartials = new Map<string, Set<string>>()
const partialsDir = join(repoRoot, 'apps/docs/content/_partials')
const guidesDir = join(repoRoot, 'apps/docs/content/guides')
const [partialFiles, guideFiles] = await Promise.all([
walkMdxFiles(partialsDir).catch(() => [] as string[]),
walkMdxFiles(guidesDir).catch(() => [] as string[]),
])
for (const file of partialFiles) {
const rel = normalizeRepoPath(relative(partialsDir, file))
const source = await readFile(file, 'utf8')
for (const ref of extractPartialRefs(source)) {
let parents = includedByPartials.get(ref)
if (!parents) {
parents = new Set()
includedByPartials.set(ref, parents)
}
parents.add(rel)
}
}
for (const file of guideFiles) {
const relFromGuides = normalizeRepoPath(relative(guidesDir, file)).replace(/\.mdx$/, '')
if (isFederatedGuideSlug(relFromGuides)) continue
const pagePath = `${DOCS_GUIDES_URL_PREFIX}${relFromGuides}`
const source = await readFile(file, 'utf8')
const refs = extractPartialRefs(source)
if (refs.length > 0) pagePartials.set(pagePath, new Set(refs))
}
return { includedByPartials, pagePartials }
}
function expandPartialClosure(
seed: string,
includedByPartials: Map<string, Set<string>>
): Set<string> {
const result = new Set<string>([seed])
const queue = [seed]
while (queue.length > 0) {
const current = queue.pop()!
const parents = includedByPartials.get(current)
if (!parents) continue
for (const parent of parents) {
if (result.has(parent)) continue
result.add(parent)
queue.push(parent)
}
}
return result
}
function pagesUsingPartials(
targetPartials: Set<string>,
pagePartials: Map<string, Set<string>>
): string[] {
const pages: string[] = []
for (const [page, refs] of pagePartials) {
for (const ref of refs) {
if (targetPartials.has(ref)) {
pages.push(page)
break
}
}
}
return pages
}
export async function resolveDocsScope(
options: ResolveDocsScopeOptions
): Promise<ResolveDocsScopeResult> {
await assertFederatedSectionsInSync(options.repoRoot)
const pages = new Set<string>()
const requiredPages = new Set<string>()
const changedPartials: string[] = []
for (const file of options.changedFiles) {
if (normalizeRepoPath(file) === GUIDE_LIST_COMPONENT) {
for (const page of GUIDE_LIST_COMPONENT_PAGES) requiredPages.add(page)
continue
}
const page = changedFileToPagePath(file)
if (page) {
pages.add(page)
continue
}
const partial = partialRelPathFromChangedFile(file)
if (partial) changedPartials.push(partial)
}
if (changedPartials.length > 0) {
const index = await buildPartialIndex(options.repoRoot)
const targets = new Set<string>()
for (const partial of changedPartials) {
for (const expanded of expandPartialClosure(partial, index.includedByPartials)) {
targets.add(expanded)
}
}
for (const page of pagesUsingPartials(targets, index.pagePartials)) {
pages.add(page)
}
}
const untestablePages = await loadUntestablePages(options.repoRoot)
const sorted = [...new Set([...requiredPages, ...pages])]
.filter((page) => !untestablePages.has(page))
.sort()
return {
pages: sorted,
skip: sorted.length === 0,
}
}
export async function resolveAllDocsPages(repoRoot: string): Promise<string[]> {
await assertFederatedSectionsInSync(repoRoot)
const guidesDir = join(repoRoot, 'apps/docs/content/guides')
const guideFiles = await walkMdxFiles(guidesDir).catch(() => [] as string[])
const untestablePages = await loadUntestablePages(repoRoot)
const pages = new Set<string>()
for (const file of guideFiles) {
const relFromGuides = normalizeRepoPath(relative(guidesDir, file)).replace(/\.mdx$/, '')
const page = `${DOCS_GUIDES_URL_PREFIX}${relFromGuides}`
if (isFederatedGuideSlug(relFromGuides) || untestablePages.has(page)) continue
pages.add(page)
}
return [...pages].sort()
}