From 83b7ff5e9af99851c6a7350c9abd53485fc3e565 Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 22:03:23 -0600 Subject: [PATCH 1/3] Mark preview builds and add a generic content-collection loader Preview builds (any base path other than /) now carry noindex and a 'Preview, not final' banner. src/build/collections.ts loads and validates content//*.md with front-matter, and checks references between items, so new page types need only a schema and a template. Pot-Run: b872 --- docs/README.md | 1 + docs/content-collections.md | 59 +++++++ docs/deployment.md | 11 ++ src/build/collections.ts | 157 ++++++++++++++++++ src/build/config.ts | 5 + src/design/common/layout.tsx | 6 +- .../components/preview-banner/examples.tsx | 15 ++ .../components/preview-banner/index.tsx | 12 ++ .../components/preview-banner/styles.css | 16 ++ src/design/index.css | 1 + src/pages/design-system.tsx | 3 + tests/build/collections.test.ts | 60 +++++++ .../bad/content/things/Bad_Name.md | 3 + .../collections/ok/content/things/alpha.md | 4 + .../collections/ok/content/things/beta.md | 9 + .../collections/ok/content/things/notes.txt | 1 + tests/views/layout.test.tsx | 21 +++ 17 files changed, 383 insertions(+), 1 deletion(-) create mode 100644 docs/content-collections.md create mode 100644 src/build/collections.ts create mode 100644 src/design/components/preview-banner/examples.tsx create mode 100644 src/design/components/preview-banner/index.tsx create mode 100644 src/design/components/preview-banner/styles.css create mode 100644 tests/build/collections.test.ts create mode 100644 tests/fixtures/collections/bad/content/things/Bad_Name.md create mode 100644 tests/fixtures/collections/ok/content/things/alpha.md create mode 100644 tests/fixtures/collections/ok/content/things/beta.md create mode 100644 tests/fixtures/collections/ok/content/things/notes.txt diff --git a/docs/README.md b/docs/README.md index bd6b2caa..f2666d37 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ This directory explains how the site behaves and how to work in it. It is writte - **`views/`** — one file per page describing its behavior; maps to `src/web/pages/` and `tests/views/`. - **`catalog.md`** — what the catalog is, how it's assembled, and how to change it. - **`content.md`** — how to author prose: hero, commitment, about, per-repo overlays. +- **`content-collections.md`** — the generic loader for folders of markdown items (`content//*.md`). - **`stewardship.md`** — tier definitions and how the health checks are evaluated. - **`deployment.md`** — branch previews, production, the gh-pages layout, and the CNAME. - **`testing.md`** — the TDD strategy, where tests live, and how to run each suite. diff --git a/docs/content-collections.md b/docs/content-collections.md new file mode 100644 index 00000000..98c015a0 --- /dev/null +++ b/docs/content-collections.md @@ -0,0 +1,59 @@ +# Content collections + +A content collection is a folder of markdown files, `content//.md`, each with YAML front-matter and an +optional markdown body. `src/build/collections.ts` loads and validates them so that a new kind of page (a project, a +note, an area) needs only a small schema and a page template, not another bespoke loader. + +## Loading + +```ts +import { loadCollection, type Fields } from './collections' + +type Project = { title: string; stage: 'experiment' | 'supported'; people: string[] } + +const parseProject = (f: Fields): Project => ({ + title: f.string('title'), + stage: f.oneOf('stage', ['experiment', 'supported'] as const), + people: f.stringList('people'), +}) + +const projects = await loadCollection(rootDir, 'projects', parseProject) +// [{ slug: 'iml', data: { title, stage, people }, body: '…markdown…' }, …] +``` + +- **Slugs** are the file name without `.md`: lowercase letters, digits and hyphens. They become URLs, so treat them as + permanent. +- **A missing folder** is an empty collection, so a page type can ship before any content exists. +- **Items are sorted by slug.** Sort again by a field such as `order` or a date where the page needs it. +- **The body** is returned as markdown; the page renders it (for example with `marked`, as `ContentPage` does). + +## Validation + +`Fields` reads one item's front-matter. Each reader throws an error naming the file and the field, which fails the +build: + +| Reader | Accepts | +|---|---| +| `string(f)` / `optionalString(f)` | a non-empty string / a string or nothing | +| `number(f, fallback?)` | a number | +| `boolean(f, fallback)` | `true` or `false` | +| `oneOf(f, values, fallback?)` | one of a fixed set of strings | +| `date(f)` / `optionalDate(f)` | a date written `YYYY-MM-DD` | +| `stringList(f)` | a list of strings (missing means empty) | +| `list(f, parse)` | a list of mappings, each parsed with its own `Fields` | + +## References between items + +When one item names another (a note naming its project, a project naming its area), check the names at build time: + +```ts +import { assertRefs, refsOf } from './collections' + +assertRefs(refsOf('notes', notes, 'project', (d) => d.project), projects.map((p) => p.slug), 'project') +``` + +`assertRefs` lists every broken reference in one error, so a single build run shows them all. + +## Tests + +`tests/build/collections.test.ts`, with fixtures in `tests/fixtures/collections/`. diff --git a/docs/deployment.md b/docs/deployment.md index de9ee8a1..aeec5070 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -36,6 +36,17 @@ The environment entry itself persists in the Deployments sidebar. Deleting envir `CNAME` at the source repo root contains `labs.flexion.us`. The build driver (`src/build/entry.tsx`) copies it into `dist/` on production builds only — preview subdirectories must not carry a CNAME. +## Preview builds are marked + +Any build whose base path is not `/` is a branch preview (`isPreview` in `src/build/config.ts`). Every page of a +preview carries: + +- ``, so search engines don't index drafts, and +- a "Preview, not final" banner linking to the live site (`src/design/components/preview-banner/`). + +Production builds have neither. Previews are still public: anyone with the URL can open them, and the branch is +visible in this public repository. + ## Base path `SITE_BASE_URL` is the single knob that changes how internal links and asset URLs are emitted. The default is `/`. Any non-root value is normalized to `/path/`. diff --git a/src/build/collections.ts b/src/build/collections.ts new file mode 100644 index 00000000..8eed14b1 --- /dev/null +++ b/src/build/collections.ts @@ -0,0 +1,157 @@ +import { parse as parseYaml } from 'yaml' +import { readdir } from 'node:fs/promises' +import { join } from 'node:path' + +// A content collection is a folder of markdown files, content//.md, +// each with YAML front-matter. See docs/content-collections.md. + +export type CollectionItem = { + slug: string // file name without .md; stable, used in URLs + data: T // validated front-matter + body: string // markdown after the front-matter, trimmed +} + +const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?/ +const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/ + +// Loads and validates every item in content//. A missing folder is an +// empty collection. Items are sorted by slug; callers re-sort as needed. +export async function loadCollection( + rootDir: string, + name: string, + parse: (fields: Fields) => T, +): Promise[]> { + const dir = join(rootDir, 'content', name) + let files: string[] + try { + files = await readdir(dir) + } catch { + return [] + } + + const items: CollectionItem[] = [] + for (const file of files.sort()) { + if (!file.endsWith('.md')) continue + const slug = file.slice(0, -'.md'.length) + const where = `content/${name}/${file}` + if (!SLUG_RE.test(slug)) { + throw new Error(`${where}: file name must be lowercase letters, digits and hyphens`) + } + const raw = await Bun.file(join(dir, file)).text() + const match = raw.match(FRONTMATTER_RE) + if (!match) throw new Error(`${where}: missing YAML front-matter`) + const parsed = parseYaml(match[1]) ?? {} + if (typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`${where}: front-matter must be a mapping`) + } + const data = parse(new Fields(where, parsed as Record)) + items.push({ slug, data, body: raw.slice(match[0].length).trim() }) + } + return items +} + +// Typed, error-reporting access to one item's front-matter. +export class Fields { + constructor( + readonly where: string, + readonly raw: Record, + ) {} + + fail(field: string, message: string): never { + throw new Error(`${this.where}: "${field}" ${message}`) + } + + string(field: string): string { + const v = this.raw[field] + if (typeof v !== 'string' || v.trim() === '') this.fail(field, 'is required and must be a string') + return v + } + + optionalString(field: string): string | undefined { + const v = this.raw[field] + if (v === undefined || v === null) return undefined + if (typeof v !== 'string') this.fail(field, 'must be a string') + return v + } + + number(field: string, fallback?: number): number { + const v = this.raw[field] + if (v === undefined && fallback !== undefined) return fallback + if (typeof v !== 'number') this.fail(field, 'is required and must be a number') + return v + } + + boolean(field: string, fallback: boolean): boolean { + const v = this.raw[field] + if (v === undefined) return fallback + if (typeof v !== 'boolean') this.fail(field, 'must be true or false') + return v + } + + oneOf(field: string, values: readonly V[], fallback?: V): V { + const v = this.raw[field] + if (v === undefined && fallback !== undefined) return fallback + if (typeof v !== 'string' || !values.includes(v as V)) { + this.fail(field, `must be one of ${values.join(', ')}`) + } + return v as V + } + + // A date written YYYY-MM-DD (the yaml package's default schema keeps it a string). + date(field: string): string { + const v = this.string(field) + if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) this.fail(field, 'must be a date written YYYY-MM-DD') + return v + } + + optionalDate(field: string): string | undefined { + return this.raw[field] === undefined ? undefined : this.date(field) + } + + stringList(field: string): string[] { + const v = this.raw[field] + if (v === undefined || v === null) return [] + if (!Array.isArray(v) || v.some((s) => typeof s !== 'string' || s === '')) { + this.fail(field, 'must be a list of strings') + } + return v as string[] + } + + list(field: string, parse: (item: Fields, index: number) => T): T[] { + const v = this.raw[field] + if (v === undefined || v === null) return [] + if (!Array.isArray(v)) this.fail(field, 'must be a list') + return v.map((item, i) => { + if (!item || typeof item !== 'object' || Array.isArray(item)) { + this.fail(`${field}[${i}]`, 'must be a mapping') + } + return parse(new Fields(`${this.where} ${field}[${i}]`, item as Record), i) + }) + } +} + +export type Ref = { from: string; field: string; to: string } + +// Fails the build if any reference names an item that does not exist. Lists +// every broken reference at once so one build run shows them all. +export function assertRefs(refs: Ref[], known: Iterable, targetLabel: string): void { + const names = new Set(known) + const broken = refs.filter((r) => !names.has(r.to)) + if (broken.length === 0) return + const lines = broken.map((r) => ` ${r.from}: "${r.field}" names unknown ${targetLabel} "${r.to}"`) + throw new Error(`Broken references:\n${lines.join('\n')}`) +} + +// Collects refs from every item of a collection. +export function refsOf( + name: string, + items: CollectionItem[], + field: string, + get: (data: T) => string[] | string | undefined, +): Ref[] { + return items.flatMap((item) => { + const v = get(item.data) + const targets = v === undefined ? [] : Array.isArray(v) ? v : [v] + return targets.map((to) => ({ from: `content/${name}/${item.slug}.md`, field, to })) + }) +} diff --git a/src/build/config.ts b/src/build/config.ts index 04ef1400..f691f3bb 100644 --- a/src/build/config.ts +++ b/src/build/config.ts @@ -20,3 +20,8 @@ export function createConfig(env: NodeJS.ProcessEnv = process.env): SiteConfig { buildTime: new Date().toISOString(), } } + +// A branch preview is any build served below the site root (see docs/deployment.md). +export function isPreview(config: Pick): boolean { + return config.basePath !== '/' +} diff --git a/src/design/common/layout.tsx b/src/design/common/layout.tsx index 45e2c674..46b0018d 100644 --- a/src/design/common/layout.tsx +++ b/src/design/common/layout.tsx @@ -2,7 +2,8 @@ import type { Child } from 'hono/jsx' import { raw } from 'hono/html' import { Header } from '../components/header' import { Footer } from '../components/footer' -import { url } from '../../build/config' +import { PreviewBanner } from '../components/preview-banner' +import { url, isPreview } from '../../build/config' import type { SiteConfig } from '../../build/config' export function Layout({ @@ -15,12 +16,14 @@ export function Layout({ children: Child }) { const documentTitle = title ? `${title} — Flexion Labs` : 'Flexion Labs' + const preview = isPreview(config) return ( {documentTitle} + {preview ? : null} @@ -31,6 +34,7 @@ export function Layout({ + {preview ? : null}
{children}