mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Problem Agents have no single index of the docs markdown exports, unlike the KB's `sitemap.md`. www's `/llms.txt` and `/llms-full.txt` also read docs files from disk, which forces www's build to wait on the docs build. ## Solution **docs** - Add `build:markdown-sitemap`, which writes `public/markdown/sitemap.md`. It scans `public/markdown/**/*.md` and lists each file as `[title](url.md)`. Guide URLs are `/docs/guides/<page>.md` and the rest are `/docs/markdown/<page>.md`, built with the existing `internal-links` helpers. - Add `build:markdown-full`, which writes `public/markdown/full.md`. It concatenates the same files. - Both scripts share one file-list helper (`internals/markdown-files.ts`), so they always cover the same files and exclude `sitemap.md` and `full.md`. - Both tasks depend on `build:markdown` and are wired into `build` in turbo. - Search v2 ingestion and the `docs.tar.gz` archive now ignore both files. **www** - `/llms.txt` and `/llms-full.txt` now fetch `sitemap.md` and `full.md` from `NEXT_PUBLIC_DOCS_URL`, replacing only their docs parts. Pricing, product overviews, agent resources, the KB link and the customer stories link are unchanged. If docs is unreachable, the docs section is left out instead of returning a 404. - Remove the on-disk docs reads, the `outputFileTracingIncludes` entries, and the `docs#build:guides-markdown` dependency and docs input globs from www's turbo config. These routes were the only link between www and the docs build. `turbo-build.test.ts` is updated to match. - Add a `/docs.md` → `/docs/markdown/sitemap.md` redirect, next to the existing `/kb.md` one. Routes without a markdown export are not patched, they are simply absent from the sitemap. ## Review instructions From the Docs preview link: 1. Open /docs/markdown/sitemap.md it should show a file with all links to the docs pages available in markdown 1. Open /docs/markdown/full.md it should show a file with all the content from all the pages Sadly, only after deployed... 1. www project should return the content of both files when: a. supabase.com/llms.txt is queried should return docs sitemap.md content b. supabase.com/llms-full.txt is queried should return docs full.md content 1. supabase.com/docs.md should return sitemap.md file ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
329 lines
12 KiB
TypeScript
329 lines
12 KiB
TypeScript
import fs from 'node:fs/promises'
|
|
import path from 'node:path'
|
|
import { LLMS_TXT_URL } from 'common/markdown-affordance'
|
|
import { configFormatsRemark } from '~/features/directives/ConfigFormats'
|
|
import { parsePartialVariables, substitutePartialVars } from '~/lib/partials.utils'
|
|
import matter from 'gray-matter'
|
|
import yaml from 'js-yaml'
|
|
import type { Content, Parent, Root } from 'mdast'
|
|
import { fromMarkdown } from 'mdast-util-from-markdown'
|
|
import { gfmFromMarkdown, gfmToMarkdown } from 'mdast-util-gfm'
|
|
import { mdxFromMarkdown, mdxToMarkdown } from 'mdast-util-mdx'
|
|
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx'
|
|
import { toMarkdown } from 'mdast-util-to-markdown'
|
|
import { gfm } from 'micromark-extension-gfm'
|
|
import { mdxjs } from 'micromark-extension-mdxjs'
|
|
import { parse as parseToml } from 'smol-toml'
|
|
import { mcpConfigPanelMarkdown as McpConfigPanel } from 'ui-patterns/McpUrlBuilder/McpConfigPanel.md'
|
|
|
|
import {
|
|
CONFIG_REFERENCE_SLUG,
|
|
CONFIG_REFERENCE_SPEC,
|
|
renderConfigReferenceMarkdown,
|
|
type ConfigSpec,
|
|
} from './config-reference-markdown'
|
|
import { stripHeadingCustomIds } from './helpers'
|
|
import { addBaseUrlPrefix, getInternalLinkBaseUrl, withDocsBasePath } from './internal-links'
|
|
import { Admonition } from './markdown-schema/Admonition'
|
|
import { AgentSetup } from './markdown-schema/AgentSetup'
|
|
import { AgentWatchSchedule } from './markdown-schema/AgentWatchSchedule'
|
|
import { AiPrompt } from './markdown-schema/AiPrompt'
|
|
import { AiSkillsIndex } from './markdown-schema/AiSkillsIndex'
|
|
import { AuthProviders } from './markdown-schema/AuthProviders'
|
|
import { ComputeDiskLimitsTable } from './markdown-schema/ComputeDiskLimitsTable'
|
|
import { ContentListings } from './markdown-schema/ContentListings'
|
|
import { CustomContent } from './markdown-schema/CustomContent'
|
|
import { DatabaseAdvisorsIndex } from './markdown-schema/DatabaseAdvisorsIndex'
|
|
import { ErrorCodes } from './markdown-schema/ErrorCodes'
|
|
import { GettingStartedStepper } from './markdown-schema/GettingStartedStepper'
|
|
import { IconCheck, IconX } from './markdown-schema/Icons'
|
|
import { Image } from './markdown-schema/Image'
|
|
import { Link } from './markdown-schema/Link'
|
|
import { McpCiConfigBlock } from './markdown-schema/McpCiConfigBlock'
|
|
import { MetricsStackCards } from './markdown-schema/MetricsStackCards'
|
|
import { NavData } from './markdown-schema/NavData'
|
|
import { Panel } from './markdown-schema/Panel'
|
|
import { Price } from './markdown-schema/Price'
|
|
import { PromptPanel } from './markdown-schema/PromptPanel'
|
|
import { RealtimeLimitsEstimator } from './markdown-schema/RealtimeLimitsEstimator'
|
|
import { RegionsList, SmartRegionsList } from './markdown-schema/RegionsList'
|
|
import { SharedData } from './markdown-schema/SharedData'
|
|
import { StepHike } from './markdown-schema/StepHike'
|
|
import { TabPanel } from './markdown-schema/TabPanel'
|
|
import { TerraformProviderSchema } from './markdown-schema/TerraformProviderSchema'
|
|
import { WrapperDashboardIntegration } from './markdown-schema/WrapperDashboardIntegration'
|
|
import { collectMarkdownSources, type FrontmatterFormat } from './markdown-sources'
|
|
|
|
const PARTIALS_DIR = path.join(process.cwd(), 'content', '_partials')
|
|
// The set of guide slugs that have a generated markdown (.md) variant. middleware.ts
|
|
// imports this to decide whether a bot request for /guides/<slug> can be served
|
|
// markdown. It lives under the gitignored public/markdown/ output dir and is
|
|
// regenerated by build:guides-markdown, which turbo runs ahead of build/typecheck/lint.
|
|
const MANIFEST_PATH = path.join(process.cwd(), 'public', 'markdown', 'manifest.json')
|
|
|
|
// The agent feedback page is the destination agents are sent to, so it carries no note.
|
|
const SLUGS_WITHOUT_AGENT_NOTE = new Set(['ai-tools/agent-feedback'])
|
|
|
|
const AGENT_NOTE = `> Note for AI agents: For other pages, see [llms.txt](${LLMS_TXT_URL}).`
|
|
|
|
type JsxNode = MdxJsxFlowElement | MdxJsxTextElement
|
|
type Props = Record<string, unknown>
|
|
|
|
/**
|
|
* A handler converts a single MDX component into a markdown string. It receives
|
|
* the component's props, the already-serialized markdown of its children, and
|
|
* the raw AST node (escape hatch for handlers that need to inspect structure).
|
|
*
|
|
* Any component not in the schema is treated as `({ children }) => children`,
|
|
* i.e. the wrapper is dropped and its children are kept as-is.
|
|
*/
|
|
type ComponentHandler = (ctx: { props: Props; children: string; node: JsxNode }) => string
|
|
type ComponentSchema = Record<string, ComponentHandler>
|
|
|
|
const PARSE_OPTIONS = {
|
|
extensions: [mdxjs(), gfm()],
|
|
mdastExtensions: [mdxFromMarkdown(), gfmFromMarkdown()],
|
|
}
|
|
const SERIALIZE_OPTIONS = {
|
|
extensions: [mdxToMarkdown(), gfmToMarkdown()],
|
|
bullet: '-' as const,
|
|
listItemIndent: 'one' as const,
|
|
}
|
|
|
|
const parseMdx = (source: string): Root => fromMarkdown(source, PARSE_OPTIONS)
|
|
const serializeMdx = (tree: Parent): string => toMarkdown(tree as Root, SERIALIZE_OPTIONS)
|
|
|
|
const defaultHandler: ComponentHandler = ({ children }) => children
|
|
|
|
const isJsx = (n: Content): n is JsxNode =>
|
|
n.type === 'mdxJsxFlowElement' || n.type === 'mdxJsxTextElement'
|
|
|
|
function propsFrom(node: JsxNode): Props {
|
|
const props: Props = {}
|
|
for (const attr of node.attributes) {
|
|
if (attr.type !== 'mdxJsxAttribute') continue
|
|
if (attr.value == null) props[attr.name] = true
|
|
else if (typeof attr.value === 'string') props[attr.name] = attr.value
|
|
else props[attr.name] = attr.value.value
|
|
}
|
|
return props
|
|
}
|
|
|
|
function resolvePartialPath(partialPath: string): string {
|
|
if (!partialPath.endsWith('.md') && !partialPath.endsWith('.mdx')) {
|
|
throw new Error('Invalid $Partial path: path must end with .mdx or .md')
|
|
}
|
|
const resolved = path.join(PARTIALS_DIR, partialPath)
|
|
if (!resolved.startsWith(PARTIALS_DIR)) {
|
|
throw new Error(`Invalid $Partial path: path must be inside ${PARTIALS_DIR}`)
|
|
}
|
|
return resolved
|
|
}
|
|
|
|
/**
|
|
* Replaces every `<$Partial path="..." />` in the tree with the parsed AST of
|
|
* the referenced file. Recurses so partials may include other partials.
|
|
*/
|
|
async function inlinePartials(parent: Parent): Promise<void> {
|
|
const next: Content[] = []
|
|
for (const child of parent.children as Content[]) {
|
|
if (isJsx(child) && child.name === '$Partial') {
|
|
const props = propsFrom(child)
|
|
const partialPath = String(props.path ?? '')
|
|
const variables = parsePartialVariables(props.variables)
|
|
const resolvedPath = resolvePartialPath(partialPath)
|
|
try {
|
|
const raw = await fs.readFile(resolvedPath, 'utf8')
|
|
const content = substitutePartialVars(matter(raw).content, variables)
|
|
const subtree = parseMdx(content)
|
|
await inlinePartials(subtree)
|
|
next.push(...(subtree.children as Content[]))
|
|
} catch {
|
|
// missing or broken partials are silently dropped
|
|
}
|
|
continue
|
|
}
|
|
if ('children' in child) await inlinePartials(child as Parent)
|
|
next.push(child)
|
|
}
|
|
parent.children = next as Parent['children']
|
|
}
|
|
|
|
/**
|
|
* Walks the tree bottom-up. For each JSX element, runs its schema handler (or
|
|
* the default) and replaces the node with an `html` node holding the result.
|
|
* The `html` type passes through `mdast-util-to-markdown` verbatim, so whatever
|
|
* markdown the handler returns lands in the final output unchanged.
|
|
*/
|
|
function applySchema(parent: Parent, schema: ComponentSchema): void {
|
|
for (const child of parent.children as Content[]) {
|
|
if ('children' in child) applySchema(child as Parent, schema)
|
|
}
|
|
const next: Content[] = []
|
|
for (const child of parent.children as Content[]) {
|
|
if (
|
|
child.type === 'mdxFlowExpression' ||
|
|
child.type === 'mdxTextExpression' ||
|
|
child.type === 'mdxjsEsm'
|
|
) {
|
|
continue
|
|
}
|
|
if (isJsx(child)) {
|
|
const handler = schema[child.name ?? ''] ?? defaultHandler
|
|
const children = serializeMdx({
|
|
type: 'root',
|
|
children: child.children as Root['children'],
|
|
}).trim()
|
|
const value = handler({ props: propsFrom(child), children, node: child })
|
|
next.push({ type: 'html', value } as Content)
|
|
continue
|
|
}
|
|
next.push(child)
|
|
}
|
|
parent.children = next as Parent['children']
|
|
}
|
|
|
|
/**
|
|
* Per-component overrides. Each handler receives `{ props, children, node }`
|
|
* and returns the markdown string that should replace the JSX element. Any
|
|
* component not listed is unwrapped (children are kept, wrapper is dropped).
|
|
*/
|
|
const SCHEMA: ComponentSchema = {
|
|
Admonition,
|
|
AgentSetup,
|
|
AgentWatchSchedule,
|
|
AiPrompt,
|
|
AiSkillsIndex,
|
|
GettingStartedStepper,
|
|
IconCheck,
|
|
IconX,
|
|
Image,
|
|
AuthProviders,
|
|
ComputeDiskLimitsTable,
|
|
CustomContent,
|
|
DatabaseAdvisorsIndex,
|
|
ErrorCodes,
|
|
Link,
|
|
McpCiConfigBlock,
|
|
McpConfigPanel,
|
|
Price,
|
|
...PromptPanel,
|
|
GlassPanel: Panel,
|
|
RealtimeLimitsEstimator,
|
|
RegionsList,
|
|
SmartRegionsList,
|
|
...StepHike,
|
|
TabPanel,
|
|
MetricsStackCards,
|
|
ContentListings,
|
|
NavData,
|
|
SharedData,
|
|
TerraformProviderSchema,
|
|
WrapperDashboardIntegration,
|
|
}
|
|
|
|
function parseFrontmatter(raw: string, frontmatter: FrontmatterFormat) {
|
|
if (frontmatter === 'toml') {
|
|
return matter(raw, { language: 'toml', engines: { toml: parseToml } })
|
|
}
|
|
return matter(raw)
|
|
}
|
|
|
|
async function transformBody(
|
|
content: string,
|
|
data: Record<string, unknown>,
|
|
slug: string
|
|
): Promise<string> {
|
|
const tree = parseMdx(content)
|
|
await inlinePartials(tree)
|
|
configFormatsRemark()(tree as Root)
|
|
addBaseUrlPrefix(tree)
|
|
stripHeadingCustomIds(tree)
|
|
applySchema(tree, SCHEMA)
|
|
const body = serializeMdx(tree)
|
|
|
|
const headerParts: string[] = []
|
|
if (data.title) headerParts.push(`# ${String(data.title)}`)
|
|
if (data.subtitle) headerParts.push(String(data.subtitle))
|
|
if (data.description && String(data.description) !== String(data.subtitle))
|
|
headerParts.push(String(data.description))
|
|
|
|
const header = headerParts.join('\n\n')
|
|
|
|
const output = header ? `${header}\n\n${body}` : body
|
|
|
|
return SLUGS_WITHOUT_AGENT_NOTE.has(slug) ? output : `${AGENT_NOTE}\n\n${output}`
|
|
}
|
|
|
|
async function parseSingleSource(
|
|
sourceFile: string,
|
|
slug: string,
|
|
frontmatter: FrontmatterFormat
|
|
): Promise<string> {
|
|
const raw = await fs.readFile(sourceFile, 'utf8')
|
|
const { content, data } = parseFrontmatter(raw, frontmatter)
|
|
return transformBody(content, data, slug)
|
|
}
|
|
|
|
async function generateConfigReference(): Promise<string> {
|
|
const spec = yaml.load(await fs.readFile(CONFIG_REFERENCE_SPEC, 'utf8')) as ConfigSpec
|
|
const tree = fromMarkdown(renderConfigReferenceMarkdown(spec), {
|
|
extensions: [gfm()],
|
|
mdastExtensions: [gfmFromMarkdown()],
|
|
})
|
|
addBaseUrlPrefix(tree)
|
|
const outPath = `public/markdown/guides/${CONFIG_REFERENCE_SLUG}.md`
|
|
await fs.mkdir(path.dirname(outPath), { recursive: true })
|
|
await fs.writeFile(
|
|
outPath,
|
|
`${AGENT_NOTE}\n\n${toMarkdown(tree, {
|
|
extensions: [gfmToMarkdown()],
|
|
bullet: '-',
|
|
listItemIndent: 'one',
|
|
})}`
|
|
)
|
|
return CONFIG_REFERENCE_SLUG
|
|
}
|
|
|
|
async function renderManifest(slugs: Array<string>): Promise<void> {
|
|
// Sorted so the output is deterministic: turbo hashes this tracked file as a task input.
|
|
const sorted = Array.from(new Set(slugs)).sort()
|
|
const content = `${JSON.stringify(sorted, null, 2)}\n`
|
|
|
|
await fs.mkdir(path.dirname(MANIFEST_PATH), { recursive: true })
|
|
await fs.writeFile(MANIFEST_PATH, content)
|
|
}
|
|
|
|
async function generate() {
|
|
const sources = await collectMarkdownSources()
|
|
|
|
await Promise.all(
|
|
sources.map(async ({ sourceFile, slug, outPath, frontmatter }) => {
|
|
let output: string
|
|
try {
|
|
output = await parseSingleSource(sourceFile, slug, frontmatter)
|
|
} catch (err) {
|
|
throw new Error(
|
|
`Failed to process ${sourceFile}: ${err instanceof Error ? err.message : err}`,
|
|
{ cause: err }
|
|
)
|
|
}
|
|
|
|
await fs.mkdir(path.dirname(outPath), { recursive: true })
|
|
await fs.writeFile(outPath, output)
|
|
})
|
|
)
|
|
|
|
const configReferenceSlug = await generateConfigReference()
|
|
await renderManifest([...sources.map((s) => s.slug), configReferenceSlug])
|
|
|
|
console.log(
|
|
`Generated ${sources.length + 1} markdown files under public/markdown/guides/ and updated public/markdown/manifest.json`
|
|
)
|
|
}
|
|
|
|
generate().catch((error) => {
|
|
console.error(error)
|
|
process.exit(1)
|
|
})
|