mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 23:49:03 +00:00
## Problem The Knowledge Base HTML pages show an "Updated" date, but their `.md` exports had no date. Readers and tools that use the markdown versions couldn't tell how recent a guide, FAQ, or troubleshooting article was. ## Solution Every Knowledge Base `.md` export now has a `Last updated: YYYY-MM-DD` line right under its title and description. It uses the date the HTML page shows. Guides and FAQs take it from the frontmatter `lastEdited`. Troubleshooting articles take it from the `troubleshooting_entries.date_updated` lookup the troubleshooting page already does, and fall back to frontmatter `lastEdited`. A page with no date gets no line. A failed database lookup logs a warning, and the export still builds. The export and the troubleshooting lookup share one date parser in `format-date.ts`. ## How to verify 1. Open a guide export on the preview, for example `/kb/guides/best-astro-authentication-providers.md`. Below the description it reads `Last updated: ` with the date from the HTML page's "Updated" label. 2. Open an FAQ `.md` export from `/kb/sitemap.md` and check that it has the same line. 3. Open a troubleshooting `.md` export from `/kb/sitemap.md`. If the HTML page shows an "Updated" date, the export shows the same day. 4. Run `pnpm --filter kb exec vitest run scripts/generate-markdown.test.ts src/lib/format-date.test.ts`. It covers the date line and the date parsing. ## Checks Ran `vitest run scripts/generate-markdown.test.ts src/lib/format-date.test.ts` in apps/kb (29 passed), `pnpm turbo run lint --filter=kb`, `tsc --noEmit -p apps/kb` (no errors in the changed files), and `oxfmt --check` on the changed files. Ran `tsx scripts/generate-markdown.ts` locally: every guide and FAQ export got the line, and the sitemap links are unchanged. A sample troubleshooting file with no database credentials fell back to its frontmatter date. The database lookup for troubleshooting wasn't run, because the sandbox has no credentials. ## Checklist - [x] I have read the [Contributing Guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] I have added tests for the change - [ ] I have checked that the change works in the preview deployment ## Feedback for Tedd To ask Tedd for a change to this PR, reply in Tedd's session on [DOCS-1838](https://linear.app/supabase/issue/DOCS-1838/add-last-modified-dates-to-md-versions-of-pages). Tedd doesn't read comments on this PR. --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
306 lines
11 KiB
TypeScript
306 lines
11 KiB
TypeScript
// Build step (the `generate:markdown` turbo task): exports every src/content/**/*.{md,mdx} file as a plain
|
|
// .md file under public/markdown/, for agents/tools that want the raw
|
|
// content instead of the rendered page (same idea as apps/docs' guides
|
|
// markdown export, recreated here at a much smaller scale — see
|
|
// vercel.json for the redirect that serves it at `<page>.md`).
|
|
import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
|
|
import path from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import remarkGfm from 'remark-gfm'
|
|
import remarkParse from 'remark-parse'
|
|
import remarkStringify from 'remark-stringify'
|
|
import { unified } from 'unified'
|
|
import YAML from 'yaml'
|
|
|
|
import { BASE_PATH } from '../src/lib/constants.ts'
|
|
import { parseDate, toIsoDay } from '../src/lib/format-date.ts'
|
|
import { isInTopic, TOPICS, topicToSlug, type Topic } from '../src/lib/topics.ts'
|
|
import {
|
|
getEntryMetadataBySlug,
|
|
type TroubleshootingEntryMetadata,
|
|
} from '../src/lib/troubleshooting-db.ts'
|
|
import { addBaseUrlPrefix, stripHeadingCustomIds } from './helpers.ts'
|
|
|
|
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url))
|
|
const CONTENT_DIR = path.join(SCRIPT_DIR, '..', 'src', 'content')
|
|
const COMMUNITY_GUIDES_PATH = path.join(SCRIPT_DIR, '..', 'src', 'data', 'community-guides.json')
|
|
const OUTPUT_DIR = path.join(SCRIPT_DIR, '..', 'public', 'markdown')
|
|
|
|
// Used to turn root-relative links into full URLs so the exported file still
|
|
// makes sense read on its own.
|
|
const SITE_ORIGIN = 'https://supabase.com'
|
|
|
|
const SITE_TITLE = 'Supabase Knowledge Base'
|
|
const SITE_DESCRIPTION =
|
|
'In-depth guides, tutorials, troubleshooting, and explainers for best practices for Supabase'
|
|
|
|
interface Frontmatter {
|
|
title?: string
|
|
description?: string
|
|
topics?: unknown
|
|
[key: string]: unknown
|
|
}
|
|
|
|
interface Entry {
|
|
title: string
|
|
url: string
|
|
}
|
|
|
|
// Single processor reused for every file: parses GFM markdown to an mdast
|
|
// tree and serializes it back, same extensions on both ends so nothing
|
|
// (tables, strikethrough, alert blockquotes) gets mangled in the round trip.
|
|
// `emphasis`/`rule` match the markers content already uses, so the round trip
|
|
// doesn't normalize authors' `_italic_`/`---` into the serializer's own `*italic*`/`***`.
|
|
const processor = unified()
|
|
.use(remarkParse)
|
|
.use(remarkGfm)
|
|
.use(remarkStringify, { bullet: '-', listItemIndent: 'one', emphasis: '_', rule: '-' })
|
|
|
|
export type MarkdownTree = ReturnType<typeof processor.parse>
|
|
|
|
/**
|
|
* Absolute base URL to prepend to root-relative links, mirroring apps/docs'
|
|
* `getInternalLinkBaseUrl()`. Empty in local dev/CI (outside Vercel), which
|
|
* keeps links relative there — resolved instead against whatever host is
|
|
* serving the build.
|
|
*
|
|
* Resolution order:
|
|
* - `VERCEL_ENV=production` → `https://supabase.com`
|
|
* - `VERCEL_ENV=preview` → `https://${VERCEL_URL}`
|
|
* - anything else → ''
|
|
*/
|
|
export function getInternalLinkBaseUrl() {
|
|
const env = process.env.VERCEL_ENV
|
|
if (env === 'production') return SITE_ORIGIN
|
|
if (env === 'preview' && process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`
|
|
return ''
|
|
}
|
|
|
|
/**
|
|
* Splits a `.md`/`.mdx` file's raw text into its YAML frontmatter (parsed
|
|
* to a plain object) and the remaining body. The delimiters are located
|
|
* with plain string ops, and the frontmatter itself is parsed with a real
|
|
* YAML parser — no regex involved in extracting values.
|
|
*
|
|
*/
|
|
export function parseFrontmatter(raw: string): { data: Frontmatter; body: string } {
|
|
if (!raw.startsWith('---\n')) return { data: {}, body: raw }
|
|
|
|
const frontmatterEnd = raw.indexOf('\n---', 4)
|
|
if (frontmatterEnd === -1) return { data: {}, body: raw }
|
|
|
|
const yamlText = raw.slice(4, frontmatterEnd)
|
|
const bodyStart = raw.indexOf('\n', frontmatterEnd + 1)
|
|
const body = bodyStart === -1 ? '' : raw.slice(bodyStart + 1)
|
|
|
|
return { data: YAML.parse(yamlText) ?? {}, body }
|
|
}
|
|
|
|
/**
|
|
* Rewrites root-relative markdown links into full, absolute URLs by parsing
|
|
* the body to an mdast tree, visiting its `link` nodes, and serializing it
|
|
* back — the AST equivalent of apps/docs' `addBaseUrlPrefix()`, so this file
|
|
* still makes sense read outside of the site (no regex over the raw text).
|
|
* Heading custom anchors are stripped in the same pass.
|
|
*/
|
|
export function absolutizeLinks(body: string): string {
|
|
const tree = processor.parse(body)
|
|
|
|
stripHeadingCustomIds(tree)
|
|
addBaseUrlPrefix(tree, getInternalLinkBaseUrl())
|
|
|
|
return String(processor.stringify(tree))
|
|
}
|
|
|
|
/**
|
|
* Renders the export: the title as an h1, then the description, the
|
|
* last-updated date, and the body.
|
|
*/
|
|
export function renderMarkdown(data: Frontmatter, body: string, lastUpdated?: Date): string {
|
|
const heading = data.title ? `# ${data.title}\n\n` : ''
|
|
const lead = data.description ? `${data.description}\n\n` : ''
|
|
const updated = lastUpdated ? `Last updated: ${toIsoDay(lastUpdated)}\n\n` : ''
|
|
return `${heading}${lead}${updated}${absolutizeLinks(body.trim())}`
|
|
}
|
|
|
|
/**
|
|
* Renders a topic index: its name as an h1, its description as the
|
|
* paragraph beneath it, then a bullet list linking to every guide tagged
|
|
* with that topic — same data `src/pages/topics/[topic].astro` renders,
|
|
* as a plain markdown page.
|
|
*/
|
|
export function renderTopicMarkdown(
|
|
topic: { name: string; description: string },
|
|
guides: Entry[]
|
|
): string {
|
|
const list = guides.length
|
|
? guides.map((guide) => `- [${guide.title}](${guide.url})`).join('\n')
|
|
: 'No guides for this topic'
|
|
return `# ${topic.name}\n\n${topic.description}\n\n${list}\n`
|
|
}
|
|
|
|
const renderLinkList = (entries: Entry[]) =>
|
|
entries.length
|
|
? entries.map((entry) => `- [${entry.title}](${entry.url})`).join('\n')
|
|
: 'No entries'
|
|
|
|
/**
|
|
* Renders the root sitemap: the site title as an h1 with its description
|
|
* beneath, then one section per kind of page (topics, guides, FAQs,
|
|
* troubleshooting articles), each a bullet list of links to the `.md` exports.
|
|
*/
|
|
export function renderSitemapMarkdown({
|
|
topics,
|
|
guides,
|
|
faqs,
|
|
troubleshooting,
|
|
}: {
|
|
topics: Entry[]
|
|
guides: Entry[]
|
|
faqs: Entry[]
|
|
troubleshooting: Entry[]
|
|
}): string {
|
|
return (
|
|
[
|
|
`# ${SITE_TITLE}`,
|
|
SITE_DESCRIPTION,
|
|
'## Topics',
|
|
renderLinkList(topics),
|
|
'## Guides',
|
|
renderLinkList(guides),
|
|
'## FAQs',
|
|
renderLinkList(faqs),
|
|
'## Troubleshooting',
|
|
renderLinkList(troubleshooting),
|
|
].join('\n\n') + '\n'
|
|
)
|
|
}
|
|
|
|
// file.mdx -> file.md, file.md -> file.md — no regex, just a suffix swap.
|
|
function toMdExtension(fileName: string): string {
|
|
if (fileName.endsWith('.mdx')) return `${fileName.slice(0, -'.mdx'.length)}.md`
|
|
return fileName
|
|
}
|
|
|
|
function withoutExtension(segments: string[]): string {
|
|
return toMdExtension(segments.join('/')).slice(0, -'.md'.length)
|
|
}
|
|
|
|
function toMdUrl(relativePath: string): string {
|
|
return `${SITE_ORIGIN}${BASE_PATH}/${withoutExtension(relativePath.split(path.sep))}.md`
|
|
}
|
|
|
|
// The first folder under src/content, e.g. guides, faqs or troubleshooting.
|
|
function collectionOf(relativePath: string): string {
|
|
return relativePath.split(path.sep)[0]
|
|
}
|
|
|
|
// Matches the entry id that src/content.config.ts gives the page.
|
|
function troubleshootingSlug(relativePath: string): string {
|
|
return withoutExtension(relativePath.split(path.sep).slice(1))
|
|
}
|
|
|
|
const byTitle = (a: Entry, b: Entry) => a.title.localeCompare(b.title)
|
|
|
|
async function findContentFiles(dir: string): Promise<string[]> {
|
|
const entries = await readdir(dir, { withFileTypes: true })
|
|
const files = await Promise.all(
|
|
entries.map((entry) => {
|
|
const fullPath = path.join(dir, entry.name)
|
|
if (entry.isDirectory()) return findContentFiles(fullPath)
|
|
if (entry.name.endsWith('.md') || entry.name.endsWith('.mdx')) return [fullPath]
|
|
return []
|
|
})
|
|
)
|
|
return files.flat()
|
|
}
|
|
|
|
async function writeFileEnsuringDir(outputPath: string, contents: string) {
|
|
await mkdir(path.dirname(outputPath), { recursive: true })
|
|
await writeFile(outputPath, contents)
|
|
}
|
|
|
|
async function main() {
|
|
const files = await findContentFiles(CONTENT_DIR)
|
|
|
|
// Troubleshooting dates live in the database, as on the troubleshooting page.
|
|
const troubleshootingSlugs = files
|
|
.map((file) => path.relative(CONTENT_DIR, file))
|
|
.filter((relativePath) => collectionOf(relativePath) === 'troubleshooting')
|
|
.map(troubleshootingSlug)
|
|
const troubleshootingMetadata = troubleshootingSlugs.length
|
|
? await getEntryMetadataBySlug(troubleshootingSlugs)
|
|
: new Map<string, TroubleshootingEntryMetadata>()
|
|
|
|
const guidesByTopic = new Map<Topic, Entry[]>(TOPICS.map((topic) => [topic.name, []]))
|
|
const entriesByCollection: Record<'guides' | 'faqs' | 'troubleshooting', Entry[]> = {
|
|
guides: [],
|
|
faqs: [],
|
|
troubleshooting: [],
|
|
}
|
|
|
|
await Promise.all(
|
|
files.map(async (file) => {
|
|
const raw = await readFile(file, 'utf-8')
|
|
const { data, body } = parseFrontmatter(raw)
|
|
const relativePath = path.relative(CONTENT_DIR, file)
|
|
|
|
const collection = collectionOf(relativePath) as keyof typeof entriesByCollection
|
|
|
|
const lastUpdated =
|
|
(collection === 'troubleshooting'
|
|
? troubleshootingMetadata.get(troubleshootingSlug(relativePath))?.dateUpdated
|
|
: undefined) ?? parseDate(data.lastEdited)
|
|
const markdown = renderMarkdown(data, body, lastUpdated)
|
|
const outputPath = path.join(OUTPUT_DIR, toMdExtension(relativePath))
|
|
await writeFileEnsuringDir(outputPath, markdown)
|
|
|
|
const topics: string[] = Array.isArray(data.topics) ? data.topics : []
|
|
const entry: Entry = { title: data.title ?? relativePath, url: toMdUrl(relativePath) }
|
|
entriesByCollection[collection]?.push(entry)
|
|
for (const { name } of TOPICS) {
|
|
if (isInTopic({ collection, topics, topic: name })) guidesByTopic.get(name)!.push(entry)
|
|
}
|
|
})
|
|
)
|
|
|
|
// community guides have no markdown file of their own, so they link off-site
|
|
const communityGuides: { title: string; url: string; topics?: string[] }[] = JSON.parse(
|
|
await readFile(COMMUNITY_GUIDES_PATH, 'utf-8')
|
|
)
|
|
for (const { title, url, topics = [] } of communityGuides) {
|
|
for (const { name } of TOPICS) {
|
|
if (
|
|
isInTopic({ collection: 'communityGuides', topics: ['Community', ...topics], topic: name })
|
|
)
|
|
guidesByTopic.get(name)!.push({ title, url })
|
|
}
|
|
}
|
|
|
|
const topicEntries: Entry[] = TOPICS.map((topic) => ({
|
|
title: topic.name,
|
|
url: toMdUrl(`topics/${topicToSlug(topic.name)}.md`),
|
|
}))
|
|
|
|
await Promise.all([
|
|
...TOPICS.map((topic) => {
|
|
const markdown = renderTopicMarkdown(topic, guidesByTopic.get(topic.name)!)
|
|
const outputPath = path.join(OUTPUT_DIR, 'topics', `${topicToSlug(topic.name)}.md`)
|
|
return writeFileEnsuringDir(outputPath, markdown)
|
|
}),
|
|
writeFileEnsuringDir(
|
|
path.join(OUTPUT_DIR, 'sitemap.md'),
|
|
renderSitemapMarkdown({
|
|
topics: topicEntries,
|
|
guides: entriesByCollection.guides.sort(byTitle),
|
|
faqs: entriesByCollection.faqs.sort(byTitle),
|
|
troubleshooting: entriesByCollection.troubleshooting.sort(byTitle),
|
|
})
|
|
),
|
|
])
|
|
}
|
|
|
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
main()
|
|
}
|