Debian Codegraph @

www/src/lib/feed.js

raw symbols SCIP
1 /**
2 * lib/feed.js
3 *
4 * Builds a unified Feed instance (essays + interviews) used by both
5 * /atom.xml and /rss.xml endpoints. One source of truth, two output
6 * formats — RSS 2.0 and Atom 1.0 stay in lockstep.
7 *
8 * Content pipeline:
9 * raw .md/.mdx body
10 * → remark-parse + remark-mdx (parse Markdown + JSX nodes)
11 * → strip MDX import/export/JSX nodes (feeds can't run JSX)
12 * → remark-rehype (MDAST → HAST)
13 * → absolutize relative href/src (feed readers need absolute URLs)
14 * → rehype-stringify (HAST → HTML)
15 *
16 * The old htmx.org Zola site emitted /atom.xml with full essay HTML; we
17 * preserve that subscriber experience.
18 */
19
20 import { Feed } from 'feed';
21 import rehypeStringify from 'rehype-stringify';
22 import remarkMdx from 'remark-mdx';
23 import remarkParse from 'remark-parse';
24 import remarkRehype from 'remark-rehype';
25 import { unified } from 'unified';
26
27 import { fileAsMarkdown, getFolder } from './content';
28
29 /** Collections surfaced in the feed, ordered by appearance only — final sort is by date. */
30 const FEED_COLLECTIONS = ['essays', 'interviews'];
31
32 const FEED_TITLE = '</> htmx - high power tools for html';
33 const FEED_DESCRIPTION = 'Essays and interviews from the htmx project.';
34 const FEED_LANGUAGE = 'en';
35
36 /**
37 * remark plugin: drop MDX-specific AST nodes that don't belong in feeds
38 * (ES imports/exports, JSX elements). Feeds are static HTML; MDX components
39 * can't render in a feed reader.
40 */
41 function remarkStripMdxNodes() {
42 /** @param {any} tree */
43 return (tree) => {
44 if (!Array.isArray(tree.children)) return;
45 const drop = new Set(['mdxjsEsm', 'mdxJsxFlowElement', 'mdxJsxTextElement', 'mdxFlowExpression', 'mdxTextExpression']);
46 /** @param {any} node */
47 const walk = (node) => {
48 if (Array.isArray(node.children)) {
49 node.children = node.children.filter(/** @param {any} c */ (c) => !drop.has(c.type));
50 node.children.forEach(walk);
51 }
52 };
53 walk(tree);
54 };
55 }
56
57 /**
58 * rehype plugin: rewrite root-relative `href` / `src` attributes to absolute
59 * URLs anchored at the site origin. Feed readers don't know our domain, so
60 * `/img/foo.png` would 404 inside a reader.
61 *
62 * @param {string} origin - Site origin, no trailing slash.
63 */
64 function rehypeAbsoluteUrls(origin) {
65 // Rewrite root-relative URLs inside raw HTML strings (preserved by
66 // `allowDangerousHtml`). Handles single- and double-quoted attributes.
67 const rawRe = /\b(href|src)=("|')(\/[^/][^"']*?)\2/g;
68 /** @param {any} tree */
69 return (tree) => {
70 /** @param {any} node */
71 const walk = (node) => {
72 if (node.type === 'element' && node.properties) {
73 for (const attr of ['href', 'src']) {
74 const v = node.properties[attr];
75 if (typeof v === 'string' && v.startsWith('/') && !v.startsWith('//')) {
76 node.properties[attr] = origin + v;
77 }
78 }
79 } else if (node.type === 'raw' && typeof node.value === 'string') {
80 node.value = node.value.replace(rawRe, (_m, attr, q, path) => `${attr}=${q}${origin}${path}${q}`);
81 }
82 if (Array.isArray(node.children)) node.children.forEach(walk);
83 };
84 walk(tree);
85 };
86 }
87
88 /**
89 * Convert a Markdown or MDX body to feed-ready HTML. Only `.mdx` sources go
90 * through `remark-mdx`; plain `.md` content can contain raw HTML fragments
91 * that the MDX parser rejects (e.g. unclosed tags inside code prose).
92 *
93 * @param {string} markdown
94 * @param {string} origin
95 * @param {boolean} isMdx
96 * @returns {Promise<string>}
97 */
98 async function markdownToHtml(markdown, origin, isMdx) {
99 let processor = unified().use(remarkParse);
100 if (isMdx) processor = processor.use(remarkMdx).use(remarkStripMdxNodes);
101 processor = processor
102 .use(remarkRehype, { allowDangerousHtml: true })
103 .use(() => rehypeAbsoluteUrls(origin))
104 .use(rehypeStringify, { allowDangerousHtml: true });
105 const result = await processor.process(markdown);
106 return String(result);
107 }
108
109 /** `fileAsMarkdown` prepends `# <title>`; feeds carry the title separately so we strip it. */
110 function stripTitlePrefix(md) {
111 return md.replace(/^# [^\n]*\n+/, '');
112 }
113
114 /**
115 * Build a `feed` package Feed instance covering all feed-eligible content.
116 * Caller invokes `.atom1()` or `.rss2()` to serialize.
117 *
118 * @param {URL | undefined} site - Astro context.site (origin trusted source).
119 * @returns {Promise<Feed>}
120 */
121 export async function buildFeed(site) {
122 const origin = (site?.href ?? 'https://htmx.org/').replace(/\/$/, '');
123
124 const feed = new Feed({
125 title: FEED_TITLE,
126 description: FEED_DESCRIPTION,
127 id: `${origin}/`,
128 link: `${origin}/`,
129 language: FEED_LANGUAGE,
130 feedLinks: {
131 atom: `${origin}/atom.xml`,
132 rss: `${origin}/rss.xml`,
133 },
134 copyright: '',
135 });
136
137 /** @type {Array<{ file: any, published: Date, updated: Date }>} */
138 const entries = [];
139 for (const collection of FEED_COLLECTIONS) {
140 const folder = await getFolder(collection);
141 for (const file of folder.allFiles) {
142 const fm = file.frontmatter;
143 if (!fm.created) continue;
144 entries.push({
145 file,
146 published: new Date(fm.created),
147 updated: fm.modified ? new Date(fm.modified) : new Date(fm.created),
148 });
149 }
150 }
151 entries.sort((a, b) => b.published.getTime() - a.published.getTime());
152
153 for (const { file, published, updated } of entries) {
154 const body = stripTitlePrefix(fileAsMarkdown(file.path));
155 const isMdx = file.path.endsWith('.mdx');
156 const content = await markdownToHtml(body, origin, isMdx);
157 const link = `${origin}${file.url}`;
158
159 feed.addItem({
160 title: file.frontmatter.title,
161 id: link,
162 link,
163 description: file.frontmatter.description ?? '',
164 content,
165 date: updated,
166 published,
167 author: (file.frontmatter.authors ?? []).map(/** @param {string} name */ (name) => ({ name })),
168 category: (file.frontmatter.tags ?? []).map(/** @param {string} name */ (name) => ({ name })),
169 });
170 }
171
172 return feed;
173 }