/** * BunPress-powered blog. * * The blog at `/blog` is rendered by BunPress (our docs engine) with a custom * Stacks theme โ€” not by the stx view layer. Posts are markdown files in * `content/blog/*.md`. A post body is Markdown, not a BunPress docs page: it is * rendered by `renderSafeMarkdown` from `@stacksjs/cms/markdown` (GFM, heading * anchors, HTML in the post shown as text, unsafe links dropped), never through * BunPress's docs pipeline, which evaluates templates and includes files. * BunPress highlights its code blocks and wraps the page in its themed shell. * We style its BunPress theme via `content/blog/.theme.css` and add blog * chrome (post header, author card, share, listing cards). RSS + sitemap are * generated here from `listPosts()`, not by BunPress's `buildRssFeed` / * `buildSitemap` โ€” see the note on `feedXml` for why. * * A post with `draft: true` in its frontmatter is written by the dashboard * (see ./blog-admin.ts) and is excluded from the listing, the feed, the sitemap, * and its own URL, so unpublished work has no public surface. * * Branding (titles, nav, author fallback, colophon, theme modes) is read from * the app's `config/blog.ts`; the defaults below match the Stacks blog so an * unconfigured app renders exactly as before. * * Post bodies go through `renderPostHtml` from `@stacksjs/cms/article` (built * on ts-medium-editor's article renderer): images become figures and adjacent * ones grids, sized from the files in public/, with lazy loading and * click-to-zoom, and a bare YouTube, Vimeo or HQ.training link becomes an * embed. stx-native blogs call the same function from their post view. * * Two consumers share the same renderers: * - `renderBlog(req)` โ€” dynamic, used by the dev server's onRequest hook. * - `buildBlog({ outDir, baseUrl })` โ€” static, used at deploy time to emit * `dist/blog/**` (see config/cloud.ts), the same way /docs builds. */ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' import { articleCss, articleScript, renderPostHtml } from '@stacksjs/cms/article' import { loadPosts } from '@stacksjs/cms/blog' import { renderSafeMarkdown } from '@stacksjs/cms/markdown' import { usableOrigin } from './site-origin' // Re-exported: it lived here first, and callers import it from this module. export { usableOrigin } const CONTENT_DIR = join(process.cwd(), 'content/blog') const THEME_FILE = join(CONTENT_DIR, '.theme.css') interface BunPress { highlightCode: (code: string, language: string, theme?: string) => Promise wrapInLayout: (content: string, config: any, currentPath: string, layout?: string) => Promise buildRssFeed?: (docsDir: string, config: any, rssConfig?: any) => Promise buildSitemap?: (docsDir: string, config: any) => Promise defaultConfig: any } type BlogThemeMode = 'colored' | 'light' | 'dark' /** Branding knobs read from `config/blog.ts` (all optional there). */ interface BlogSiteConfig { title: string description: string /** Short title used in the layout nav; defaults to `title`. */ siteTitle: string /** Fallback post author when frontmatter has none. */ author: string /** Canonical site origin for feed/sitemap URLs when no request origin exists. */ url: string nav: { text: string, link: string }[] /** Which modes the theme toggle offers. */ themes: BlogThemeMode[] defaultTheme: BlogThemeMode /** Raw HTML for the footer colophon line. */ colophon: string /** Empty-state heading shown when no posts exist yet. */ emptyTitle: string /** Empty-state copy shown under the heading (plain text). */ emptyText: string } /** * What a key missing from `config/blog.ts` falls back to: the app's own name * (APP_NAME) and origin (APP_URL). These were stacksjs.com's values, so an app * whose config left `url` out published a feed and sitemap linking to * stacksjs.com, under "The Stacks Blog". * * Read at call time rather than module load, so the app's env is in place. */ function blogDefaults(): BlogSiteConfig { const appName = (process.env.APP_NAME || '').trim() const appUrl = (process.env.APP_URL || '').trim().replace(/\/+$/, '') const title = appName ? `${appName} Blog` : 'Blog' return { title, description: '', siteTitle: title, author: appName, url: appUrl && !/^https?:\/\//.test(appUrl) ? `https://${appUrl}` : appUrl, nav: [ { text: 'Home', link: '/' }, { text: 'Blog', link: '/blog' }, ], themes: ['colored', 'light', 'dark'], defaultTheme: 'colored', colophon: 'RSS', emptyTitle: 'No posts yet', emptyText: 'The first one is in the works. Leave your email and it will land in your inbox the moment it ships.', } } let sitePromise: Promise | null = null /** Load `config/blog.ts` and merge over the app-derived defaults (cached). */ function site(): Promise { if (!sitePromise) { sitePromise = (async () => { try { const mod = await import(join(process.cwd(), 'config/blog.ts')) const cfg = (mod.default ?? {}) as Partial const merged: BlogSiteConfig = { ...blogDefaults(), ...cfg } if (!cfg.siteTitle && cfg.title) merged.siteTitle = cfg.title return merged } catch { return blogDefaults() } })() } return sitePromise } let bunpressPromise: Promise | null = null async function loadBunPress(): Promise { if (!bunpressPromise) { bunpressPromise = (async () => { const sourceCandidates = [ join(homedir(), 'Code/Tools/bunpress/packages/bunpress/dist/src/index.js'), join(process.cwd(), 'pantry/@stacksjs/bunpress/dist/src/index.js'), ] const candidates = sourceCandidates.filter(entry => existsSync(entry)) try { candidates.push(Bun.resolveSync('@stacksjs/bunpress', import.meta.dir)) } catch { // BunPress is optional for apps that use their own blog renderer. } for (const entry of new Set(candidates)) { try { return (await import(entry)) as unknown as BunPress } catch (cause) { const detail = cause instanceof Error ? cause.message : String(cause) throw new Error(`[blog] Failed to import BunPress from ${entry}: ${detail}`, { cause }) } } return null })() } return bunpressPromise } function escapeHtml(s: string): string { return String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]!)) } function escapeXml(s: string): string { return String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[c]!)) } function postUrl(baseUrl: string, slug: string): string { return `${baseUrl.replace(/\/$/, '')}/blog/${slug}` } function rssDate(date?: string): string { if (!date) return '' const parsed = new Date(date) return Number.isNaN(parsed.getTime()) ? date : parsed.toUTCString() } async function fallbackFeedXml(baseUrl: string): Promise { const cfg = await site() const origin = usableOrigin(baseUrl) || usableOrigin(cfg.url) || cfg.url const posts = listPosts().slice(0, 50) const items = posts.map((p) => { const url = postUrl(origin, p.slug) // `dc:creator` is carried over from the BunPress-built feed this replaced, // so readers that show a byline keep showing one. return ` ${escapeXml(p.fm.title || p.slug)} ${escapeXml(url)} ${escapeXml(url)} ${escapeXml(rssDate(p.fm.date))} ${escapeXml(p.fm.description || '')} ${escapeXml(p.fm.author || cfg.author)} ` }).join('\n') return ` ${escapeXml(cfg.title)} ${escapeXml(`${origin}/blog`)} ${escapeXml(cfg.description)} ${items} ` } async function fallbackSitemapXml(baseUrl: string): Promise { const cfg = await site() const origin = usableOrigin(baseUrl) || usableOrigin(cfg.url) || cfg.url const urls = [`${origin}/blog`, ...listPosts().map(p => postUrl(origin, p.slug))] .map(url => ` ${escapeXml(url)}`) .join('\n') return ` ${urls} ` } function formatDate(d?: string): string { if (!d) return '' const date = new Date(d) if (Number.isNaN(date.getTime())) return d const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return `${months[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}` } const THEME_BUTTONS: Record = { colored: { label: 'Glacier theme', glyph: '๐ŸŒฒ' }, light: { label: 'Light theme', glyph: 'โ˜€' }, dark: { label: 'Dark theme', glyph: '๐ŸŒ™' }, } /** * Chrome injected into every blog page: * - an early (head-ish) script that applies the saved theme before paint and * defines the toggle handler, then * - a fixed theme switcher offering the configured modes. * The default mode comes from config (`defaultTheme`); the script only diverges * from it when the visitor has previously chosen another mode, or when a * `?theme=` override is present. */ async function blogChrome(): Promise { const cfg = await site() const modes = cfg.themes.length ? cfg.themes : blogDefaults().themes const fallback = modes.includes(cfg.defaultTheme) ? cfg.defaultTheme : modes[0] const buttons = modes.map(m => ``).join('\n ') const toggle = modes.length > 1 ? `
${buttons}
` : '' return ` ${toggle}` } /** Minimal hairline footer that closes out every blog page. */ async function blogFooter(): Promise { const cfg = await site() return `

${cfg.colophon}

` } async function blogConfig(bp: BunPress, fm: Record) { const cfg = await site() const themeCss = existsSync(THEME_FILE) ? readFileSync(THEME_FILE, 'utf-8') : '' const baseCss = (bp.defaultConfig.markdown?.css as string) || '' return { ...bp.defaultConfig, title: fm.title || cfg.title, description: fm.description || cfg.description, docsDir: CONTENT_DIR, theme: 'bun', markdown: { ...bp.defaultConfig.markdown, css: `${baseCss}\n${articleCss()}\n${themeCss}` }, themeConfig: { siteTitle: cfg.siteTitle, nav: cfg.nav, }, } } /** * The published blog's paths, for the site-wide `/sitemap.xml` to merge in * (see `./seo.ts`). Empty when there are no published posts, so an app with an * empty `content/blog` does not advertise a listing page. * * Driven by `listPosts()` like the feed and `/blog/sitemap.xml`, so a draft is * missing from every one of them rather than from some. */ export function blogSitemapPaths(contentDir: string = CONTENT_DIR): string[] { const posts = listPosts(contentDir) if (posts.length === 0) return [] return ['/blog', ...posts.map(post => `/blog/${post.slug}`)] } /** * The published posts, featured first and then newest first, read by * `@stacksjs/cms/blog`: the same reader stx-native blog pages use, so the * pages, the feed and the sitemap agree on what is published. A real post * needs a title and a date, which skips docs like STRATEGY.md; `draft: true` * (set by the dashboard) holds one back from all of them. */ function listPosts(contentDir: string = CONTENT_DIR): { slug: string, fm: Record }[] { return loadPosts({ dir: contentDir }).map(post => ({ slug: post.slug, fm: post.frontmatter })) } // โ”€โ”€ HTML/XML builders (shared by the dynamic + static paths) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ async function notFoundHtml(bp: BunPress): Promise { const body = ` โ† All posts

404

Nothing here

This post doesn't exist (or it moved). Head back to all posts.

` return bp.wrapInLayout(await blogChrome() + body + await blogFooter(), await blogConfig(bp, { title: 'Not found' }), '/blog', 'page') } /** A post's YAML frontmatter and the Markdown after it. */ function splitFrontmatter(raw: string): { frontmatter: Record, body: string } { const normalized = raw.replace(/\r\n/g, '\n') const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(normalized) if (!match) return { frontmatter: {}, body: normalized } let frontmatter: unknown try { frontmatter = Bun.YAML.parse(match[1] ?? '') } catch { frontmatter = null } return { frontmatter: frontmatter && typeof frontmatter === 'object' && !Array.isArray(frontmatter) ? frontmatter as Record : {}, body: normalized.slice(match[0].length), } } function unescapeHtml(s: string): string { return s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '\'').replace(/&/g, '&') } /** * Syntax-highlight the fenced code blocks in rendered post HTML. The * highlighter escapes the code it is given, so `<` in code still shows as `<`. */ async function highlightCodeBlocks(bp: BunPress, html: string): Promise { const theme = bp.defaultConfig.markdown?.syntaxHighlightTheme || 'github-light' const blocks = /
([\s\S]*?)<\/code><\/pre>/g
  const highlighted: string[] = []
  for (const [, lang = '', code = ''] of html.matchAll(blocks))
    highlighted.push(await bp.highlightCode(unescapeHtml(code).replace(/\n$/, ''), lang, theme))
  let index = 0
  return html.replace(blocks, (_, lang: string) => `
${highlighted[index++]}
`) } /** Full HTML for a single post, or null if the markdown file doesn't exist. */ async function postHtml(bp: BunPress, slug: string, origin: string): Promise { const cfg = await site() const file = join(CONTENT_DIR, `${slug}.md`) if (!existsSync(file)) return null const raw = readFileSync(file, 'utf-8') const { frontmatter: fm, body } = splitFrontmatter(raw) // Figures, image grids sized from the files in public/, lazy loading, // click-to-zoom and embeds for bare links (see @stacksjs/cms/article). const html = renderPostHtml(await highlightCodeBlocks(bp, renderSafeMarkdown(body))) // Only real posts (title + date) are served; prose docs in content/blog/ // (e.g. STRATEGY.md) are not addressable as posts. `draft: true` 404s here as // well as hiding from the listing, so an unpublished post has no public URL. // BunPress parses YAML, so `draft` arrives as a boolean, not the string the // single-line parser behind `listPosts` sees. if (!fm.title || !fm.date || fm.draft === true || fm.draft === 'true') return null const author = fm.author || cfg.author const initial = escapeHtml(author.charAt(0).toUpperCase()) const header = ` โ† All posts

${escapeHtml(fm.title || slug)}

` const authorCard = fm.authorBio ? `` : '' const shareUrl = `${origin}/blog/${slug}` const share = ` ` const others = listPosts().filter(p => p.slug !== slug).slice(0, 3) const more = others.length ? `` : '' return bp.wrapInLayout(await blogChrome() + header + html + authorCard + share + more + await blogFooter() + articleScript(), await blogConfig(bp, fm), `/blog/${slug}`, 'page') } /** Full HTML for the blog listing. */ async function indexHtml(bp: BunPress): Promise { const cfg = await site() const posts = listPosts() // Editorial index: the lead post (featured first, otherwise newest) gets a // hero treatment, everything after it is a hairline row. No thumbnails; // type, rules, and whitespace carry the page. const [lead, ...rest] = posts const leadHtml = lead ? `

${lead.fm.featured === 'true' ? 'Featured' : ''}

${escapeHtml(lead.fm.title || lead.slug)}

${escapeHtml((lead.fm.description || '').slice(0, 200))}

Read the post
` : '' const rows = rest.map(p => `

${escapeHtml(p.fm.title || p.slug)}

${escapeHtml((p.fm.description || '').slice(0, 160))}

`).join('\n') const cards = leadHtml + (rest.length ? `
${rows}
` : '') // Empty state doubles as an email-capture moment: every Stacks app ships the // public `/api/email/subscribe` endpoint, so the form works out of the box. const emptyState = `

${escapeHtml(cfg.emptyTitle)}

${escapeHtml(cfg.emptyText)}

` const body = `

${escapeHtml(cfg.title)}

${escapeHtml(cfg.description)}

${posts.length ? `

${posts.length} ${posts.length === 1 ? 'post' : 'posts'}

` : ''}
${cards || emptyState}
` return bp.wrapInLayout(await blogChrome() + body + await blogFooter(), await blogConfig(bp, { title: cfg.title, description: cfg.description }), '/blog', 'page') } /** * RSS feed and XML sitemap. `baseUrl` is the site origin (no /blog). * * Both are generated from `listPosts()` rather than BunPress's `buildRssFeed` / * `buildSitemap`. Those scan `content/blog/*.md` themselves and have no concept * of our `draft` flag, so they published an unfinished post's title, description, * and link even though the listing hid it and its own URL 404'd. Driving every * public surface off `listPosts()` keeps one answer to "what is published". */ async function feedXml(baseUrl: string): Promise { return fallbackFeedXml(baseUrl) } async function sitemapXml(baseUrl: string): Promise { return fallbackSitemapXml(baseUrl) } // โ”€โ”€ Dynamic path (dev server onRequest) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ /** * Render a blog request via BunPress, or return null to let the caller handle * non-blog paths. Handles the listing, posts, the RSS feed, and the sitemap. */ export async function renderBlog(req: Request): Promise { if (req.method !== 'GET' && req.method !== 'HEAD') return null const url = new URL(req.url) const { pathname } = url const isFeed = pathname === '/blog/feed.xml' const isSitemap = pathname === '/blog/sitemap.xml' const isPage = pathname === '/blog' || pathname === '/blog/' || /^\/blog\/[^/.]+$/.test(pathname) if (!isFeed && !isSitemap && !isPage) return null // assets, category/tag, etc. โ†’ not ours const bp = await loadBunPress() if (!bp) return null // BunPress unavailable โ€” fall back to whatever the caller does const html = (s: string, status = 200) => new Response(s, { status, headers: { 'Content-Type': 'text/html; charset=utf-8' } }) if (isFeed) return new Response(await feedXml(url.origin), { headers: { 'Content-Type': 'application/rss+xml; charset=utf-8' } }) if (isSitemap) return new Response(await sitemapXml(url.origin), { headers: { 'Content-Type': 'application/xml; charset=utf-8' } }) if (pathname === '/blog' || pathname === '/blog/') return html(await indexHtml(bp)) const slug = pathname.replace(/^\/blog\//, '').replace(/\/$/, '') const post = await postHtml(bp, slug, url.origin) return post ? html(post) : html(await notFoundHtml(bp), 404) } /** * RSS + sitemap for an stx-native blog. When an app renders /blog with its own * stx views (so BunPress is skipped for the HTML pages), it still wants * /blog/feed.xml and /blog/sitemap.xml โ€” these are generated straight from the * `content/blog/*.md` frontmatter with NO BunPress dependency, so they work in * dev and production alike. Returns null for any non-feed path (the stx page * layer then handles /blog and /blog/). Absolute URLs use the configured * site url (blog config), never the loopback request origin. */ export async function renderBlogFeed(req: Request): Promise { if (req.method !== 'GET' && req.method !== 'HEAD') return null const { pathname } = new URL(req.url) if (pathname === '/blog/feed.xml') return new Response(await fallbackFeedXml(''), { headers: { 'Content-Type': 'application/rss+xml; charset=utf-8' } }) if (pathname === '/blog/sitemap.xml') return new Response(await fallbackSitemapXml(''), { headers: { 'Content-Type': 'application/xml; charset=utf-8' } }) return null } // โ”€โ”€ Static path (deploy-time build โ†’ dist/blog) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ /** * Build the blog to a static directory the same way /docs is built (see * config/cloud.ts). Emits clean-URL pages (`/index.html`), the listing, * the RSS feed, and the sitemap. `baseUrl` is the deployed site origin * (e.g. https://stacksjs.com) โ€” used for absolute feed/sitemap/share URLs. */ export async function buildBlog(options: { outDir: string, baseUrl?: string } = { outDir: 'dist/blog' }): Promise { const outDir = options.outDir || 'dist/blog' // `options.baseUrl` comes from APP_URL at deploy time and is not trusted: see // `usableOrigin`. An unusable value falls back to the configured site url // rather than being baked into every absolute link. const siteUrl = (await site()).url const baseUrl = usableOrigin(options.baseUrl) || usableOrigin(siteUrl) || siteUrl.replace(/\/$/, '') if (options.baseUrl && !usableOrigin(options.baseUrl)) { // eslint-disable-next-line no-console console.warn(`[blog] ignoring unusable baseUrl ${JSON.stringify(options.baseUrl)}; falling back to ${baseUrl}`) } const bp = await loadBunPress() if (!bp) throw new Error('[blog] BunPress not found; cannot build the blog.') mkdirSync(outDir, { recursive: true }) const write = (rel: string, content: string) => { const target = join(outDir, rel) mkdirSync(join(target, '..'), { recursive: true }) writeFileSync(target, content, 'utf-8') } // Listing write('index.html', await indexHtml(bp)) // Posts โ€” clean-URL directories (`/index.html`). const posts = listPosts() for (const p of posts) { const html = await postHtml(bp, p.slug, baseUrl) if (html) write(join(p.slug, 'index.html'), html) } // SEO write('feed.xml', await feedXml(baseUrl)) write('sitemap.xml', await sitemapXml(baseUrl)) // eslint-disable-next-line no-console console.log(`[blog] built ${posts.length} post(s) + listing, feed.xml, sitemap.xml โ†’ ${outDir}`) }