Open History to see the last commit
1import { writeFileSync } from 'node:fs'
2import path from 'node:path'
3import { create } from 'xmlbuilder2'
4import { createLogger } from './utils'
5import type { TanStackStartOutputConfig } from './schema'
6import type { XMLBuilder } from 'xmlbuilder2/lib/interfaces'
7β
8export type SitemapUrl = {
9 loc: string
10 lastmod: string
11 priority?: number
12 changefreq?:
13 | 'always'
14 | 'hourly'
15 | 'daily'
16 | 'weekly'
17 | 'monthly'
18 | 'yearly'
19 | 'never'
20 alternateRefs?: Array<{
21 href: string
22 hreflang?: string
23 }>
24 images?: Array<{
25 loc: string
26 title?: string
27 caption?: string
28 }>
29 news?: {
30 publication: {
31 name: string
32 language: string
33 }
34 publicationDate: string | Date
35 title: string
36 }
37}
38β
39export type SitemapData = {
40 urls: Array<SitemapUrl>
41}
42β
43function buildSitemapJson(
44 pages: TanStackStartOutputConfig['pages'],
45 host: string,
46): SitemapData {
47 const slash = checkSlash(host)
48β
49 const urls: Array<SitemapUrl> = pages
50 .filter((page) => {
51 return page.sitemap?.exclude !== true
52 })
53 .map((page) => ({
54 loc: `${host}${slash}${page.path.replace(/^\/+/g, '')}`,
55 lastmod: page.sitemap?.lastmod
56 ? new Date(page.sitemap.lastmod).toISOString().split('T')[0]!
57 : new Date().toISOString().split('T')[0]!,
58 priority: page.sitemap?.priority,
59 changefreq: page.sitemap?.changefreq,
60 alternateRefs: page.sitemap?.alternateRefs,
61 images: page.sitemap?.images,
62 news: page.sitemap?.news,
63 }))
64β
65 return { urls }
66}
67β
68function jsonToXml(sitemapData: SitemapData): string {
69 const sitemap = createXml('urlset')
70β
71 for (const item of sitemapData.urls) {
72 const page = sitemap.ele('url')
73 page.ele('loc').txt(item.loc)
74 page.ele('lastmod').txt(item.lastmod)
75β
76 if (item.priority !== undefined) {
77 page.ele('priority').txt(item.priority.toString())
78 }
79 if (item.changefreq) {
80 page.ele('changefreq').txt(item.changefreq)
81 }
82β
83 // Add alternate references
84 if (item.alternateRefs?.length) {
85 for (const ref of item.alternateRefs) {
86 const alternateRef = page.ele('xhtml:link')
87 alternateRef.att('rel', 'alternate')
88 alternateRef.att('href', ref.href)
89 if (ref.hreflang) {
90 alternateRef.att('hreflang', ref.hreflang)
91 }
92 }
93 }
94β
95 // Add images
96 if (item.images?.length) {
97 for (const image of item.images) {
98 const imageElement = page.ele('image:image')
99 imageElement.ele('image:loc').txt(image.loc)
100 if (image.title) {
101 imageElement.ele('image:title').txt(image.title)
102 }
103 if (image.caption) {
104 imageElement.ele('image:caption').txt(image.caption)
105 }
106 }
107 }
108β
109 // Add news
110 if (item.news) {
111 const newsElement = page.ele('news:news')
112 const publication = newsElement.ele('news:publication')
113 publication.ele('news:name').txt(item.news.publication.name)
114 publication.ele('news:language').txt(item.news.publication.language)
115 newsElement
116 .ele('news:publication_date')
117 .txt(new Date(item.news.publicationDate).toISOString().split('T')[0]!)
118 newsElement.ele('news:title').txt(item.news.title)
119 }
120 }
121β
122 return sitemap.end({ prettyPrint: true })
123}
124β
125export function buildSitemap({
126 startConfig,
127 publicDir,
128}: {
129 startConfig: TanStackStartOutputConfig
130 publicDir: string
131}) {
132 const logger = createLogger('sitemap')
133β
134 let sitemapOptions = startConfig.sitemap
135β
136 if (!sitemapOptions && startConfig.pages.length) {
137 sitemapOptions = { enabled: true, outputPath: 'sitemap.xml' }
138 }
139β
140 if (!sitemapOptions?.enabled) {
141 throw new Error('Sitemap is not enabled')
142 }
143β
144 const { host, outputPath } = sitemapOptions
145β
146 if (!host) {
147 if (!startConfig.sitemap) {
148 logger.info(
149 'Hint: Pages found, but no sitemap host has been set. To enable sitemap generation, set the `sitemap.host` option.',
150 )
151 return
152 }
153 throw new Error(
154 'Sitemap host is not set and required to build the sitemap.',
155 )
156 }
157β
158 if (!outputPath) {
159 throw new Error('Sitemap output path is not set')
160 }
161β
162 const { pages } = startConfig
163β
164 if (!pages.length) {
165 logger.info('No pages were found to build the sitemap. Skipping...')
166 return
167 }
168β
169 logger.info('Building Sitemap...')
170β
171 // Build the sitemap data
172 const sitemapData = buildSitemapJson(pages, host)
173β
174 // Generate output paths
175 const xmlOutputPath = path.join(publicDir, outputPath)
176 const pagesOutputPath = path.join(publicDir, 'pages.json')
177β
178 try {
179 // Write XML sitemap
180 logger.info(`Writing sitemap XML at ${xmlOutputPath}`)
181 writeFileSync(xmlOutputPath, jsonToXml(sitemapData))
182β
183 // Write pages data for runtime use
184 logger.info(`Writing pages data at ${pagesOutputPath}`)
185 writeFileSync(
186 pagesOutputPath,
187 JSON.stringify(
188 {
189 pages,
190 host,
191 lastBuilt: new Date().toISOString(),
192 },
193 null,
194 2,
195 ),
196 )
197 } catch (e) {
198 logger.error(`Unable to write sitemap files`, e)
199 }
200}
201β
202function createXml(elementName: 'urlset' | 'sitemapindex'): XMLBuilder {
203 return create({ version: '1.0', encoding: 'UTF-8' })
204 .ele(elementName, {
205 xmlns: 'https://www.sitemaps.org/schemas/sitemap/0.9',
206 })
207 .com(`This file was automatically generated by TanStack Start.`)
208}
209β
210function checkSlash(host: string): string {
211 const finalChar = host.slice(-1)
212 return finalChar === '/' ? '' : '/'
213}