|
| 1 | +import { getSiteUrl } from '$lib/utils/site'; |
| 2 | +import type { RequestHandler } from './$types'; |
| 3 | + |
| 4 | +type SitemapEntry = { |
| 5 | + path: string; |
| 6 | + changefreq?: string; |
| 7 | + priority?: string; |
| 8 | + lastmod?: string; |
| 9 | +}; |
| 10 | + |
| 11 | +const SITE_URL = getSiteUrl(); |
| 12 | +const CACHE_CONTROL_HEADER = 'max-age=0, s-maxage=3600'; |
| 13 | +const DEFAULT_CHANGE_FREQUENCY = 'daily'; |
| 14 | +const DEFAULT_PRIORITY = '0.5'; |
| 15 | + |
| 16 | +const PAGE_ENTRIES: Record<string, Omit<SitemapEntry, 'path'>> = { |
| 17 | + '/': { |
| 18 | + changefreq: 'daily', |
| 19 | + priority: '1.0' |
| 20 | + } |
| 21 | +}; |
| 22 | + |
| 23 | +const generatedAt = new Date().toISOString(); |
| 24 | +const sitemapXml = createSitemap(makeEntries(PAGE_ENTRIES, generatedAt)); |
| 25 | + |
| 26 | +export const prerender = true; |
| 27 | + |
| 28 | +export const GET: RequestHandler = async () => { |
| 29 | + return new Response(sitemapXml, { |
| 30 | + headers: { |
| 31 | + 'Content-Type': 'application/xml', |
| 32 | + 'Cache-Control': CACHE_CONTROL_HEADER |
| 33 | + } |
| 34 | + }); |
| 35 | +}; |
| 36 | + |
| 37 | +function makeEntries( |
| 38 | + pages: Record<string, Omit<SitemapEntry, 'path'>>, |
| 39 | + generatedAtIso: string |
| 40 | +): SitemapEntry[] { |
| 41 | + return Object.entries(pages) |
| 42 | + .map(([path, config]) => ({ |
| 43 | + path, |
| 44 | + changefreq: config.changefreq ?? DEFAULT_CHANGE_FREQUENCY, |
| 45 | + priority: config.priority ?? DEFAULT_PRIORITY, |
| 46 | + lastmod: config.lastmod ?? generatedAtIso |
| 47 | + })) |
| 48 | + .sort((a, b) => { |
| 49 | + if (a.path === '/') return -1; |
| 50 | + if (b.path === '/') return 1; |
| 51 | + return a.path.localeCompare(b.path); |
| 52 | + }); |
| 53 | +} |
| 54 | + |
| 55 | +function createSitemap(entries: SitemapEntry[]): string { |
| 56 | + const urls = entries.map(formatUrlEntry).join('\n'); |
| 57 | + |
| 58 | + return `<?xml version="1.0" encoding="UTF-8" ?>\n<urlset\n xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"\n xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"\n xmlns:xhtml="https://www.w3.org/1999/xhtml"\n xmlns:mobile="https://www.google.com/schemas/sitemap-mobile/1.0"\n xmlns:image="https://www.google.com/schemas/sitemap-image/1.1"\n xmlns:video="https://www.google.com/schemas/sitemap-video/1.1"\n>\n${urls}\n</urlset>`; |
| 59 | +} |
| 60 | + |
| 61 | +function formatUrlEntry({ path, changefreq, priority, lastmod }: SitemapEntry): string { |
| 62 | + const loc = path === '/' ? SITE_URL : `${SITE_URL}${path}`; |
| 63 | + |
| 64 | + return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>${changefreq}</changefreq>\n <priority>${priority}</priority>\n </url>`; |
| 65 | +} |
| 66 | + |
0 commit comments