The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
perf(design-system): improve local dev content reload (#50069)
Danny White31046e7a7f34
diff --git a/apps/design-system/README.md b/apps/design-system/README.mdindex a726c230985..45cd3d78a54 100644--- a/apps/design-system/README.md+++ b/apps/design-system/README.md@@ -4,40 +4,60 @@ Design resources for building consistent user experiences at Supabase.## Getting started-First, make a copy of _.env.local.example_ and name it _env.local_. Then install any required packages and start the development server:+From the repo root:```bash+# Copy local env vars (sets NEXT_PUBLIC_BASE_PATH for asset URLs)+cp apps/design-system/.env.local.example apps/design-system/.env.local+# Move into the design-system appcd apps/design-system+# Install dependenciespnpm i+# Build the registry and Velite content, then start the dev serverspnpm dev```-The `dev` command generates `__registry__`, then runs the Next.js development server and Contentlayer together. That is the recommended workflow.+Or from `apps/design-system`:++```bash+# Copy local env vars (sets NEXT_PUBLIC_BASE_PATH for asset URLs)+cp .env.local.example .env.local+# Install dependencies+pnpm i+# Build the registry and Velite content, then start the dev servers+pnpm dev+```++The `dev` command builds the registry and Velite content, then runs the Next.js dev server and Velite watcher in parallel.++Open [http://localhost:3003/design-system](http://localhost:3003/design-system) in your browser to see the result.++Doc pages load compiled MDX from `.velite/codes/*.json` per document. Metadata lives in the smaller `allDocs.json` index (~367KB instead of ~27MB), so content edits only reload the changed doc's code.### Alternative commands-You can also run the development server and content watcher separately. Generate the registry first, because `dev:next` and `dev:content` do not:+You can also run the development server and content watcher separately. Build the registry and content first, because `dev:next` and `dev:content` do not:```bash-pnpm generate:registry+pnpm build:registry+pnpm build:content# Run only the Next.js development serverpnpm dev:next-# Run only the content watcher (in a separate terminal shell)+# Run only the Velite content watcher (in a separate terminal shell)pnpm dev:content```-From the repo root, `pnpm dev:design-system` runs the same `dev` script, so it also generates `__registry__`. If you split the watchers from the root, generate first:+From the repo root, `pnpm dev:design-system` runs the same `dev` script. If you split the watchers from the root, build first:```bash-pnpm --filter=design-system generate:registry+pnpm --filter=design-system build:registry+pnpm --filter=design-system build:contentpnpm --filter=design-system dev:nextpnpm --filter=design-system dev:content```-Open [http://localhost:3003](http://localhost:3003) in your browser to see the result.-### Watching for MDX changesThe `dev` command watches MDX files and hot-reloads them. If you are running `pnpm dev:next` on its own, also run `pnpm dev:content` in another terminal.@@ -64,5 +84,5 @@ Do not edit `__registry__`. `pnpm dev`, `pnpm typecheck`, and `pnpm build` gener```bashcd apps/design-system-pnpm generate:registry+pnpm build:registry```diff --git a/apps/design-system/app/(app)/docs/[[...slug]]/page.tsx b/apps/design-system/app/(app)/docs/[[...slug]]/page.tsxindex 3f3aa0f3c3d..0e59e898eb7 100644--- a/apps/design-system/app/(app)/docs/[[...slug]]/page.tsx+++ b/apps/design-system/app/(app)/docs/[[...slug]]/page.tsx@@ -3,8 +3,10 @@ import { DocsPager, getBreadcrumbSegments } from '@/components/pager'import { SourcePanel } from '@/components/source-panel'import { DashboardTableOfContents } from '@/components/toc'import { siteConfig } from '@/config/site'+import { getAllDocs, getDocBySlug, getDocMetaBySlug } from '@/lib/docs'import { getTableOfContents } from '@/lib/toc'import { absoluteUrl } from '@/lib/utils'+/* eslint-disable turbo/no-undeclared-env-vars */import '@/styles/code-block-variables.css'import '@/styles/mdx.css'@@ -16,8 +18,6 @@ import { notFound } from 'next/navigation'import Balancer from 'react-wrap-balancer'import { ScrollArea, Separator } from 'ui'-import { allDocs } from '@/.velite'-interface DocPageProps {params: Promise<{slug: string[]@@ -26,13 +26,7 @@ interface DocPageProps {async function getDocFromParams({ params }: { params: { slug: string[] } }) {const slug = params.slug?.join('/') || ''- const doc = allDocs.find((doc) => doc.slugAsParams === slug)-- if (!doc) {- return null- }-- return doc+ return getDocMetaBySlug(slug)}export async function generateMetadata(props: DocPageProps): Promise<Metadata> {@@ -71,14 +65,20 @@ export async function generateMetadata(props: DocPageProps): Promise<Metadata> {}export async function generateStaticParams(): Promise<{ slug: string[] }[]> {+ if (process.env.NODE_ENV === 'development') {+ return []+ }++ const allDocs = await getAllDocs()return allDocs.map((doc) => ({- slug: doc.slugAsParams.split('/'),+ slug: doc.slugAsParams ? doc.slugAsParams.split('/') : [],}))}export default async function DocPage(props: DocPageProps) {const params = await props.params- const doc = await getDocFromParams({ params })+ const slug = params.slug?.join('/') || ''+ const doc = await getDocBySlug(slug)if (!doc) {notFound()diff --git a/apps/design-system/lib/docs.ts b/apps/design-system/lib/docs.tsnew file mode 100644index 00000000000..da1d8f69ed3--- /dev/null+++ b/apps/design-system/lib/docs.ts@@ -0,0 +1,44 @@+import 'server-only'++/* eslint-disable turbo/no-undeclared-env-vars */+import { readFile } from 'node:fs/promises'+import path from 'node:path'+import { connection } from 'next/server'++import type { Doc as DocMeta } from '@/.velite'++export type { DocMeta }++export type Doc = DocMeta & { code: string }++const CODE_DIR = path.join(process.cwd(), '.velite/codes')++async function loadDocCode(codeId: string): Promise<string> {+ const raw = await readFile(path.join(CODE_DIR, `${codeId}.json`), 'utf8')+ return JSON.parse(raw) as string+}++export async function getAllDocs(): Promise<DocMeta[]> {+ if (process.env.NODE_ENV === 'development') {+ await connection()+ }++ const { allDocs } = await import('@/.velite')+ return allDocs+}++export async function getDocMetaBySlug(slug: string): Promise<DocMeta | null> {+ const allDocs = await getAllDocs()+ return allDocs.find((doc) => doc.slugAsParams === slug) ?? null+}++export async function getDocBySlug(slug: string): Promise<Doc | null> {+ const doc = await getDocMetaBySlug(slug)++ if (!doc) {+ return null+ }++ const code = await loadDocCode(doc.codeId)+ return { ...doc, code }+}diff --git a/apps/design-system/velite.config.js b/apps/design-system/velite.config.jsindex 088d9307b4b..f6805e6a44d 100644--- a/apps/design-system/velite.config.js+++ b/apps/design-system/velite.config.js@@ -1,3 +1,5 @@+/* eslint-disable turbo/no-undeclared-env-vars */+import { mkdir, rename, writeFile } from 'node:fs/promises'import path from 'path'import { getHighlighter, loadTheme } from '@shikijs/compat'import rehypeAutolinkHeadings from 'rehype-autolink-headings'@@ -10,6 +12,13 @@ import { defineConfig, s } from 'velite'import { rehypeComponent } from './lib/rehype-component'+const CODE_OUTPUT_DIR = '.velite/codes'++function toCodeId(slugAsParams) {+ if (!slugAsParams) return 'index'+ return Buffer.from(slugAsParams, 'utf8').toString('base64url')+}+const LinksProperties = s.object({doc: s.string().optional(),api: s.string().optional(),@@ -46,16 +55,29 @@ const docs = s// real benefit for a dev-only content cache, and dominates build time.code: s.mdx({ copyLinkedFiles: false, minify: false }),})- .transform(({ path: flattenedPath, ...data }) => ({- ...data,- slug: `/${flattenedPath}`,- slugAsParams: flattenedPath.split('/').slice(1).join('/'),- }))+ .transform(async ({ path: flattenedPath, code, ...data }) => {+ const slugAsParams = flattenedPath.split('/').slice(1).join('/')+ const codeId = toCodeId(slugAsParams)+ const codesDir = path.join(process.cwd(), CODE_OUTPUT_DIR)++ await mkdir(codesDir, { recursive: true })+ const codePath = path.join(codesDir, `${codeId}.json`)+ const tmpPath = `${codePath}.tmp`+ await writeFile(tmpPath, JSON.stringify(code), 'utf8')+ await rename(tmpPath, codePath)++ return {+ ...data,+ slug: `/${flattenedPath}`,+ slugAsParams,+ codeId,+ }+ })export default defineConfig({root: './content',output: {- clean: true,+ clean: process.env.NODE_ENV === 'production',},collections: {allDocs: {