-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
index.ts
188 lines (160 loc) · 5.2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import type { AstroConfig, AstroIntegration } from 'astro';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { EnumChangefreq, LinkItem as LinkItemBase, SitemapItemLoose } from 'sitemap';
import { simpleSitemapAndIndex } from 'sitemap';
import { ZodError } from 'zod';
import { generateSitemap } from './generate-sitemap.js';
import { validateOptions } from './validate-options.js';
export { EnumChangefreq as ChangeFreqEnum } from 'sitemap';
export type ChangeFreq = `${EnumChangefreq}`;
export type SitemapItem = Pick<
SitemapItemLoose,
'url' | 'lastmod' | 'changefreq' | 'priority' | 'links'
>;
export type LinkItem = LinkItemBase;
export type SitemapOptions =
| {
filter?(page: string): boolean;
customPages?: string[];
i18n?: {
defaultLocale: string;
locales: Record<string, string>;
};
// number of entries per sitemap file
entryLimit?: number;
// sitemap specific
changefreq?: ChangeFreq;
lastmod?: Date;
priority?: number;
// called for each sitemap item just before to save them on disk, sync or async
serialize?(item: SitemapItem): SitemapItem | Promise<SitemapItem | undefined> | undefined;
}
| undefined;
function formatConfigErrorMessage(err: ZodError) {
const errorList = err.issues.map((issue) => ` ${issue.path.join('.')} ${issue.message + '.'}`);
return errorList.join('\n');
}
const PKG_NAME = '@astrojs/sitemap';
const OUTFILE = 'sitemap-index.xml';
const STATUS_CODE_PAGES = new Set(['404', '500']);
function isStatusCodePage(pathname: string): boolean {
if (pathname.endsWith('/')) {
pathname = pathname.slice(0, -1);
}
const end = pathname.split('/').pop() ?? '';
return STATUS_CODE_PAGES.has(end);
}
const createPlugin = (options?: SitemapOptions): AstroIntegration => {
let config: AstroConfig;
return {
name: PKG_NAME,
hooks: {
'astro:config:done': async ({ config: cfg }) => {
config = cfg;
},
'astro:build:done': async ({ dir, routes, pages, logger }) => {
try {
if (!config.site) {
logger.warn(
'The Sitemap integration requires the `site` astro.config option. Skipping.'
);
return;
}
const opts = validateOptions(config.site, options);
const { filter, customPages, serialize, entryLimit } = opts;
let finalSiteUrl: URL;
if (config.site) {
finalSiteUrl = new URL(config.base, config.site);
} else {
console.warn(
'The Sitemap integration requires the `site` astro.config option. Skipping.'
);
return;
}
let pageUrls = pages
.filter((p) => !isStatusCodePage(p.pathname))
.map((p) => {
if (p.pathname !== '' && !finalSiteUrl.pathname.endsWith('/'))
finalSiteUrl.pathname += '/';
const fullPath = finalSiteUrl.pathname + p.pathname;
return new URL(fullPath, finalSiteUrl).href;
});
let routeUrls = routes.reduce<string[]>((urls, r) => {
// Only expose pages, not endpoints or redirects
if (r.type !== 'page') return urls;
/**
* Dynamic URLs have entries with `undefined` pathnames
*/
if (r.pathname) {
if (isStatusCodePage(r.pathname ?? r.route)) return urls;
/**
* remove the initial slash from relative pathname
* because `finalSiteUrl` always has trailing slash
*/
const fullPath = finalSiteUrl.pathname + r.generate(r.pathname).substring(1);
let newUrl = new URL(fullPath, finalSiteUrl).href;
if (config.trailingSlash === 'never') {
urls.push(newUrl);
} else if (config.build.format === 'directory' && !newUrl.endsWith('/')) {
urls.push(newUrl + '/');
} else {
urls.push(newUrl);
}
}
return urls;
}, []);
pageUrls = Array.from(new Set([...pageUrls, ...routeUrls, ...(customPages ?? [])]));
try {
if (filter) {
pageUrls = pageUrls.filter(filter);
}
} catch (err) {
logger.error(`Error filtering pages\n${(err as any).toString()}`);
return;
}
if (pageUrls.length === 0) {
logger.warn(`No pages found!\n\`${OUTFILE}\` not created.`);
return;
}
let urlData = generateSitemap(pageUrls, finalSiteUrl.href, opts);
if (serialize) {
try {
const serializedUrls: SitemapItem[] = [];
for (const item of urlData) {
const serialized = await Promise.resolve(serialize(item));
if (serialized) {
serializedUrls.push(serialized);
}
}
if (serializedUrls.length === 0) {
logger.warn('No pages found!');
return;
}
urlData = serializedUrls;
} catch (err) {
logger.error(`Error serializing pages\n${(err as any).toString()}`);
return;
}
}
const destDir = fileURLToPath(dir);
await simpleSitemapAndIndex({
hostname: finalSiteUrl.href,
destinationDir: destDir,
sourceData: urlData,
limit: entryLimit,
gzip: false,
});
logger.info(`\`${OUTFILE}\` created at \`${path.relative(process.cwd(), destDir)}\``);
} catch (err) {
if (err instanceof ZodError) {
logger.warn(formatConfigErrorMessage(err));
} else {
throw err;
}
}
},
},
};
};
export default createPlugin;