import { promises as fs } from 'fs'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; import xml2js from 'xml2js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const LANGUAGES = ['en', 'zh-Hans', 'zh-Hant']; const BASE_URL = 'mirror.starset.fans'; interface Update { id: string; date: string; } interface UpdateIndex { updates: Update[]; } async function getYearlyIndices(lang: string): Promise { const indexDir = join(__dirname, '..', 'data', lang, 'updates', 'index'); try { const files = await fs.readdir(indexDir); return files.filter(file => file.match(/^\d{4}\.json$/)); } catch (err) { console.error(`Error reading index directory for ${lang}:`, err); return []; } } async function generateUpdateUrls(lang: string) { const yearFiles = await getYearlyIndices(lang); const urls = []; for (const yearFile of yearFiles) { try { const content = await fs.readFile( join(__dirname, '..', 'data', lang, 'updates', 'index', yearFile), 'utf-8' ); const data = JSON.parse(content) as UpdateIndex; if (data.updates) { for (const update of data.updates) { urls.push({ loc: `https://${BASE_URL}/updates/${update.id}`, lastmod: update.date, changefreq: 'monthly', priority: '0.7' }); } } } catch (err) { console.error(`Error processing ${yearFile} for ${lang}:`, err); } } return urls; } async function mergeSitemaps() { const parser = new xml2js.Parser(); const mainSitemapPath = join(__dirname, '..', 'dist', 'sitemap.xml'); try { const mainSitemapContent = await fs.readFile(mainSitemapPath, 'utf-8'); const mainSitemap = await parser.parseStringPromise(mainSitemapContent); // Filter out existing update URLs while maintaining order const existingUrls = mainSitemap.urlset.url.filter((url: any) => !url.loc[0].includes('/updates/')); mainSitemap.urlset.url = existingUrls; // Add language-specific update URLs at the end for (const lang of LANGUAGES) { const updateUrls = await generateUpdateUrls(lang); mainSitemap.urlset.url.push(...updateUrls); } const builder = new xml2js.Builder(); const newSitemap = builder.buildObject(mainSitemap); await fs.writeFile(mainSitemapPath, newSitemap); console.log('Successfully updated sitemap.xml in dist directory'); } catch (err) { console.error('Error merging sitemaps:', err); if (err instanceof Error && 'code' in err && err.code === 'ENOENT') { console.error('Make sure the dist directory exists and contains sitemap.xml'); } process.exit(1); } } // Run the script mergeSitemaps();