diff --git a/.dockerignore b/.dockerignore index 358db729..f3d7c86b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -12,6 +12,7 @@ build/ dist/ storybook-static/ docs-static/ +blog-static/ coverage/ # Development files @@ -137,4 +138,7 @@ package-lock.json DEVELOPMENT.md DEPLOYMENT.md SECURITY.md -CLAUDE.md \ No newline at end of file +CLAUDE.md +blog/node_modules/ +blog/dist/ +blog/.astro/ diff --git a/.github/workflows/blog.yml b/.github/workflows/blog.yml new file mode 100644 index 00000000..f0615c39 --- /dev/null +++ b/.github/workflows/blog.yml @@ -0,0 +1,97 @@ +name: Blog builder + +# The blog is built in the cluster from pushed articles (blog/scripts/publish.ts). This +# workflow tests the builder and publishes its image, ghcr.io/-blog. It runs when the +# blog or the portfolio source it imports (tokens, components, site links) changes. +on: + push: + branches: [master] + paths: + - blog/** + - src/** + - .github/workflows/blog.yml + pull_request: + paths: + - blog/** + - src/** + - .github/workflows/blog.yml + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + name: Test the blog builder + runs-on: ubuntu-latest + defaults: + run: + working-directory: blog + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: yarn + cache-dependency-path: blog/yarn.lock + + - name: Install + run: yarn install --frozen-lockfile + + - name: Publish script tests + run: yarn test + + - name: Type check + run: yarn typecheck + env: + ASTRO_TELEMETRY_DISABLED: 1 + + - name: Build the sample articles + run: yarn build:fixtures + env: + ASTRO_TELEMETRY_DISABLED: 1 + NODE_ENV: production + + image: + name: Publish the builder image + needs: test + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository }}-blog + tags: | + type=sha,format=short + type=raw,value=latest,enable={{is_default_branch}} + labels: | + org.opencontainers.image.title=Blog builder for derekmackley.com/blog + org.opencontainers.image.description=Builds the blog from pushed articles and switches the live site atomically. Never reads the vault. + + - name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: blog/Dockerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: BUILD_ID=${{ github.sha }} + platforms: linux/amd64 + cache-from: type=gha,scope=blog + cache-to: type=gha,mode=max,scope=blog diff --git a/.gitignore b/.gitignore index 8b231169..4b77a1bc 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ node_modules/ # production /build /docs-static +/blog-static /logs # misc @@ -64,4 +65,6 @@ dist/ **/vendor **/.bundle **/.jekyll-cache -**/_site \ No newline at end of file +**/_site/blog/node_modules +/blog/dist +/blog/.astro diff --git a/blog/Dockerfile b/blog/Dockerfile new file mode 100644 index 00000000..66a89da4 --- /dev/null +++ b/blog/Dockerfile @@ -0,0 +1,40 @@ +# Blog builder: builds derekmackley.com/blog from pushed articles and switches the live +# site over atomically (scripts/publish.ts). Runs as a CronJob with the blog-content +# volume mounted at /content: it reads /content/articles and writes /content/site. +# It never sees the Obsidian vault. +# +# Build context is the repository root (the blog imports the portfolio's design tokens +# and React components from ../src): +# docker build -f blog/Dockerfile -t developer-portfolio-blog . + +# syntax=docker/dockerfile:1 +FROM node:22-alpine + +ENV NODE_ENV=production \ + ASTRO_TELEMETRY_DISABLED=1 \ + ARTICLES_DIR=/content/articles \ + SITE_DIR=/content/site + +WORKDIR /app/blog + +# Dependencies first, for layer caching. Dev tools (astro check, typescript) are not needed to build. +COPY blog/package.json blog/yarn.lock ./ +RUN yarn install --frozen-lockfile --production --non-interactive \ + && yarn cache clean + +# The shared portfolio source the blog imports (tokens, props-only components, site links) +COPY src /app/src +COPY blog/ /app/blog/ + +# Prove the image can build before it is published (the sample articles only) +RUN ARTICLES_DIR=/app/blog/fixtures/articles SITE_DIR=/tmp/selftest node scripts/publish.ts \ + && test -f /tmp/selftest/current/sample-article-format/index.html \ + && rm -rf /tmp/selftest /tmp/blog-* + +# BUILD_ID makes a new image rebuild the site even when the articles did not change +ARG BUILD_ID=dev +ENV BUILD_ID=${BUILD_ID} + +# Same uid/gid as the vault jobs and the volume's VolSync mover +USER 1000:1000 +ENTRYPOINT ["node", "scripts/publish.ts"] diff --git a/blog/astro.config.mjs b/blog/astro.config.mjs new file mode 100644 index 00000000..2848dc8a --- /dev/null +++ b/blog/astro.config.mjs @@ -0,0 +1,44 @@ +// @ts-check +import { fileURLToPath } from 'node:url'; +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; +import sitemap from '@astrojs/sitemap'; +import rehypeCallouts from 'rehype-callouts'; +import { unified } from '@astrojs/markdown-remark'; + +// The portfolio's source, shared read-only: design tokens and props-only React molecules +const portfolioSrc = fileURLToPath(new URL('../src', import.meta.url)); + +export default defineConfig({ + site: 'https://derekmackley.com', + // Served by the portfolio's Express server from the blog-content volume + base: '/blog', + trailingSlash: 'ignore', + build: { format: 'directory' }, + outDir: process.env.BLOG_OUT_DIR ?? './dist', + // The publisher's root filesystem is read-only; keep caches in /tmp there + cacheDir: process.env.BLOG_CACHE_DIR ?? './node_modules/.astro', + integrations: [react(), sitemap()], + markdown: { + processor: unified({ + // Raw HTML in an article is not rendered; articles are Markdown only + remarkRehype: { allowDangerousHtml: false }, + rehypePlugins: [[rehypeCallouts, { theme: 'github' }]], + }), + shikiConfig: { theme: 'github-dark-dimmed', wrap: true }, + }, + vite: { + resolve: { + alias: { + '@': portfolioSrc, + '@molecules': `${portfolioSrc}/components/molecules`, + '@atoms': `${portfolioSrc}/components/atoms`, + '@utils': `${portfolioSrc}/utils`, + '@tokens': `${portfolioSrc}/assets/css/design-system`, + }, + // Components under ../src must use this package's React, not a second copy + dedupe: ['react', 'react-dom', 'framer-motion'], + }, + server: { fs: { allow: ['..'] } }, + }, +}); diff --git a/blog/fixtures/articles/sample-article-format/format.svg b/blog/fixtures/articles/sample-article-format/format.svg new file mode 100644 index 00000000..ec86dd1c --- /dev/null +++ b/blog/fixtures/articles/sample-article-format/format.svg @@ -0,0 +1,7 @@ + + + + vaultpusharticles/buildersite/ + + + diff --git a/blog/fixtures/articles/sample-article-format/index.md b/blog/fixtures/articles/sample-article-format/index.md new file mode 100644 index 00000000..ed14226f --- /dev/null +++ b/blog/fixtures/articles/sample-article-format/index.md @@ -0,0 +1,43 @@ +--- +title: "Sample article: the format the push process writes" +description: "Development fixture showing every element an article can use. Never published: the real articles come from the push process." +published: 2026-11-21 +topics: [fixtures, format] +--- + +This is a **fixture** for local development and the build tests. Real articles arrive on the +`blog-content` volume from the push process, one folder per post. + +## Headings and text + +Plain Markdown: *emphasis*, **strong**, `inline code`, and [a link to the other sample](/blog/second-sample-post/). + +> A plain blockquote for a pull quote. + +> [!NOTE] +> Callouts use the GitHub form. `[!TIP]`, `[!WARNING]` and `[!IMPORTANT]` get their own colour. + +> [!WARNING] +> Raw HTML is dropped: the tags are removed and their text stays. + +## Images + +Images sit next to `index.md` and are referenced relatively: + +![The article format as a diagram](./format.svg) + +## Code and tables + +```yaml +# blog-content/articles//index.md +title: "Waiting Is Not Failing" +published: 2026-11-21 +topics: [gitops, flux] +``` + +| Field | Required | Notes | +|---|---|---| +| title | yes | up to 120 characters | +| description | yes | used in the list, RSS and search results | +| published | yes | YYYY-MM-DD | +| topics | no | lowercase words joined by hyphens | diff --git a/blog/fixtures/articles/second-sample-post/index.md b/blog/fixtures/articles/second-sample-post/index.md new file mode 100644 index 00000000..22be6526 --- /dev/null +++ b/blog/fixtures/articles/second-sample-post/index.md @@ -0,0 +1,9 @@ +--- +title: "Second sample post" +description: "Development fixture for the list, topics and older/newer navigation." +published: 2026-11-20 +updated: 2026-11-21 +topics: [fixtures] +--- + +A short second fixture so the index, topic pages and older/newer links have something to show. diff --git a/blog/package.json b/blog/package.json new file mode 100644 index 00000000..b92bf542 --- /dev/null +++ b/blog/package.json @@ -0,0 +1,36 @@ +{ + "name": "developer-portfolio-blog", + "private": true, + "type": "module", + "description": "derekmackley.com/blog: Astro site built from pushed articles, styled with the portfolio's design tokens. Never reads the vault.", + "engines": { + "node": ">=22.23.4" + }, + "scripts": { + "dev": "ARTICLES_DIR=fixtures/articles astro dev --port 4322", + "build": "astro build", + "build:fixtures": "ARTICLES_DIR=fixtures/articles astro build", + "preview": "astro preview --port 4322", + "publish:site": "node scripts/publish.ts", + "typecheck": "astro check", + "test": "node --test 'scripts/**/*.test.ts'" + }, + "dependencies": { + "@astrojs/markdown-remark": "7.3.10", + "@astrojs/react": "7.1.9", + "@astrojs/rss": "4.0.19", + "@astrojs/sitemap": "3.7.6", + "astro": "7.4.13", + "framer-motion": "14.14.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "rehype-callouts": "2.2.0" + }, + "devDependencies": { + "@astrojs/check": "^0.9.12", + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "typescript": "6.0.3" + } +} diff --git a/blog/scripts/publish.test.ts b/blog/scripts/publish.test.ts new file mode 100644 index 00000000..bfb5c57e --- /dev/null +++ b/blog/scripts/publish.test.ts @@ -0,0 +1,144 @@ +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { currentRelease, inputHash, listArticleFiles, pruneReleases, publish, type PublishOptions } from './publish.ts'; + +let root: string; +let articles: string; +let site: string; +let builds: number; + +/** Stand-in for astro: writes an index.html listing the article folders. */ +const fakeBuild = (articlesDir: string, outDir: string) => { + builds++; + mkdirSync(outDir, { recursive: true }); + writeFileSync(path.join(outDir, 'index.html'), existsSync(articlesDir) ? readdirSync(articlesDir).sort().join(',') : ''); +}; + +const opts = (over: Partial = {}): PublishOptions => ({ + articlesDir: articles, + siteDir: site, + buildId: 'test', + keep: 2, + force: false, + build: fakeBuild, + log: () => {}, + ...over, +}); + +const addArticle = (slug: string, body = 'text') => { + mkdirSync(path.join(articles, slug), { recursive: true }); + writeFileSync(path.join(articles, slug, 'index.md'), body); +}; + +const liveIndex = () => readFileSync(path.join(site, 'current', 'index.html'), 'utf8'); + +beforeEach(() => { + root = mkdtempSync(path.join(tmpdir(), 'publish-test-')); + articles = path.join(root, 'articles'); + site = path.join(root, 'site'); + mkdirSync(articles); + builds = 0; +}); + +afterEach(() => rmSync(root, { recursive: true, force: true })); + +describe('publish', () => { + it('builds a release and points current at it', () => { + addArticle('first-post'); + const result = publish(opts()); + assert.equal(result.status, 'published'); + assert.equal(liveIndex(), 'first-post'); + assert.equal(readlinkSync(path.join(site, 'current')), path.join('releases', result.release)); + assert.match(readFileSync(path.join(site, 'current', '.publish-hash'), 'utf8'), /^[0-9a-f]{64}\n$/); + }); + + it('does nothing when the articles have not changed', () => { + addArticle('first-post'); + const first = publish(opts()); + const second = publish(opts()); + assert.deepEqual(second, { status: 'unchanged', release: first.release }); + assert.equal(builds, 1); + }); + + it('rebuilds when an article changes, the builder changes, or --force', () => { + addArticle('first-post'); + publish(opts()); + addArticle('first-post', 'edited'); + assert.equal(publish(opts()).status, 'published'); + assert.equal(publish(opts({ buildId: 'new-image' })).status, 'published'); + assert.equal(publish(opts({ buildId: 'new-image', force: true })).status, 'published'); + assert.equal(builds, 4); + }); + + it('keeps the newest releases and never removes the live one', () => { + addArticle('a'); + for (const body of ['1', '2', '3', '4']) { + addArticle('a', body); + publish(opts()); + } + const releases = readdirSync(path.join(site, 'releases')); + assert.equal(releases.length, 2); + assert.ok(releases.includes(currentRelease(site)!)); + }); + + it('leaves the live site alone when the build fails', () => { + addArticle('first-post'); + publish(opts()); + addArticle('second-post'); + assert.throws(() => publish(opts({ build: () => { throw new Error('boom'); } })), /boom/); + assert.equal(liveIndex(), 'first-post'); + assert.equal(readdirSync(path.join(site, 'releases')).filter((n) => n.startsWith('.')).length, 0); + }); + + it('refuses a build with no index.html', () => { + addArticle('first-post'); + assert.throws(() => publish(opts({ build: (_a, out) => mkdirSync(out, { recursive: true }) })), /no index.html/); + assert.equal(existsSync(path.join(site, 'current')), false); + }); + + it('publishes an empty blog when there are no articles yet', () => { + rmSync(articles, { recursive: true }); + assert.equal(publish(opts()).status, 'published'); + assert.equal(liveIndex(), ''); + }); +}); + +describe('article files', () => { + it('lists regular files, sorted', () => { + addArticle('b'); + addArticle('a'); + writeFileSync(path.join(articles, 'a', 'diagram.png'), 'png'); + assert.deepEqual(listArticleFiles(articles), ['a/diagram.png', 'a/index.md', 'b/index.md']); + }); + + it('refuses symlinks, so nothing outside the articles can be read', () => { + addArticle('a'); + writeFileSync(path.join(root, 'secret.md'), 'private'); + symlinkSync(path.join(root, 'secret.md'), path.join(articles, 'a', 'leak.md')); + assert.throws(() => listArticleFiles(articles), /symlink/); + assert.throws(() => publish(opts()), /symlink/); + }); + + it('refuses hidden files', () => { + addArticle('a'); + writeFileSync(path.join(articles, 'a', '.env'), 'x'); + assert.throws(() => listArticleFiles(articles), /hidden/); + }); + + it('hashes names and contents', () => { + addArticle('a', 'one'); + const h1 = inputHash(articles, 'x'); + addArticle('a', 'two'); + assert.notEqual(inputHash(articles, 'x'), h1); + assert.notEqual(inputHash(articles, 'y'), inputHash(articles, 'x')); + }); +}); + +describe('pruneReleases', () => { + it('is a no-op without a releases folder', () => { + assert.deepEqual(pruneReleases(site, 3), []); + }); +}); diff --git a/blog/scripts/publish.ts b/blog/scripts/publish.ts new file mode 100644 index 00000000..d3ebbca6 --- /dev/null +++ b/blog/scripts/publish.ts @@ -0,0 +1,202 @@ +/** + * Builds the blog from pushed articles and switches the live site over atomically. + * + * ARTICLES_DIR articles pushed by the private side (read only): /index.md + images + * SITE_DIR what the portfolio serves: releases/-/ and `current` -> one of them + * + * Each run hashes the articles (plus BUILD_ID, the builder image's version) and does + * nothing when the live release was built from the same input. Otherwise it builds into + * scratch space, copies the result to a new release folder, then points `current` at it + * with a symlink rename, so a reader gets the old site or the new one, never a mix. + * The newest KEEP_RELEASES releases are kept for rollback; older ones are removed. + * + * It never reads anything outside ARTICLES_DIR: symlinks and dotfiles there are refused. + * + * Usage: ARTICLES_DIR=/content/articles SITE_DIR=/content/site node scripts/publish.ts [--force] + */ +import { createHash, randomBytes } from 'node:crypto'; +import { spawnSync } from 'node:child_process'; +import { + cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, + symlinkSync, writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export const HASH_FILE = '.publish-hash'; +const BLOG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +export interface PublishOptions { + articlesDir: string; + siteDir: string; + buildId: string; + keep: number; + force: boolean; + /** Builds the site from articlesDir into outDir; throws on failure */ + build: (articlesDir: string, outDir: string) => void; + log: (line: string) => void; +} + +export type PublishResult = + | { status: 'unchanged'; release: string } + | { status: 'published'; release: string; removed: string[] }; + +/** Every regular file under dir as a path relative to it, sorted. Refuses symlinks and dotfiles. */ +export const listArticleFiles = (dir: string): string[] => { + if (!existsSync(dir)) return []; + const out: string[] = []; + const walk = (rel: string) => { + for (const entry of readdirSync(path.join(dir, rel), { withFileTypes: true })) { + const child = rel ? `${rel}/${entry.name}` : entry.name; + if (entry.name.startsWith('.')) throw new Error(`refusing hidden file in articles: ${child}`); + if (entry.isSymbolicLink()) throw new Error(`refusing symlink in articles: ${child}`); + if (entry.isDirectory()) walk(child); + else if (entry.isFile()) out.push(child); + else throw new Error(`refusing special file in articles: ${child}`); + } + }; + walk(''); + return out.sort(); +}; + +/** Hash of the article files (names and bytes) and the builder version. */ +export const inputHash = (articlesDir: string, buildId: string): string => { + const hash = createHash('sha256').update(`build:${buildId}\0`); + for (const rel of listArticleFiles(articlesDir)) { + hash.update(rel).update('\0').update(readFileSync(path.join(articlesDir, rel))).update('\0'); + } + return hash.digest('hex'); +}; + +/** The release `current` points at, or null. */ +export const currentRelease = (siteDir: string): string | null => { + const link = path.join(siteDir, 'current'); + try { + if (!lstatSync(link).isSymbolicLink()) return null; + return path.basename(readlinkSync(link)); + } catch { + return null; + } +}; + +const releaseHash = (siteDir: string, release: string): string | null => { + try { + return readFileSync(path.join(siteDir, 'releases', release, HASH_FILE), 'utf8').trim(); + } catch { + return null; + } +}; + +/** Points `current` at releases/ with one rename. */ +export const switchCurrent = (siteDir: string, release: string): void => { + const tmp = path.join(siteDir, `.current-${randomBytes(4).toString('hex')}`); + symlinkSync(path.join('releases', release), tmp); + renameSync(tmp, path.join(siteDir, 'current')); +}; + +/** Removes all but the newest `keep` releases, never the live one. Returns what it removed. */ +export const pruneReleases = (siteDir: string, keep: number): string[] => { + const dir = path.join(siteDir, 'releases'); + if (!existsSync(dir)) return []; + const live = currentRelease(siteDir); + const releases = readdirSync(dir).filter((n) => !n.startsWith('.')).sort().reverse(); + const removed: string[] = []; + releases.forEach((name, i) => { + if (i >= Math.max(1, keep) && name !== live) { + rmSync(path.join(dir, name), { recursive: true, force: true }); + removed.push(name); + } + }); + return removed; +}; + +export const publish = (opts: PublishOptions): PublishResult => { + const hash = inputHash(opts.articlesDir, opts.buildId); + const live = currentRelease(opts.siteDir); + if (!opts.force && live && releaseHash(opts.siteDir, live) === hash) { + opts.log(`unchanged: ${live} was built from these articles`); + return { status: 'unchanged', release: live }; + } + + const scratch = path.join(tmpdir(), `blog-build-${randomBytes(4).toString('hex')}`); + try { + opts.log(`building ${listArticleFiles(opts.articlesDir).length} article file(s)`); + opts.build(opts.articlesDir, scratch); + if (!existsSync(path.join(scratch, 'index.html'))) throw new Error('build produced no index.html'); + writeFileSync(path.join(scratch, HASH_FILE), `${hash}\n`); + + const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z'); + // Random suffix: a forced rebuild of the same input in the same second gets its own folder + const release = `${stamp}-${hash.slice(0, 12)}-${randomBytes(2).toString('hex')}`; + const releases = path.join(opts.siteDir, 'releases'); + mkdirSync(releases, { recursive: true }); + // Copy into a hidden folder first (the volume is another filesystem), then rename into place + const staging = path.join(releases, `.staging-${release}`); + cpSync(scratch, staging, { recursive: true }); + renameSync(staging, path.join(releases, release)); + + switchCurrent(opts.siteDir, release); + opts.log(`published ${release}`); + const removed = pruneReleases(opts.siteDir, opts.keep); + if (removed.length) opts.log(`removed old release(s): ${removed.join(', ')}`); + return { status: 'published', release, removed }; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +}; + +/** + * The real build: `astro build` in a scratch copy of the blog project. + * + * Astro writes into the project folder while it builds (.astro/) and then renames files + * into the output folder, so the project and the output must share a filesystem, and the + * image's own files are read-only. The scratch copy holds the blog's sources; its + * node_modules and the shared portfolio src/ are symlinks back into the image. + */ +export const astroBuild = (articlesDir: string, outDir: string): void => { + const work = mkdtempSync(path.join(path.dirname(outDir), 'blog-work-')); + const project = path.join(work, 'blog'); + try { + cpSync(BLOG_ROOT, project, { + recursive: true, + filter: (src) => !['node_modules', 'dist', '.astro'].includes(path.basename(src)) || src === BLOG_ROOT, + }); + symlinkSync(path.join(BLOG_ROOT, 'node_modules'), path.join(project, 'node_modules')); + symlinkSync(path.resolve(BLOG_ROOT, '..', 'src'), path.join(work, 'src')); + const astro = path.join(project, 'node_modules', 'astro', 'bin', 'astro.mjs'); + const result = spawnSync(process.execPath, [astro, 'build'], { + cwd: project, + stdio: 'inherit', + env: { + ...process.env, + NODE_ENV: 'production', + ASTRO_TELEMETRY_DISABLED: '1', + ARTICLES_DIR: path.resolve(articlesDir), + BLOG_OUT_DIR: outDir, + BLOG_CACHE_DIR: path.join(work, 'cache'), + }, + }); + if (result.status !== 0) throw new Error(`astro build failed (exit ${result.status ?? result.signal})`); + } finally { + rmSync(work, { recursive: true, force: true }); + } +}; + +const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isMain) { + try { + publish({ + articlesDir: process.env.ARTICLES_DIR ?? '/content/articles', + siteDir: process.env.SITE_DIR ?? '/content/site', + buildId: process.env.BUILD_ID ?? 'dev', + keep: Number(process.env.KEEP_RELEASES ?? '3'), + force: process.argv.includes('--force'), + build: astroBuild, + log: (line) => console.log(`publish: ${line}`), + }); + } catch (e) { + console.error(`publish: failed: ${(e as Error).message}`); + process.exitCode = 1; + } +} diff --git a/blog/src/components/PostCard.astro b/blog/src/components/PostCard.astro new file mode 100644 index 00000000..1b48074e --- /dev/null +++ b/blog/src/components/PostCard.astro @@ -0,0 +1,27 @@ +--- +import type { Post } from '../lib/posts'; +import { formatDate, isoDate, readingMinutes, url } from '../lib/posts'; +import TopicList from './TopicList.astro'; + +interface Props { + post: Post; + /** The index's newest post is shown larger */ + featured?: boolean; +} + +const { post, featured = false } = Astro.props; +const { title, description, published, topics } = post.data; +--- + +
+

