Something went wrong. Try again.
build smart knowledge-sharing systems that combine the best of human expertise with smart technology
Something went wrong. Try again.
2.6 kB · 104 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import fs from "fs/promises";import path from "path";
import { russAuthor } from "@/content/blog/authors";import type { Post } from "@/content/blog/posts";import { tagsToCategories } from "@/lib/atproto-feed";
interface Frontmatter { title?: string; description?: string; publishDate?: string; ogImage?: string; tags?: string[]; atUri?: string;}
function unquote(value: string): string { const trimmed = value.trim(); if ( (trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'")) ) { return trimmed.slice(1, -1); } return trimmed;}
function parseFrontmatter( raw: string): { data: Frontmatter; body: string } | null { const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/); if (!match) return null;
const [, yaml, body] = match; const data: Frontmatter = {}; const lines = yaml.split(/\r?\n/);
let currentListKey: keyof Frontmatter | null = null;
for (const line of lines) { if (!line.trim()) continue;
const listItem = line.match(/^\s+-\s+(.*)$/); if (listItem && currentListKey) { const arr = (data[currentListKey] ?? []) as string[]; arr.push(unquote(listItem[1])); (data[currentListKey] as unknown) = arr; continue; }
const kv = line.match(/^([a-zA-Z][a-zA-Z0-9_]*):\s*(.*)$/); if (!kv) { currentListKey = null; continue; }
const [, key, rawValue] = kv; const value = rawValue.trim();
if (value === "") { currentListKey = key as keyof Frontmatter; if (!(key in data)) (data as Record<string, unknown>)[key] = []; continue; }
currentListKey = null; (data as Record<string, string>)[key] = unquote(value); }
return { data, body };}
export async function loadLocalDraft(slug: string): Promise<Post | undefined> { if (process.env.NODE_ENV === "production") return undefined;
const filePath = path.join(process.cwd(), "src/content/blog", `${slug}.md`); let raw: string; try { raw = await fs.readFile(filePath, "utf-8"); } catch { return undefined; }
const parsed = parseFrontmatter(raw); if (!parsed) return undefined;
const { data, body } = parsed; const { title } = data; if (!title) return undefined;
const datetime = data.publishDate ? new Date(data.publishDate) : new Date();
return { id: `draft-${slug}`, title, href: `/blog/${slug}`, description: data.description ?? "", datetime, categories: tagsToCategories(data.tags ?? []), author: russAuthor, body, atUri: data.atUri || undefined, };}