Files
supabase/e2e/docs/utils/resolve-docs-scope.ts
Alexis Aguilar b66682ee07 ci(docs): scan only the guides production serves in the daily accessibility scan (#54499)
## Problem

The daily Docs Accessibility Scan builds its page list from
`apps/docs/content/guides` on `master`, then loads each page from
production. When production runs behind `master`, every guide merged
since the last production deploy returns 404 and fails the scan, even
though the guide is fine.

On 2026-12-02, the scan failed on 8 guides this way. A deployment freeze
had moved docs production to a temporary `release` branch, so guides
merged to `master` that day weren't deployed. The same thing can happen
outside a freeze, when a guide merges minutes before the scan runs.

## Solution

The scan now tests only the guides production serves. It keeps the
guides from the repo list that also appear in the production sitemap,
`https://supabase.com/docs/sitemap.xml`.

- **Why the sitemap.** The docs build generates `sitemap.xml` from
`content/guides` on every production deploy, leaving out guides the nav
turns off. It isn't cached between builds, so it always lists what
production serves. It needs no new credentials. Today it lists every one
of the 609 guides the scan tests, plus the federated sections the scan
already skips.
- **How it's wired.** `run-e2e-docs.ts --all` filters the list when
`DOCS_E2E_DEPLOYED_ONLY` is set, using the `/docs/sitemap.xml` of the
site in `PLAYWRIGHT_BASE_URL`, so the page list and the scanned site
can't come from different sites. `docs-a11y-scan.yml` sets it. Runs
without the variable behave as before. The filter lives in
`e2e/docs/utils/production-pages.ts`, with unit tests.
- **Skipped guides are listed.** Each guide missing from the sitemap
prints "Skipping `<page>`: not in `<sitemap URL>`." in the run log, and
shows as a warning on the run page even when the scan passes. It's
scanned on the first run after its deploy.
- **Skipped guides keep their earlier results in the alert.** The runner
passes the skipped guides to the a11y failures reporter from #54444,
which lists each one as unchecked. A guide with an open failure that
drops out of the sitemap keeps that failure open, instead of posting as
fixed and then as new when it returns.
- **A real 404 still fails.** A live guide that starts returning 404 is
still in the sitemap, so it's still scanned and still fails.
- **A broken sitemap fails the run.** The run fails when the sitemap
can't be read, lists no guides, or is missing more than a tenth of the
repo's guides. A partial sitemap can't silently shrink the scan.
- **Wrapped tags.** The sitemap's formatter wraps long `<loc>` tags
across lines, as `<loc\n >url</loc\n>`. The parser handles that. A
line-based parse misses about 10 guides.

The workflow header comment and `e2e/docs/README.md` say where the page
list comes from.

### Behavior changes to review

1. **A guide whose nav entry is turned off is skipped, not failed.** The
docs build leaves it out of the sitemap, and production returns 404 for
it. That matches production. It also means turning off a live guide's
nav entry by mistake doesn't fail the scan. The guide shows as a warning
on the run page instead.
2. **Interaction with the failure alert from #54444.** The alert reports
a guide that returns 404 as an `http-404` failure. With this change,
only a guide production should serve can produce that failure. A skipped
guide keeps whatever failures it already had open, so a guide whose nav
entry is turned off stays in the list until it's back or deleted.

## Limitations

- A guide skipped for about two weeks or more loses its commit
attribution if it fails when it returns. The alert reads only the last
500 deployed commits, so it can't tell which commit production was
running when the guide was last checked, and says so.
- `getting-started/features` is in the sitemap even though a static
redirect sends it elsewhere. The scan already skips redirected guides,
so it doesn't affect the scan.

## Review instructions

1. Run `pnpm -C e2e/docs test` and confirm all 63 tests pass.
2. List the scan's tests against the live sitemap:
   ```bash
cd e2e/docs && CI=1 PLAYWRIGHT_BASE_URL=https://supabase.com
DOCS_E2E_DEPLOYED_ONLY=1 \
pnpm run e2e:docs:all --grep @a11y --list | grep -E
'Resolved|Skipping|Total'
   ```
Expect every guide resolved and nothing skipped while production matches
`master`.
3. Run step 2 with `PLAYWRIGHT_BASE_URL=https://example.com`, a site
with no docs sitemap. Expect the run to fail with the sitemap URL and
its status.
4. Add a temporary guide that isn't on production, such as
`apps/docs/content/guides/zz-temp-probe.mdx`, and run step 2 with
`DOCS_A11Y_FAILURES_FILE=/tmp/a11y.json`. Expect "Skipping
/docs/guides/zz-temp-probe", and both `/docs/guides/zz-temp-probe` and
`/docs/guides/zz-temp-probe: http` under `unchecked` in
`/tmp/a11y.json`. Delete the guide afterward.

Verified locally:

- Unit tests, typecheck, oxfmt, and actionlint on the changed workflow.
The unit tests also pass in a copy of the repo with no installed
packages, as CI runs them. The only actionlint warning is the existing
blacksmith runner label.
- Mutation probes on the wrapped-tag parsing, the trailing-slash trim,
the guides-only filter, the missing-share guard, and each of the three
ways a sitemap fails the run: an error status, no guides, and a site
that can't be reached. Unit tests cover all three with a local
`node:http` server.
- A copy of the production sitemap with the 8 guides from the 2026-12-02
run removed. The run skipped exactly those 8 and resolved the rest.
- A temporary guide that's in the sitemap but returns 404 on production.
The scan failed it with "Expected a successful response … got 404".
- Review step 4, after rebasing onto #54444. The skipped guide reached
the reporter as unchecked under its page and status keys. A mutation
probe that drops the skipped guides from the reporter fails the new
test.
- A sitemap with no guides, and one that can't be reached. Both failed
the run before Playwright started.

Resolves
[DOCS-1839](https://linear.app/supabase/issue/DOCS-1839/scan-only-the-pages-production-serves-in-the-daily-docs-accessibility)

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
2026-12-03 17:03:53 -07:00

340 lines
11 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/'
export 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
}
export function pagePathToGuideFile(pagePath: string): string | null {
if (!pagePath.startsWith(DOCS_GUIDES_URL_PREFIX)) return null
return `${GUIDES_PREFIX}${pagePath.slice(DOCS_GUIDES_URL_PREFIX.length)}.mdx`
}
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,
}
}
// The guide's MDX file and every partial it includes, directly or through other partials
export async function pageSourceFiles(repoRoot: string, pagePath: string): Promise<string[]> {
const mdx = pagePathToGuideFile(pagePath)
if (!mdx) return []
const files = new Set([mdx])
const queue = [mdx]
while (queue.length > 0) {
const file = queue.pop()!
const source = await readFile(join(repoRoot, file), 'utf8').catch(() => null)
if (source === null) continue
for (const ref of extractPartialRefs(source)) {
const partial = `${PARTIALS_PREFIX}${ref}`
if (files.has(partial)) continue
files.add(partial)
queue.push(partial)
}
}
return [...files]
}
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()
}