|
| 1 | +import { writeFile } from 'node:fs/promises'; |
| 2 | +import { join } from 'node:path'; |
| 3 | + |
| 4 | +import { BASE_URL } from '../../constants.mjs'; |
| 5 | + |
| 6 | +/** |
| 7 | + * This generator generates a sitemap.xml file for search engine optimization |
| 8 | + * |
| 9 | + * @typedef {Array<ApiDocMetadataEntry>} Input |
| 10 | + * |
| 11 | + * @type {GeneratorMetadata<Input, string>} |
| 12 | + */ |
| 13 | +export default { |
| 14 | + name: 'sitemap', |
| 15 | + |
| 16 | + version: '1.0.0', |
| 17 | + |
| 18 | + description: 'Generates a sitemap.xml file for search engine optimization', |
| 19 | + |
| 20 | + dependsOn: 'metadata', |
| 21 | + |
| 22 | + /** |
| 23 | + * Generates a sitemap.xml file |
| 24 | + * |
| 25 | + * @param {Input} entries |
| 26 | + * @param {Partial<GeneratorOptions>} options |
| 27 | + * @returns {Promise<string>} |
| 28 | + */ |
| 29 | + async generate(entries, { output }) { |
| 30 | + const apiPages = entries |
| 31 | + .filter(entry => entry.heading.depth === 1) |
| 32 | + .map(entry => { |
| 33 | + const path = entry.api_doc_source.replace(/^doc\//, '/docs/latest/'); |
| 34 | + const url = new URL(path, BASE_URL).href; |
| 35 | + |
| 36 | + return { |
| 37 | + loc: url, |
| 38 | + lastmod: new Date().toISOString().split('T')[0], |
| 39 | + changefreq: 'weekly', |
| 40 | + priority: '0.8', |
| 41 | + }; |
| 42 | + }); |
| 43 | + |
| 44 | + const mainPages = [ |
| 45 | + { |
| 46 | + loc: new URL('/docs/latest/api/', BASE_URL).href, |
| 47 | + lastmod: new Date().toISOString().split('T')[0], |
| 48 | + changefreq: 'daily', |
| 49 | + priority: '1.0', |
| 50 | + }, |
| 51 | + ]; |
| 52 | + |
| 53 | + const allPages = [...mainPages, ...apiPages]; |
| 54 | + |
| 55 | + const sitemap = `<?xml version="1.0" encoding="UTF-8"?> |
| 56 | +<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> |
| 57 | +${allPages |
| 58 | + .map( |
| 59 | + page => ` <url> |
| 60 | + <loc>${page.loc}</loc> |
| 61 | + <lastmod>${page.lastmod}</lastmod> |
| 62 | + <changefreq>${page.changefreq}</changefreq> |
| 63 | + <priority>${page.priority}</priority> |
| 64 | + </url>` |
| 65 | + ) |
| 66 | + .join('\n')} |
| 67 | +</urlset>`; |
| 68 | + |
| 69 | + if (output) { |
| 70 | + await writeFile(join(output, 'sitemap.xml'), sitemap, 'utf-8'); |
| 71 | + } |
| 72 | + |
| 73 | + return sitemap; |
| 74 | + }, |
| 75 | +}; |
0 commit comments