import { writeFileSync, mkdirSync } from 'fs';
import path from 'path';
import GithubSlugger from 'github-slugger';
import { escape } from 'pliny/utils/htmlEscaper.js';
import siteMetadata from '../data/siteMetadata.js';
import tagData from '../app/tag-data.json' assert { type: 'json' };
import { allBlogs } from '../.contentlayer/generated/index.mjs';
const generateRssItem = (config, post) => `
-
${config.siteUrl}/blog/${post.slug}
${escape(post.title)}
${config.siteUrl}/blog/${post.slug}
${post.summary && `${escape(post.summary)}`}
${new Date(post.date).toUTCString()}
${config.email} (${config.author})
${post.tags && post.tags.map((t) => `${t}`).join('')}
`;
const generateRss = (config, posts, page = 'feed.xml') => `
${escape(config.title)}
${config.siteUrl}/blog
${escape(config.description)}
${config.language}
${config.email} (${config.author})
${config.email} (${config.author})
${new Date(posts[0].date).toUTCString()}
${posts.map((post) => generateRssItem(config, post)).join('')}
`;
async function generateRSS(config, allBlogs, page = 'feed.xml') {
const publishPosts = allBlogs.filter((post) => post.draft !== true);
// RSS for blog post
if (publishPosts.length > 0) {
const rss = generateRss(config, publishPosts);
writeFileSync(`./public/${page}`, rss);
}
if (publishPosts.length > 0) {
for (const tag of Object.keys(tagData)) {
const filteredPosts = allBlogs.filter((post) =>
post.tags.map((t) => GithubSlugger.slug(t)).includes(tag),
);
const rss = generateRss(config, filteredPosts, `tags/${tag}/${page}`);
const rssPath = path.join('public', 'tags', tag);
mkdirSync(rssPath, { recursive: true });
writeFileSync(path.join(rssPath, page), rss);
}
}
}
const rss = () => {
generateRSS(siteMetadata, allBlogs);
console.log('RSS feed generated...');
};
export default rss;