import { send } from 'h3' import { sitemapRoutes } from '~/data/sitemap-routes' import { getSiteUrlFromEvent } from '~/server/utils/site-url' import { toLocalePath } from '~/utils/locale-path' import { toAbsoluteUrl } from '~/utils/seo' import type { SiteLocale } from '~/types/locale' function escapeXml(value: string): string { return value .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('"', '"') .replaceAll("'", ''') } function buildAlternateLinks(siteUrl: string, basePath: string): string { const enUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'en'))) const zhUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'zh'))) return [ ` `, ` `, ` ` ].join('\n') } export default defineEventHandler((event) => { const config = useRuntimeConfig() const siteUrl = getSiteUrlFromEvent(event, String(config.public.siteUrl)) const lastmod = new Date().toISOString().slice(0, 10) const locales: SiteLocale[] = ['en', 'zh'] const urls = sitemapRoutes .flatMap((route) => locales.map((locale) => { const loc = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(route.path, locale))) return [ ' ', ` ${loc}`, buildAlternateLinks(siteUrl, route.path), ` ${lastmod}`, ` ${route.changefreq}`, ` ${route.priority.toFixed(1)}`, ' ' ].join('\n') }) ) .join('\n') const body = [ '', '', '', urls, '', '' ].join('\n') setResponseHeaders(event, { 'content-type': 'application/xml; charset=utf-8', 'x-content-type-options': 'nosniff', 'cache-control': 'public, max-age=3600' }) return send(event, body) })