+ + + {readingMinutes(post.body)} min read +

+

+ {title} +

+

{description}

+ +
diff --git a/blog/src/components/TopicList.astro b/blog/src/components/TopicList.astro new file mode 100644 index 00000000..6b4e1dde --- /dev/null +++ b/blog/src/components/TopicList.astro @@ -0,0 +1,27 @@ +--- +import { url } from '../lib/posts'; + +interface Props { + topics: string[]; + /** Topic of the page being viewed, if any */ + current?: string; +} + +const { topics, current } = Astro.props; +--- + +{topics.length > 0 && ( + +)} diff --git a/blog/src/content.config.ts b/blog/src/content.config.ts new file mode 100644 index 00000000..2ed3d2b5 --- /dev/null +++ b/blog/src/content.config.ts @@ -0,0 +1,32 @@ +import { defineCollection, z } from 'astro:content'; +import { glob } from 'astro/loaders'; + +/** + * Articles arrive from the push process, one folder per post: + * + * //index.md front matter below + standard Markdown + * // referenced as ![alt](./image.png) + * + * The builder never sees the vault. Anything that does not match this schema + * fails the build, so a bad push can't ship a broken or half-filled page. + */ +const articlesDir = process.env.ARTICLES_DIR ?? './fixtures/articles'; + +const posts = defineCollection({ + loader: glob({ + pattern: '*/index.md', + base: articlesDir, + // The folder name is the slug: "waiting-is-not-failing/index.md" -> "waiting-is-not-failing" + generateId: ({ entry }) => entry.split('/')[0], + }), + schema: z.object({ + title: z.string().min(1).max(120), + description: z.string().min(1).max(300), + published: z.coerce.date(), + updated: z.coerce.date().optional(), + topics: z.array(z.string().regex(/^[a-z0-9-]+$/, 'topics are lowercase words joined by hyphens')).default([]), + draft: z.boolean().default(false), + }), +}); + +export const collections = { posts }; diff --git a/blog/src/layouts/Base.astro b/blog/src/layouts/Base.astro new file mode 100644 index 00000000..a24bfd31 --- /dev/null +++ b/blog/src/layouts/Base.astro @@ -0,0 +1,76 @@ +--- +// Shared shell: the portfolio's tokens and its real React components, so the blog +// reads as part of the same site as the resume, Storybook and the docs. The +// components render at build time only: the blog ships no JavaScript. +import '@tokens/index.css'; +import '../styles/blog.css'; +import HeaderName from '@atoms/HeaderName'; +import SiteLinks from '@molecules/SiteLinks'; +import { siteLinks } from '@/data/siteLinks'; +import { url } from '../lib/posts'; + +interface Props { + title: string; + description: string; + /** Article pages pass their dates for Open Graph */ + article?: { published: Date; updated?: Date }; +} + +const { title, description, article } = Astro.props; +const fullTitle = title === 'Blog' ? 'Blog | Derek Mackley' : `${title} | Derek Mackley`; +const canonical = new URL(Astro.url.pathname, Astro.site); +const headerLinks = siteLinks.filter((link) => !link.external); +const year = new Date().getUTCFullYear(); +--- + + + + + + + {fullTitle} + + + + + + + + + + + + {article && } + {article?.updated && } + + + + + + + +
+
+ + + + +
+
+ +
+ +
+ +
+ +
+ + diff --git a/blog/src/lib/posts.ts b/blog/src/lib/posts.ts new file mode 100644 index 00000000..a0ab356d --- /dev/null +++ b/blog/src/lib/posts.ts @@ -0,0 +1,46 @@ +import { getCollection, type CollectionEntry } from 'astro:content'; + +export type Post = CollectionEntry<'posts'>; + +const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +/** Paths the blog itself uses; an article can't take them */ +const RESERVED = new Set(['topics', '404', 'rss', 'media', 'assets', '_astro']); + +/** Published posts, newest first. A folder name that isn't a clean, free slug fails the build. */ +export const getPosts = async (): Promise => { + const posts = await getCollection('posts', ({ data }) => !data.draft); + for (const post of posts) { + if (!SLUG.test(post.id)) { + throw new Error(`Article folder "${post.id}" is not a valid slug (lowercase words joined by hyphens)`); + } + if (RESERVED.has(post.id)) { + throw new Error(`Article folder "${post.id}" uses a name the blog reserves for its own pages`); + } + } + return posts.sort((a, b) => b.data.published.getTime() - a.data.published.getTime()); +}; + +/** Every topic with its posts, alphabetical. */ +export const getTopics = async (): Promise> => { + const topics = new Map(); + for (const post of await getPosts()) { + for (const topic of post.data.topics) { + topics.set(topic, [...(topics.get(topic) ?? []), post]); + } + } + return new Map([...topics.entries()].sort(([a], [b]) => a.localeCompare(b))); +}; + +/** "November 21, 2026", in UTC so the date never shifts with the build machine's zone. */ +export const formatDate = (date: Date): string => + date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }); + +/** "2026-11-21" for