@nuxtjs/sitemap 7.4.3 → 7.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/package.json +25 -23
  2. package/dist/client/200.html +0 -13
  3. package/dist/client/404.html +0 -13
  4. package/dist/client/_nuxt/CVO1_9PV.js +0 -1
  5. package/dist/client/_nuxt/CnQ734Pf.js +0 -172
  6. package/dist/client/_nuxt/Cp-IABpG.js +0 -1
  7. package/dist/client/_nuxt/D0r3Knsf.js +0 -1
  8. package/dist/client/_nuxt/DrLDkm_a.js +0 -1
  9. package/dist/client/_nuxt/DyQhad1I.js +0 -1
  10. package/dist/client/_nuxt/builds/latest.json +0 -1
  11. package/dist/client/_nuxt/builds/meta/bdc97cc6-8746-4e08-aaf6-c2b5c273d5b5.json +0 -1
  12. package/dist/client/_nuxt/entry.BzbtAPc0.css +0 -1
  13. package/dist/client/_nuxt/error-404.rTOVQ3Ki.css +0 -1
  14. package/dist/client/_nuxt/error-500.BtbPDLpj.css +0 -1
  15. package/dist/client/index.html +0 -13
  16. package/dist/content.d.mts +0 -232
  17. package/dist/content.d.ts +0 -232
  18. package/dist/content.mjs +0 -45
  19. package/dist/module.d.mts +0 -10
  20. package/dist/module.d.ts +0 -10
  21. package/dist/module.json +0 -13
  22. package/dist/module.mjs +0 -1213
  23. package/dist/runtime/server/composables/asSitemapUrl.d.ts +0 -2
  24. package/dist/runtime/server/composables/asSitemapUrl.js +0 -3
  25. package/dist/runtime/server/composables/defineSitemapEventHandler.d.ts +0 -4
  26. package/dist/runtime/server/composables/defineSitemapEventHandler.js +0 -2
  27. package/dist/runtime/server/content-compat.d.ts +0 -1
  28. package/dist/runtime/server/content-compat.js +0 -2
  29. package/dist/runtime/server/kit.d.ts +0 -3
  30. package/dist/runtime/server/kit.js +0 -25
  31. package/dist/runtime/server/plugins/compression.d.ts +0 -2
  32. package/dist/runtime/server/plugins/compression.js +0 -8
  33. package/dist/runtime/server/plugins/nuxt-content-v2.d.ts +0 -2
  34. package/dist/runtime/server/plugins/nuxt-content-v2.js +0 -39
  35. package/dist/runtime/server/plugins/warm-up.d.ts +0 -2
  36. package/dist/runtime/server/plugins/warm-up.js +0 -39
  37. package/dist/runtime/server/robots-polyfill/getPathRobotConfig.d.ts +0 -5
  38. package/dist/runtime/server/robots-polyfill/getPathRobotConfig.js +0 -3
  39. package/dist/runtime/server/routes/__sitemap__/debug.d.ts +0 -40
  40. package/dist/runtime/server/routes/__sitemap__/debug.js +0 -29
  41. package/dist/runtime/server/routes/__sitemap__/nuxt-content-urls-v2.d.ts +0 -2
  42. package/dist/runtime/server/routes/__sitemap__/nuxt-content-urls-v2.js +0 -6
  43. package/dist/runtime/server/routes/__sitemap__/nuxt-content-urls-v3.d.ts +0 -2
  44. package/dist/runtime/server/routes/__sitemap__/nuxt-content-urls-v3.js +0 -24
  45. package/dist/runtime/server/routes/sitemap/[sitemap].xml.d.ts +0 -2
  46. package/dist/runtime/server/routes/sitemap/[sitemap].xml.js +0 -50
  47. package/dist/runtime/server/routes/sitemap.xml.d.ts +0 -2
  48. package/dist/runtime/server/routes/sitemap.xml.js +0 -13
  49. package/dist/runtime/server/routes/sitemap.xsl.d.ts +0 -2
  50. package/dist/runtime/server/routes/sitemap.xsl.js +0 -255
  51. package/dist/runtime/server/routes/sitemap_index.xml.d.ts +0 -2
  52. package/dist/runtime/server/routes/sitemap_index.xml.js +0 -42
  53. package/dist/runtime/server/sitemap/builder/sitemap-index.d.ts +0 -13
  54. package/dist/runtime/server/sitemap/builder/sitemap-index.js +0 -197
  55. package/dist/runtime/server/sitemap/builder/sitemap.d.ts +0 -16
  56. package/dist/runtime/server/sitemap/builder/sitemap.js +0 -241
  57. package/dist/runtime/server/sitemap/builder/xml.d.ts +0 -6
  58. package/dist/runtime/server/sitemap/builder/xml.js +0 -197
  59. package/dist/runtime/server/sitemap/nitro.d.ts +0 -4
  60. package/dist/runtime/server/sitemap/nitro.js +0 -144
  61. package/dist/runtime/server/sitemap/urlset/normalise.d.ts +0 -6
  62. package/dist/runtime/server/sitemap/urlset/normalise.js +0 -137
  63. package/dist/runtime/server/sitemap/urlset/sort.d.ts +0 -2
  64. package/dist/runtime/server/sitemap/urlset/sort.js +0 -13
  65. package/dist/runtime/server/sitemap/urlset/sources.d.ts +0 -6
  66. package/dist/runtime/server/sitemap/urlset/sources.js +0 -143
  67. package/dist/runtime/server/sitemap/utils/chunk.d.ts +0 -10
  68. package/dist/runtime/server/sitemap/utils/chunk.js +0 -66
  69. package/dist/runtime/server/tsconfig.json +0 -3
  70. package/dist/runtime/server/utils.d.ts +0 -5
  71. package/dist/runtime/server/utils.js +0 -16
  72. package/dist/runtime/types.d.ts +0 -458
  73. package/dist/runtime/types.js +0 -0
  74. package/dist/runtime/utils-pure.d.ts +0 -14
  75. package/dist/runtime/utils-pure.js +0 -85
  76. package/dist/shared/sitemap.DR3_6qqU.mjs +0 -212
  77. package/dist/types.d.mts +0 -5
  78. package/dist/utils.d.mts +0 -28
  79. package/dist/utils.d.ts +0 -28
  80. package/dist/utils.mjs +0 -368
package/dist/module.mjs DELETED
@@ -1,1213 +0,0 @@
1
- import { useNuxt, loadNuxtModuleInstance, createResolver, addTemplate, extendPages, tryUseNuxt, defineNuxtModule, useLogger, hasNuxtModule, getNuxtModuleVersion, hasNuxtModuleCompatibility, addServerImports, addServerPlugin, resolveModule, addServerHandler, addPrerenderRoutes } from '@nuxt/kit';
2
- import { withHttps, withBase, joinURL, withTrailingSlash, withoutLeadingSlash, withLeadingSlash, withoutTrailingSlash } from 'ufo';
3
- import { withSiteUrl, installNuxtSiteConfig } from 'nuxt-site-config/kit';
4
- import { defu } from 'defu';
5
- import { readPackageJSON } from 'pkg-types';
6
- import { extname, relative, dirname } from 'pathe';
7
- import { statSync, existsSync } from 'node:fs';
8
- import { createPathFilter, splitForLocales, mergeOnKey } from '../dist/runtime/utils-pure.js';
9
- import { provider, env } from 'std-env';
10
- import { mkdir, writeFile } from 'node:fs/promises';
11
- import { join } from 'node:path';
12
- import chalk from 'chalk';
13
- import { p as parseHtmlExtractSitemapMeta } from './shared/sitemap.DR3_6qqU.mjs';
14
- import { normaliseDate } from '../dist/runtime/server/sitemap/urlset/normalise.js';
15
- import 'ultrahtml';
16
-
17
- async function resolveUrls(urls, ctx) {
18
- try {
19
- if (typeof urls === "function")
20
- urls = urls();
21
- urls = await urls;
22
- } catch (e) {
23
- ctx.logger.error(`Failed to resolve ${typeof urls} urls.`);
24
- ctx.logger.error(e);
25
- return [];
26
- }
27
- try {
28
- urls = JSON.parse(JSON.stringify(urls));
29
- } catch (e) {
30
- ctx.logger.error(`Failed to serialize ${typeof urls} \`${ctx.path}\`, please make sure that the urls resolve as a valid array without circular dependencies.`);
31
- ctx.logger.error(e);
32
- return [];
33
- }
34
- return urls;
35
- }
36
- function deepForEachPage(pages, callback, opts, fullpath = null, depth = 0) {
37
- pages.forEach((page) => {
38
- let currentPath;
39
- if (page.path.startsWith("/")) {
40
- currentPath = page.path;
41
- } else {
42
- currentPath = page.path === "" ? fullpath : `${fullpath.replace(/\/$/, "")}/${page.path}`;
43
- }
44
- let didCallback = false;
45
- if (opts.isI18nMicro) {
46
- const localePattern = /\/:locale\(([^)]+)\)/;
47
- const match = localePattern.exec(currentPath || "");
48
- if (match) {
49
- const locales = match[1].split("|");
50
- locales.forEach((locale) => {
51
- const subPage = { ...page };
52
- const localizedPath = (currentPath || "").replace(localePattern, `/${locale}`);
53
- subPage.name += opts.routesNameSeparator + locale;
54
- subPage.path = localizedPath;
55
- callback(subPage, localizedPath || "", depth);
56
- didCallback = true;
57
- });
58
- }
59
- }
60
- if (!didCallback) {
61
- callback(page, currentPath || "", depth);
62
- }
63
- if (page.children) {
64
- deepForEachPage(page.children, callback, opts, currentPath, depth + 1);
65
- }
66
- });
67
- }
68
- function convertNuxtPagesToSitemapEntries(pages, config) {
69
- const pathFilter = createPathFilter(config.filter);
70
- const routesNameSeparator = config.routesNameSeparator || "___";
71
- let flattenedPages = [];
72
- deepForEachPage(
73
- pages,
74
- (page, loc, depth) => {
75
- flattenedPages.push({ page, loc, depth });
76
- },
77
- {
78
- ...config,
79
- routesNameSeparator: config.routesNameSeparator || "___"
80
- }
81
- );
82
- flattenedPages = flattenedPages.filter((page) => !page.loc.includes(":")).filter((page, idx, arr) => {
83
- return !arr.find((p) => {
84
- return p.loc === page.loc && p.depth > page.depth;
85
- });
86
- }).map((p) => {
87
- delete p.depth;
88
- return p;
89
- });
90
- if (config.strategy === "prefix_and_default") {
91
- flattenedPages = flattenedPages.filter((p) => {
92
- if (p.page?.name) {
93
- const [, locale] = p.page.name.split(routesNameSeparator);
94
- return locale !== config.defaultLocale || p.page.name.endsWith("__default");
95
- }
96
- return true;
97
- });
98
- }
99
- const pagesWithMeta = flattenedPages.map((p) => {
100
- if (config.autoLastmod && p.page.file) {
101
- try {
102
- const stats = statSync(p.page.file);
103
- if (stats?.mtime)
104
- p.lastmod = stats.mtime;
105
- } catch {
106
- }
107
- }
108
- if (p.page?.meta?.sitemap) {
109
- p = defu(p.page.meta.sitemap, p);
110
- }
111
- return p;
112
- });
113
- const localeGroups = {};
114
- pagesWithMeta.reduce((acc, e) => {
115
- if (e.page.name?.includes(routesNameSeparator)) {
116
- const [name, locale] = e.page.name.split(routesNameSeparator);
117
- if (!acc[name])
118
- acc[name] = [];
119
- const { _sitemap } = config.normalisedLocales.find((l) => l.code === locale) || { _sitemap: locale };
120
- acc[name].push({ ...e, _sitemap: config.isI18nMapped ? _sitemap : void 0, locale });
121
- } else {
122
- acc.default = acc.default || [];
123
- acc.default.push(e);
124
- }
125
- return acc;
126
- }, localeGroups);
127
- return Object.entries(localeGroups).map(([locale, entries]) => {
128
- if (locale === "default") {
129
- return entries.map((e) => {
130
- const [name] = (e.page?.name || "").split(routesNameSeparator);
131
- if (localeGroups[name]?.some((a) => a.locale === config.defaultLocale))
132
- return false;
133
- const defaultLocale = config.normalisedLocales.find((l) => l.code === config.defaultLocale);
134
- if (defaultLocale && config.isI18nMapped)
135
- e._sitemap = defaultLocale._sitemap;
136
- delete e.page;
137
- delete e.locale;
138
- return { ...e };
139
- }).filter(Boolean);
140
- }
141
- return entries.map((entry) => {
142
- const alternatives = entries.map((entry2) => {
143
- const locale2 = config.normalisedLocales.find((l) => l.code === entry2.locale);
144
- if (!pathFilter(entry2.loc))
145
- return false;
146
- const href = locale2?.domain ? withHttps(withBase(entry2.loc, locale2?.domain)) : entry2.loc;
147
- return {
148
- hreflang: locale2?._hreflang,
149
- href
150
- };
151
- }).filter(Boolean);
152
- const xDefault = entries.find((a) => a.locale === config.defaultLocale);
153
- if (xDefault && alternatives.length && pathFilter(xDefault.loc)) {
154
- const locale2 = config.normalisedLocales.find((l) => l.code === xDefault.locale);
155
- const href = locale2?.domain ? withHttps(withBase(xDefault.loc, locale2?.domain)) : xDefault.loc;
156
- alternatives.push({
157
- hreflang: "x-default",
158
- href
159
- });
160
- }
161
- const e = { ...entry };
162
- if (config.isI18nMapped) {
163
- const { _sitemap } = config.normalisedLocales.find((l) => l.code === entry.locale) || { _sitemap: locale };
164
- e._sitemap = _sitemap;
165
- }
166
- delete e.page;
167
- delete e.locale;
168
- return {
169
- ...e,
170
- alternatives
171
- };
172
- });
173
- }).filter(Boolean).flat();
174
- }
175
- function generateExtraRoutesFromNuxtConfig(nuxt = useNuxt()) {
176
- const filterForValidPage = (p) => p && !extname(p) && !p.startsWith("/api/") && !p.startsWith("/_");
177
- const routeRules = Object.entries(nuxt.options.routeRules || {}).filter(([k, v]) => {
178
- if (k.includes("*") || k.includes(".") || k.includes(":"))
179
- return false;
180
- if (typeof v.robots === "boolean" && !v.robots)
181
- return false;
182
- return !v.redirect;
183
- }).map(([k]) => k).filter(filterForValidPage);
184
- const prerenderUrls = (nuxt.options.nitro.prerender?.routes || []).filter(filterForValidPage);
185
- return { routeRules, prerenderUrls };
186
- }
187
-
188
- async function getNuxtModuleOptions(module, nuxt = useNuxt()) {
189
- const moduleMeta = (typeof module === "string" ? { name: module } : await module.getMeta?.()) || {};
190
- const { nuxtModule } = await loadNuxtModuleInstance(module, nuxt);
191
- let moduleEntry;
192
- for (const m of nuxt.options.modules) {
193
- if (Array.isArray(m) && m.length >= 2) {
194
- const _module = m[0];
195
- const _moduleEntryName = typeof _module === "string" ? _module : (await _module.getMeta?.())?.name || "";
196
- if (_moduleEntryName === moduleMeta.name)
197
- moduleEntry = m;
198
- }
199
- }
200
- let inlineOptions = {};
201
- if (moduleEntry)
202
- inlineOptions = moduleEntry[1];
203
- if (nuxtModule.getOptions)
204
- return nuxtModule.getOptions(inlineOptions, nuxt);
205
- return inlineOptions;
206
- }
207
- function extendTypes(module, template) {
208
- const nuxt = useNuxt();
209
- const { resolve } = createResolver(import.meta.url);
210
- const fileName = `${module.replace("/", "-")}.d.ts`;
211
- addTemplate({
212
- filename: `module/${fileName}`,
213
- getContents: async () => {
214
- const typesPath = relative(resolve(nuxt.options.rootDir, nuxt.options.buildDir, "module"), resolve("../runtime/types"));
215
- const s = await template({ typesPath });
216
- return `// Generated by ${module}
217
- ${s}
218
- export {}
219
- `;
220
- }
221
- });
222
- nuxt.hooks.hook("prepare:types", ({ references }) => {
223
- references.push({ path: resolve(nuxt.options.buildDir, `module/${fileName}`) });
224
- });
225
- nuxt.hooks.hook("nitro:config", (config) => {
226
- config.typescript = config.typescript || {};
227
- config.typescript.tsConfig = config.typescript.tsConfig || {};
228
- config.typescript.tsConfig.include = config.typescript.tsConfig.include || [];
229
- config.typescript.tsConfig.include.push(`./module/${fileName}`);
230
- });
231
- }
232
- function createPagesPromise(nuxt = useNuxt()) {
233
- return new Promise((resolve) => {
234
- nuxt.hooks.hook("modules:done", () => {
235
- if (typeof nuxt.options.pages === "boolean" && nuxt.options.pages === false || typeof nuxt.options.pages === "object" && !nuxt.options.pages.enabled) {
236
- return resolve([]);
237
- }
238
- extendPages(resolve);
239
- });
240
- });
241
- }
242
- function createNitroPromise(nuxt = useNuxt()) {
243
- return new Promise((resolve) => {
244
- nuxt.hooks.hook("nitro:init", (nitro) => {
245
- resolve(nitro);
246
- });
247
- });
248
- }
249
- const autodetectableProviders = {
250
- azure_static: "azure",
251
- cloudflare_pages: "cloudflare-pages",
252
- netlify: "netlify",
253
- stormkit: "stormkit",
254
- vercel: "vercel",
255
- cleavr: "cleavr",
256
- stackblitz: "stackblitz"
257
- };
258
- const autodetectableStaticProviders = {
259
- netlify: "netlify-static",
260
- vercel: "vercel-static"
261
- };
262
- function detectTarget(options = {}) {
263
- return options?.static ? autodetectableStaticProviders[provider] : autodetectableProviders[provider];
264
- }
265
- function resolveNitroPreset(nitroConfig) {
266
- nitroConfig = nitroConfig || tryUseNuxt()?.options?.nitro;
267
- if (provider === "stackblitz")
268
- return "stackblitz";
269
- let preset;
270
- if (nitroConfig && nitroConfig?.preset)
271
- preset = nitroConfig.preset;
272
- if (!preset)
273
- preset = env.NITRO_PRESET || env.SERVER_PRESET || detectTarget() || "node-server";
274
- return preset.replace("_", "-");
275
- }
276
-
277
- function formatPrerenderRoute(route) {
278
- let str = ` \u251C\u2500 ${route.route} (${route.generateTimeMS}ms)`;
279
- if (route.error) {
280
- const errorColor = chalk[route.error.statusCode === 404 ? "yellow" : "red"];
281
- const errorLead = "\u2514\u2500\u2500";
282
- str += `
283
- \u2502 ${errorLead} ${errorColor(route.error)}`;
284
- }
285
- return chalk.gray(str);
286
- }
287
- function includesSitemapRoot(sitemapName, routes) {
288
- return routes.includes(`/__sitemap__/`) || routes.includes(`/sitemap.xml`) || routes.includes(`/${sitemapName}`) || routes.includes("/sitemap_index.xml");
289
- }
290
- function isNuxtGenerate(nuxt = useNuxt()) {
291
- return nuxt.options.nitro.static || nuxt.options._generate || [
292
- "static",
293
- "github-pages"
294
- ].includes(resolveNitroPreset());
295
- }
296
- const NuxtRedirectHtmlRegex = /<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=([^"]+)"><\/head><\/html>/;
297
- function setupPrerenderHandler(_options, nuxt = useNuxt()) {
298
- const { runtimeConfig: options, logger } = _options;
299
- const prerenderedRoutes = nuxt.options.nitro.prerender?.routes || [];
300
- let prerenderSitemap = isNuxtGenerate() || includesSitemapRoot(options.sitemapName, prerenderedRoutes);
301
- if (resolveNitroPreset() === "vercel-edge") {
302
- logger.warn("Runtime sitemaps are not supported on Vercel Edge, falling back to prerendering sitemaps.");
303
- prerenderSitemap = true;
304
- }
305
- nuxt.options.nitro.prerender = nuxt.options.nitro.prerender || {};
306
- nuxt.options.nitro.prerender.routes = nuxt.options.nitro.prerender.routes || [];
307
- const shouldHookIntoPrerender = prerenderSitemap || nuxt.options.nitro.prerender.routes.length && nuxt.options.nitro.prerender.crawlLinks;
308
- if (isNuxtGenerate() && options.debug) {
309
- nuxt.options.nitro.prerender.routes.push("/__sitemap__/debug.json");
310
- logger.info("Adding debug route for sitemap generation:", chalk.cyan("/__sitemap__/debug.json"));
311
- }
312
- if (!shouldHookIntoPrerender) {
313
- return;
314
- }
315
- nuxt.options.nitro.prerender.routes = nuxt.options.nitro.prerender.routes.filter((r) => r && !includesSitemapRoot(options.sitemapName, [r]));
316
- nuxt.hooks.hook("nitro:init", async (nitro) => {
317
- let prerenderer;
318
- nitro.hooks.hook("prerender:init", async (_prerenderer) => {
319
- prerenderer = _prerenderer;
320
- });
321
- nitro.hooks.hook("prerender:generate", async (route) => {
322
- const html = route.contents;
323
- if (!route.fileName?.endsWith(".html") || !html || ["/200.html", "/404.html"].includes(route.route))
324
- return;
325
- if (html.match(NuxtRedirectHtmlRegex)) {
326
- return;
327
- }
328
- route._sitemap = defu(route._sitemap, {
329
- loc: route.route
330
- });
331
- if (options.autoI18n && Object.keys(options.sitemaps).length > 1) {
332
- const path = route.route;
333
- const match = splitForLocales(path, options.autoI18n.locales.map((l) => l.code));
334
- const locale = match[0] || options.autoI18n.defaultLocale;
335
- if (options.isI18nMapped) {
336
- const { _sitemap } = options.autoI18n.locales.find((l) => l.code === locale) || { _sitemap: locale };
337
- route._sitemap._sitemap = _sitemap;
338
- }
339
- }
340
- route._sitemap = defu(parseHtmlExtractSitemapMeta(html, {
341
- images: options.discoverImages,
342
- videos: options.discoverVideos,
343
- // TODO configurable?
344
- lastmod: true,
345
- alternatives: true,
346
- resolveUrl(s) {
347
- return s.startsWith("/") ? withSiteUrl(s) : s;
348
- }
349
- }), route._sitemap);
350
- });
351
- nitro.hooks.hook("prerender:done", async () => {
352
- const isNuxt5 = nuxt.options._majorVersion === 5;
353
- let nitroModule;
354
- if (isNuxt5) {
355
- nitroModule = await import(String("nitro"));
356
- } else {
357
- nitroModule = await import(String("nitropack"));
358
- }
359
- if (!nitroModule) {
360
- return;
361
- }
362
- await nitroModule.build(prerenderer);
363
- await prerenderRoute(nitro, options.isMultiSitemap ? "/sitemap_index.xml" : `/${Object.keys(options.sitemaps)[0]}`);
364
- });
365
- });
366
- }
367
- async function prerenderRoute(nitro, route) {
368
- const start = Date.now();
369
- const _route = { route, fileName: route };
370
- const encodedRoute = encodeURI(route);
371
- const res = await globalThis.$fetch.raw(
372
- withBase(encodedRoute, nitro.options.baseURL),
373
- {
374
- headers: { "x-nitro-prerender": encodedRoute },
375
- retry: nitro.options.prerender.retry,
376
- retryDelay: nitro.options.prerender.retryDelay
377
- }
378
- );
379
- const header = res.headers.get("x-nitro-prerender") || "";
380
- const prerenderUrls = [
381
- ...header.split(",").map((i) => i.trim()).map((i) => decodeURIComponent(i)).filter(Boolean)
382
- ];
383
- const filePath = join(nitro.options.output.publicDir, _route.fileName);
384
- await mkdir(dirname(filePath), { recursive: true });
385
- const data = res._data;
386
- if (filePath.endsWith("json") || typeof data === "object")
387
- await writeFile(filePath, JSON.stringify(data), "utf8");
388
- else
389
- await writeFile(filePath, data, "utf8");
390
- _route.generateTimeMS = Date.now() - start;
391
- nitro._prerenderedRoutes.push(_route);
392
- nitro.logger.log(formatPrerenderRoute(_route));
393
- for (const url of prerenderUrls)
394
- await prerenderRoute(nitro, url);
395
- }
396
-
397
- const DEVTOOLS_UI_ROUTE = "/__sitemap__/devtools";
398
- const DEVTOOLS_UI_LOCAL_PORT = 3030;
399
- function setupDevToolsUI(options, resolve, nuxt = useNuxt()) {
400
- const clientPath = resolve("./client");
401
- const isProductionBuild = existsSync(clientPath);
402
- if (isProductionBuild) {
403
- nuxt.hook("vite:serverCreated", async (server) => {
404
- const sirv = await import('sirv').then((r) => r.default || r);
405
- server.middlewares.use(
406
- DEVTOOLS_UI_ROUTE,
407
- sirv(clientPath, { dev: true, single: true })
408
- );
409
- });
410
- } else {
411
- nuxt.hook("vite:extendConfig", (config) => {
412
- config.server = config.server || {};
413
- config.server.proxy = config.server.proxy || {};
414
- config.server.proxy[DEVTOOLS_UI_ROUTE] = {
415
- target: `http://localhost:${DEVTOOLS_UI_LOCAL_PORT}${DEVTOOLS_UI_ROUTE}`,
416
- changeOrigin: true,
417
- followRedirects: true,
418
- rewrite: (path) => path.replace(DEVTOOLS_UI_ROUTE, "")
419
- };
420
- });
421
- }
422
- nuxt.hook("devtools:customTabs", (tabs) => {
423
- tabs.push({
424
- // unique identifier
425
- name: "sitemap",
426
- // title to display in the tab
427
- title: "Sitemap",
428
- // any icon from Iconify, or a URL to an image
429
- icon: "carbon:load-balancer-application",
430
- // iframe view
431
- view: {
432
- type: "iframe",
433
- src: DEVTOOLS_UI_ROUTE
434
- }
435
- });
436
- });
437
- }
438
-
439
- function splitPathForI18nLocales(path, autoI18n) {
440
- const locales = autoI18n.strategy === "prefix_except_default" ? autoI18n.locales.filter((l) => l.code !== autoI18n.defaultLocale) : autoI18n.locales;
441
- if (typeof path !== "string" || path.startsWith("/_"))
442
- return path;
443
- const match = splitForLocales(path, locales.map((l) => l.code));
444
- const locale = match[0];
445
- if (locale)
446
- return path;
447
- return [
448
- path,
449
- ...locales.map((l) => `/${l.code}${path}`)
450
- ];
451
- }
452
- function generatePathForI18nPages(ctx) {
453
- const { localeCode, pageLocales, nuxtI18nConfig, forcedStrategy, normalisedLocales } = ctx;
454
- const locale = normalisedLocales.find((l) => l.code === localeCode);
455
- let path = pageLocales;
456
- switch (forcedStrategy ?? nuxtI18nConfig.strategy) {
457
- case "prefix_except_default":
458
- case "prefix_and_default":
459
- path = localeCode === nuxtI18nConfig.defaultLocale ? pageLocales : joinURL(localeCode, pageLocales);
460
- break;
461
- case "prefix":
462
- path = joinURL(localeCode, pageLocales);
463
- break;
464
- }
465
- return locale?.domain ? withHttps(withBase(path, locale.domain)) : path;
466
- }
467
- function normalizeLocales(nuxtI18nConfig) {
468
- let locales = nuxtI18nConfig.locales || [];
469
- let onlyLocales = nuxtI18nConfig?.bundle?.onlyLocales || [];
470
- onlyLocales = typeof onlyLocales === "string" ? [onlyLocales] : onlyLocales;
471
- locales = mergeOnKey(locales.map((locale) => typeof locale === "string" ? { code: locale } : locale), "code");
472
- if (onlyLocales.length) {
473
- locales = locales.filter((locale) => onlyLocales.includes(locale.code));
474
- }
475
- return locales.map((locale) => {
476
- if (locale.iso && !locale.language) {
477
- locale.language = locale.iso;
478
- }
479
- locale._hreflang = locale.language || locale.code;
480
- locale._sitemap = locale.language || locale.code;
481
- return locale;
482
- });
483
- }
484
-
485
- function isValidFilter(filter) {
486
- if (typeof filter === "string")
487
- return true;
488
- if (filter instanceof RegExp)
489
- return true;
490
- if (typeof filter === "object" && typeof filter.regex === "string")
491
- return true;
492
- return false;
493
- }
494
- function normalizeFilters(filters) {
495
- return (filters || []).map((filter) => {
496
- if (!isValidFilter(filter)) {
497
- console.warn(`[@nuxtjs/sitemap] You have provided an invalid filter: ${filter}, ignoring.`);
498
- return false;
499
- }
500
- return filter instanceof RegExp ? { regex: filter.toString() } : filter;
501
- }).filter(Boolean);
502
- }
503
-
504
- const module = defineNuxtModule({
505
- meta: {
506
- name: "@nuxtjs/sitemap",
507
- compatibility: {
508
- nuxt: ">=3.9.0",
509
- bridge: false
510
- },
511
- configKey: "sitemap"
512
- },
513
- defaults: {
514
- enabled: true,
515
- credits: true,
516
- cacheMaxAgeSeconds: 60 * 10,
517
- // cache for 10 minutes
518
- minify: false,
519
- debug: false,
520
- defaultSitemapsChunkSize: 1e3,
521
- autoLastmod: false,
522
- discoverImages: true,
523
- discoverVideos: true,
524
- urls: [],
525
- sortEntries: true,
526
- sitemapsPathPrefix: "/__sitemap__/",
527
- xsl: "/__sitemap__/style.xsl",
528
- xslTips: true,
529
- strictNuxtContentPaths: false,
530
- runtimeCacheStorage: true,
531
- sitemapName: "sitemap.xml",
532
- // cacheControlHeader: 'max-age=600, must-revalidate',
533
- defaults: {},
534
- // index sitemap options filtering
535
- include: [],
536
- exclude: ["/_**"],
537
- // sources
538
- sources: [],
539
- excludeAppSources: []
540
- },
541
- async setup(config, nuxt) {
542
- const { resolve } = createResolver(import.meta.url);
543
- const { name, version } = await readPackageJSON(resolve("../package.json"));
544
- const logger = useLogger(name);
545
- logger.level = config.debug || nuxt.options.debug ? 4 : 3;
546
- if (config.enabled === false) {
547
- logger.debug("The module is disabled, skipping setup.");
548
- return;
549
- }
550
- config.exclude.push(`${withTrailingSlash(nuxt.options.app.buildAssetsDir)}**`);
551
- nuxt.options.alias["#sitemap"] = resolve("./runtime");
552
- nuxt.options.nitro.alias = nuxt.options.nitro.alias || {};
553
- nuxt.options.nitro.alias["#sitemap"] = resolve("./runtime");
554
- config.xslColumns = config.xslColumns || [
555
- { label: "URL", width: "50%" },
556
- { label: "Images", width: "25%", select: "count(image:image)" },
557
- {
558
- label: "Last Updated",
559
- width: "25%",
560
- select: "concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)),concat(' ', substring(sitemap:lastmod,20,6)))"
561
- }
562
- ];
563
- if (config.autoLastmod) {
564
- config.defaults = config.defaults || {};
565
- config.defaults.lastmod = normaliseDate(/* @__PURE__ */ new Date());
566
- }
567
- const normalizedSitemaps = typeof config.sitemaps === "boolean" ? {} : config.sitemaps || {};
568
- if (!nuxt.options._prepare && Object.keys(normalizedSitemaps).length) {
569
- const isSitemapIndexOnly = typeof normalizedSitemaps?.index !== "undefined" && Object.keys(normalizedSitemaps).length === 1;
570
- if (!isSitemapIndexOnly) {
571
- const warnForIgnoredKey = (key) => {
572
- logger.warn(`You are using multiple-sitemaps but have provided \`sitemap.${key}\` in your Nuxt config. This will be ignored, please move it to the child sitemap config.`);
573
- logger.warn("Learn more at: https://nuxtseo.com/sitemap/guides/multi-sitemaps");
574
- };
575
- switch (true) {
576
- case (config?.sources?.length || 0) > 0:
577
- warnForIgnoredKey("sources");
578
- break;
579
- case config?.includeAppSources !== void 0:
580
- warnForIgnoredKey("includeAppSources");
581
- break;
582
- }
583
- }
584
- }
585
- await installNuxtSiteConfig();
586
- const userGlobalSources = [
587
- ...config.sources || []
588
- ];
589
- const appGlobalSources = [];
590
- nuxt.options.nitro.storage = nuxt.options.nitro.storage || {};
591
- if (config.runtimeCacheStorage && !nuxt.options.dev && typeof config.runtimeCacheStorage === "object")
592
- nuxt.options.nitro.storage.sitemap = config.runtimeCacheStorage;
593
- if (!config.sitemapName.endsWith("xml")) {
594
- const newName = `${config.sitemapName.split(".")[0]}.xml`;
595
- logger.warn(`You have provided a \`sitemapName\` that does not end with \`.xml\`. This is not supported by search engines, renaming to \`${newName}\`.`);
596
- config.sitemapName = newName;
597
- }
598
- config.sitemapName = withoutLeadingSlash(config.sitemapName);
599
- let usingMultiSitemaps = !!config.sitemaps;
600
- let isI18nMapped = false;
601
- let nuxtI18nConfig = {};
602
- let resolvedAutoI18n = typeof config.autoI18n === "boolean" ? false : config.autoI18n || false;
603
- const hasDisabledAutoI18n = typeof config.autoI18n === "boolean" && !config.autoI18n;
604
- let normalisedLocales = [];
605
- let usingI18nPages = false;
606
- const i18nModule = ["@nuxtjs/i18n", "nuxt-i18n-micro"].find((s) => hasNuxtModule(s));
607
- if (i18nModule) {
608
- const i18nVersion = await getNuxtModuleVersion(i18nModule);
609
- if (i18nVersion && i18nModule === "@nuxtjs/i18n" && !await hasNuxtModuleCompatibility(i18nModule, ">=8"))
610
- logger.warn(`You are using ${i18nModule} v${i18nVersion}. For the best compatibility, please upgrade to ${i18nModule} v8.0.0 or higher.`);
611
- nuxtI18nConfig = await getNuxtModuleOptions(i18nModule) || {};
612
- if (typeof nuxtI18nConfig.includeDefaultLocaleRoute !== "undefined") {
613
- nuxtI18nConfig.strategy = nuxtI18nConfig.includeDefaultLocaleRoute ? "prefix" : "prefix_except_default";
614
- }
615
- normalisedLocales = normalizeLocales(nuxtI18nConfig);
616
- usingI18nPages = !!Object.keys(nuxtI18nConfig.pages || {}).length;
617
- if (usingI18nPages && !hasDisabledAutoI18n) {
618
- const i18nPagesSources = {
619
- context: {
620
- name: `${i18nModule}:pages`,
621
- description: "Generated from your i18n.pages config.",
622
- tips: [
623
- "You can disable this with `autoI18n: false`."
624
- ]
625
- },
626
- urls: []
627
- };
628
- for (const pageLocales of Object.values(nuxtI18nConfig?.pages)) {
629
- for (const localeCode in pageLocales) {
630
- const locale = normalisedLocales.find((l) => l.code === localeCode);
631
- if (!locale || !pageLocales[localeCode] || pageLocales[localeCode].includes("["))
632
- continue;
633
- const alternatives = Object.keys(pageLocales).filter((l) => pageLocales[l] !== false).map((l) => ({
634
- hreflang: normalisedLocales.find((nl) => nl.code === l)?._hreflang || l,
635
- href: generatePathForI18nPages({ localeCode: l, pageLocales: pageLocales[l], nuxtI18nConfig, normalisedLocales })
636
- }));
637
- if (alternatives.length && nuxtI18nConfig.defaultLocale && pageLocales[nuxtI18nConfig.defaultLocale] && pageLocales[nuxtI18nConfig.defaultLocale] !== false)
638
- alternatives.push({ hreflang: "x-default", href: generatePathForI18nPages({ normalisedLocales, localeCode: nuxtI18nConfig.defaultLocale, pageLocales: pageLocales[nuxtI18nConfig.defaultLocale], nuxtI18nConfig }) });
639
- i18nPagesSources.urls.push({
640
- _sitemap: locale._sitemap,
641
- loc: generatePathForI18nPages({ normalisedLocales, localeCode, pageLocales: pageLocales[localeCode], nuxtI18nConfig }),
642
- alternatives
643
- });
644
- if (nuxtI18nConfig.strategy === "prefix_and_default" && localeCode === nuxtI18nConfig.defaultLocale) {
645
- i18nPagesSources.urls.push({
646
- _sitemap: locale._sitemap,
647
- loc: generatePathForI18nPages({ normalisedLocales, localeCode, pageLocales: pageLocales[localeCode], nuxtI18nConfig, forcedStrategy: "prefix" }),
648
- alternatives
649
- });
650
- }
651
- }
652
- }
653
- appGlobalSources.push(i18nPagesSources);
654
- if (Array.isArray(config.excludeAppSources))
655
- config.excludeAppSources.push("nuxt:pages");
656
- } else {
657
- if (!normalisedLocales.length)
658
- logger.warn(`You are using ${i18nModule} but have not configured any locales, this will cause issues with ${name}. Please configure \`locales\`.`);
659
- }
660
- const hasSetAutoI18n = typeof config.autoI18n === "object" && Object.keys(config.autoI18n).length;
661
- const hasI18nConfigForAlternatives = nuxtI18nConfig.differentDomains || usingI18nPages || nuxtI18nConfig.strategy !== "no_prefix" && nuxtI18nConfig.locales;
662
- if (!hasSetAutoI18n && !hasDisabledAutoI18n && hasI18nConfigForAlternatives) {
663
- resolvedAutoI18n = {
664
- differentDomains: nuxtI18nConfig.differentDomains,
665
- defaultLocale: nuxtI18nConfig.defaultLocale,
666
- locales: normalisedLocales,
667
- strategy: nuxtI18nConfig.strategy,
668
- // @ts-expect-error untyped
669
- pages: nuxtI18nConfig.pages
670
- };
671
- }
672
- let canI18nMap = config.sitemaps !== false && nuxtI18nConfig.strategy !== "no_prefix";
673
- if (typeof config.sitemaps === "object") {
674
- const isSitemapIndexOnly = typeof config.sitemaps.index !== "undefined" && Object.keys(config.sitemaps).length === 1;
675
- if (!isSitemapIndexOnly)
676
- canI18nMap = false;
677
- }
678
- if (canI18nMap && resolvedAutoI18n) {
679
- config.sitemaps = { index: [...config.sitemaps?.index || [], ...config.appendSitemaps || []] };
680
- for (const locale of resolvedAutoI18n.locales)
681
- config.sitemaps[locale._sitemap] = { includeAppSources: true };
682
- isI18nMapped = true;
683
- usingMultiSitemaps = true;
684
- }
685
- }
686
- nuxt.hooks.hook("robots:config", (robotsConfig) => {
687
- robotsConfig.sitemap.push(usingMultiSitemaps ? "/sitemap_index.xml" : `/${config.sitemapName}`);
688
- });
689
- nuxt.hooks.hook("modules:done", async () => {
690
- const robotsModuleName = ["nuxt-simple-robots", "@nuxtjs/robots"].find((s) => hasNuxtModule(s));
691
- let needsRobotsPolyfill = true;
692
- if (robotsModuleName) {
693
- const robotsVersion = await getNuxtModuleVersion(robotsModuleName);
694
- if (robotsVersion && !await hasNuxtModuleCompatibility(robotsModuleName, ">=4"))
695
- logger.warn(`You are using ${robotsModuleName} v${robotsVersion}. For the best compatibility, please upgrade to ${robotsModuleName} v4.0.0 or higher.`);
696
- else
697
- needsRobotsPolyfill = false;
698
- }
699
- if (needsRobotsPolyfill) {
700
- nuxt.options.nitro.alias = nuxt.options.nitro.alias || {};
701
- nuxt.options.nitro.alias["#internal/nuxt-robots"] = resolve("./runtime/server/robots-polyfill");
702
- addServerImports([{
703
- name: "getPathRobotConfig",
704
- as: "getPathRobotConfig",
705
- from: resolve("./runtime/server/robots-polyfill/getPathRobotConfig")
706
- }]);
707
- }
708
- });
709
- extendTypes(name, async ({ typesPath }) => {
710
- return `
711
- declare module 'nitropack' {
712
- interface PrerenderRoute {
713
- _sitemap?: import('${typesPath}').SitemapUrl
714
- }
715
- interface NitroRouteRules {
716
- index?: boolean
717
- sitemap?: import('${typesPath}').SitemapItemDefaults
718
- }
719
- interface NitroRouteConfig {
720
- index?: boolean
721
- sitemap?: import('${typesPath}').SitemapItemDefaults
722
- }
723
- interface NitroRuntimeHooks {
724
- 'sitemap:index-resolved': (ctx: import('${typesPath}').SitemapIndexRenderCtx) => void | Promise<void>
725
- 'sitemap:input': (ctx: import('${typesPath}').SitemapInputCtx) => void | Promise<void>
726
- 'sitemap:resolved': (ctx: import('${typesPath}').SitemapRenderCtx) => void | Promise<void>
727
- 'sitemap:output': (ctx: import('${typesPath}').SitemapOutputHookCtx) => void | Promise<void>
728
- 'sitemap:sources': (ctx: import('${typesPath}').SitemapSourcesHookCtx) => void | Promise<void>
729
- }
730
- }
731
- declare module 'vue-router' {
732
- interface RouteMeta {
733
- sitemap?: import('${typesPath}').SitemapItemDefaults
734
- }
735
- }
736
- `;
737
- });
738
- const prerenderedRoutes = nuxt.options.nitro.prerender?.routes || [];
739
- const prerenderSitemap = isNuxtGenerate() || includesSitemapRoot(config.sitemapName, prerenderedRoutes);
740
- const routeRules = {};
741
- nuxt.options.nitro.routeRules = nuxt.options.nitro.routeRules || {};
742
- if (prerenderSitemap) {
743
- routeRules.headers = {
744
- "Content-Type": "text/xml; charset=UTF-8",
745
- "Cache-Control": config.cacheMaxAgeSeconds ? `public, max-age=${config.cacheMaxAgeSeconds}, must-revalidate` : "no-cache, no-store",
746
- "X-Sitemap-Prerendered": (/* @__PURE__ */ new Date()).toISOString()
747
- };
748
- }
749
- if (config.xsl) {
750
- nuxt.options.nitro.routeRules[config.xsl] = {
751
- headers: {
752
- "Content-Type": "application/xslt+xml"
753
- }
754
- };
755
- }
756
- if (usingMultiSitemaps) {
757
- nuxt.options.nitro.routeRules["/sitemap.xml"] = { redirect: "/sitemap_index.xml" };
758
- nuxt.options.nitro.routeRules["/sitemap_index.xml"] = routeRules;
759
- if (typeof config.sitemaps === "object") {
760
- for (const k in config.sitemaps) {
761
- if (k === "index")
762
- continue;
763
- nuxt.options.nitro.routeRules[joinURL(config.sitemapsPathPrefix || "", `/${k}.xml`)] = routeRules;
764
- const sitemapConfig = config.sitemaps[k];
765
- if (sitemapConfig.chunks) {
766
- nuxt.options.nitro.routeRules[joinURL(config.sitemapsPathPrefix || "", `/${k}-*.xml`)] = routeRules;
767
- }
768
- }
769
- } else {
770
- nuxt.options.nitro.routeRules[joinURL(config.sitemapsPathPrefix || "", `/[0-9]+.xml`)] = routeRules;
771
- }
772
- } else {
773
- nuxt.options.nitro.routeRules[`/${config.sitemapName}`] = routeRules;
774
- }
775
- if (config.experimentalWarmUp)
776
- addServerPlugin(resolve("./runtime/server/plugins/warm-up"));
777
- if (config.experimentalCompression)
778
- addServerPlugin(resolve("./runtime/server/plugins/compression"));
779
- const isNuxtContentDocumentDriven = !!nuxt.options.content?.documentDriven || config.strictNuxtContentPaths;
780
- const usingNuxtContent = hasNuxtModule("@nuxt/content");
781
- const isNuxtContentV3 = usingNuxtContent && await hasNuxtModuleCompatibility("@nuxt/content", "^3");
782
- const nuxtV3Collections = /* @__PURE__ */ new Set();
783
- const isNuxtContentV2 = usingNuxtContent && await hasNuxtModuleCompatibility("@nuxt/content", "^2");
784
- if (isNuxtContentV3) {
785
- if (nuxt.options._installedModules.some((m) => m.meta.name === "Content")) {
786
- logger.warn("You have loaded `@nuxt/content` before `@nuxtjs/sitemap`, this may cause issues with the integration. Please ensure `@nuxtjs/sitemap` is loaded first.");
787
- }
788
- config.exclude.push("/__nuxt_content/**");
789
- const needsCustomAlias = await hasNuxtModuleCompatibility("@nuxt/content", "<3.6.0");
790
- if (needsCustomAlias) {
791
- nuxt.options.alias["#sitemap/content-v3-nitro-path"] = resolve(dirname(resolveModule("@nuxt/content")), "runtime/nitro");
792
- nuxt.options.alias["@nuxt/content/nitro"] = resolve("./runtime/server/content-compat");
793
- }
794
- nuxt.hooks.hook("content:file:afterParse", (ctx) => {
795
- const content = ctx.content;
796
- nuxtV3Collections.add(ctx.collection.name);
797
- if (String(ctx.content.path).includes("/.")) {
798
- ctx.content.sitemap = null;
799
- return;
800
- }
801
- if (!("sitemap" in ctx.collection.fields)) {
802
- ctx.content.sitemap = null;
803
- return;
804
- }
805
- if (typeof content.sitemap !== "undefined" && !content.sitemap) {
806
- ctx.content.sitemap = null;
807
- return;
808
- }
809
- if (ctx.content.robots === false) {
810
- ctx.content.sitemap = null;
811
- return;
812
- }
813
- const images = [];
814
- if (config.discoverImages) {
815
- images.push(
816
- ...content.body.value?.filter(
817
- (c) => ["image", "img", "nuxtimg", "nuxt-img"].includes(c[0])
818
- ).filter((c) => c[1]?.src).map((c) => ({ loc: c[1].src })) || []
819
- );
820
- }
821
- const lastmod = content.seo?.articleModifiedTime || content.updatedAt;
822
- const defaults = {
823
- loc: content.path
824
- };
825
- if (images.length > 0)
826
- defaults.images = images;
827
- if (lastmod)
828
- defaults.lastmod = lastmod;
829
- ctx.content.sitemap = defu(typeof content.sitemap === "object" ? content.sitemap : {}, defaults);
830
- });
831
- addServerHandler({
832
- route: "/__sitemap__/nuxt-content-urls.json",
833
- handler: resolve("./runtime/server/routes/__sitemap__/nuxt-content-urls-v3")
834
- });
835
- if (config.strictNuxtContentPaths) {
836
- logger.warn("You have set `strictNuxtContentPaths: true` but are using @nuxt/content v3. This is not required, please remove it.");
837
- }
838
- appGlobalSources.push({
839
- context: {
840
- name: "@nuxt/content@v3:urls",
841
- description: "Generated from your markdown files.",
842
- tips: [`Parsing the following collections: ${Array.from(nuxtV3Collections).join(", ")}`]
843
- },
844
- fetch: "/__sitemap__/nuxt-content-urls.json"
845
- });
846
- } else if (isNuxtContentV2) {
847
- addServerPlugin(resolve("./runtime/server/plugins/nuxt-content-v2"));
848
- addServerHandler({
849
- route: "/__sitemap__/nuxt-content-urls.json",
850
- handler: resolve("./runtime/server/routes/__sitemap__/nuxt-content-urls-v2")
851
- });
852
- const tips = [];
853
- if (nuxt.options.content?.documentDriven)
854
- tips.push("Enabled because you're using `@nuxt/content` with `documentDriven: true`.");
855
- else if (config.strictNuxtContentPaths)
856
- tips.push("Enabled because you've set `config.strictNuxtContentPaths: true`.");
857
- else
858
- tips.push("You can provide a `sitemap` key in your markdown frontmatter to configure specific URLs. Make sure you include a `loc`.");
859
- appGlobalSources.push({
860
- context: {
861
- name: "@nuxt/content@v2:urls",
862
- description: "Generated from your markdown files.",
863
- tips
864
- },
865
- fetch: "/__sitemap__/nuxt-content-urls.json"
866
- });
867
- }
868
- const sitemaps = {};
869
- if (usingMultiSitemaps) {
870
- addServerHandler({
871
- route: "/sitemap_index.xml",
872
- handler: resolve("./runtime/server/routes/sitemap_index.xml"),
873
- lazy: true,
874
- middleware: false
875
- });
876
- if (config.sitemapsPathPrefix && config.sitemapsPathPrefix !== "/") {
877
- addServerHandler({
878
- route: joinURL(config.sitemapsPathPrefix, `/**:sitemap`),
879
- handler: resolve("./runtime/server/routes/sitemap/[sitemap].xml"),
880
- lazy: true,
881
- middleware: false
882
- });
883
- } else {
884
- const sitemapNames = Object.keys(config.sitemaps || {});
885
- for (const sitemapName of sitemapNames) {
886
- if (sitemapName === "index")
887
- continue;
888
- const sitemapConfig = config.sitemaps[sitemapName];
889
- addServerHandler({
890
- route: withLeadingSlash(`${sitemapName}.xml`),
891
- handler: resolve("./runtime/server/routes/sitemap/[sitemap].xml"),
892
- lazy: true,
893
- middleware: false
894
- });
895
- if (sitemapConfig.chunks) {
896
- addServerHandler({
897
- route: `/${sitemapName}-*.xml`,
898
- handler: resolve("./runtime/server/routes/sitemap/[sitemap].xml"),
899
- lazy: true,
900
- middleware: false
901
- });
902
- }
903
- }
904
- }
905
- sitemaps.index = {
906
- sitemapName: "index",
907
- _route: withBase("sitemap_index.xml", nuxt.options.app.baseURL || "/"),
908
- // @ts-expect-error untyped
909
- sitemaps: [...config.sitemaps.index || [], ...config.appendSitemaps || []]
910
- };
911
- if (typeof config.sitemaps === "object") {
912
- for (const sitemapName in config.sitemaps) {
913
- if (sitemapName === "index")
914
- continue;
915
- const definition = config.sitemaps[sitemapName];
916
- const sitemapConfig = defu(
917
- {
918
- sitemapName,
919
- _route: withBase(joinURL(config.sitemapsPathPrefix || "", `${sitemapName}.xml`), nuxt.options.app.baseURL || "/"),
920
- _hasSourceChunk: typeof definition.urls !== "undefined" || definition.sources?.length
921
- },
922
- { ...definition, urls: void 0, sources: void 0 },
923
- { include: config.include, exclude: config.exclude }
924
- );
925
- if (definition.chunks) {
926
- let chunkSize = config.defaultSitemapsChunkSize || 1e3;
927
- if (typeof definition.chunks === "number") {
928
- if (definition.chunks <= 0) {
929
- logger.warn(`Invalid chunks value (${definition.chunks}) for sitemap "${sitemapName}". Using default.`);
930
- } else {
931
- chunkSize = definition.chunks;
932
- }
933
- }
934
- if (definition.chunkSize !== void 0) {
935
- if (typeof definition.chunkSize !== "number" || definition.chunkSize <= 0) {
936
- logger.warn(`Invalid chunkSize value (${definition.chunkSize}) for sitemap "${sitemapName}". Using default.`);
937
- } else {
938
- chunkSize = definition.chunkSize;
939
- }
940
- }
941
- sitemapConfig._isChunking = true;
942
- sitemapConfig._chunkSize = chunkSize;
943
- sitemapConfig.chunks = definition.chunks;
944
- sitemapConfig.chunkSize = definition.chunkSize;
945
- }
946
- sitemaps[sitemapName] = sitemapConfig;
947
- }
948
- } else {
949
- sitemaps.chunks = {
950
- sitemapName: "chunks",
951
- defaults: config.defaults,
952
- include: config.include,
953
- exclude: config.exclude,
954
- includeAppSources: true
955
- };
956
- }
957
- } else {
958
- sitemaps[config.sitemapName] = {
959
- sitemapName: config.sitemapName,
960
- route: withBase(config.sitemapName, nuxt.options.app.baseURL || "/"),
961
- // will contain the xml
962
- defaults: config.defaults,
963
- include: config.include,
964
- exclude: config.exclude,
965
- includeAppSources: true
966
- };
967
- }
968
- if (resolvedAutoI18n && usingI18nPages && !hasDisabledAutoI18n) {
969
- const pages = nuxtI18nConfig?.pages || {};
970
- for (const sitemapName in sitemaps) {
971
- let mapToI18nPages = function(path) {
972
- if (typeof path !== "string")
973
- return [path];
974
- const withoutSlashes = withoutTrailingSlash(withoutLeadingSlash(path)).replace("/index", "");
975
- if (pages && withoutSlashes in pages) {
976
- const pageLocales = pages[withoutSlashes];
977
- if (pageLocales) {
978
- return Object.keys(pageLocales).map((localeCode) => withLeadingSlash(generatePathForI18nPages({
979
- localeCode,
980
- pageLocales: pageLocales[localeCode],
981
- nuxtI18nConfig,
982
- normalisedLocales
983
- })));
984
- }
985
- }
986
- let match = [path];
987
- Object.values(pages).forEach((pageLocales) => {
988
- if (pageLocales && nuxtI18nConfig.defaultLocale in pageLocales && pageLocales[nuxtI18nConfig.defaultLocale] === path)
989
- match = Object.keys(pageLocales).map((localeCode) => withLeadingSlash(generatePathForI18nPages({ localeCode, pageLocales: pageLocales[localeCode], nuxtI18nConfig, normalisedLocales })));
990
- });
991
- return match;
992
- };
993
- if (["index", "chunks"].includes(sitemapName))
994
- continue;
995
- const sitemap = sitemaps[sitemapName];
996
- sitemap.include = (sitemap.include || []).flatMap((path) => mapToI18nPages(path));
997
- sitemap.exclude = (sitemap.exclude || []).flatMap((path) => mapToI18nPages(path));
998
- }
999
- }
1000
- if (resolvedAutoI18n && resolvedAutoI18n.locales && resolvedAutoI18n.strategy !== "no_prefix") {
1001
- const i18n = resolvedAutoI18n;
1002
- for (const sitemapName in sitemaps) {
1003
- if (["index", "chunks"].includes(sitemapName))
1004
- continue;
1005
- const sitemap = sitemaps[sitemapName];
1006
- sitemap.include = (sitemap.include || []).map((path) => splitPathForI18nLocales(path, i18n)).flat();
1007
- sitemap.exclude = (sitemap.exclude || []).map((path) => splitPathForI18nLocales(path, i18n)).flat();
1008
- }
1009
- }
1010
- for (const sitemapName in sitemaps) {
1011
- const sitemap = sitemaps[sitemapName];
1012
- sitemap.include = normalizeFilters(sitemap.include);
1013
- sitemap.exclude = normalizeFilters(sitemap.exclude);
1014
- }
1015
- const runtimeConfig = {
1016
- isI18nMapped,
1017
- sitemapName: config.sitemapName,
1018
- isMultiSitemap: usingMultiSitemaps,
1019
- excludeAppSources: config.excludeAppSources,
1020
- cacheMaxAgeSeconds: nuxt.options.dev ? 0 : config.cacheMaxAgeSeconds,
1021
- autoLastmod: config.autoLastmod,
1022
- defaultSitemapsChunkSize: config.defaultSitemapsChunkSize,
1023
- minify: config.minify,
1024
- sortEntries: config.sortEntries,
1025
- debug: config.debug,
1026
- // needed for nuxt/content integration and prerendering
1027
- discoverImages: config.discoverImages,
1028
- discoverVideos: config.discoverVideos,
1029
- sitemapsPathPrefix: config.sitemapsPathPrefix,
1030
- /* @nuxt/content */
1031
- isNuxtContentDocumentDriven,
1032
- /* xsl styling */
1033
- xsl: config.xsl,
1034
- xslTips: config.xslTips,
1035
- xslColumns: config.xslColumns,
1036
- credits: config.credits,
1037
- version,
1038
- sitemaps
1039
- };
1040
- if (resolvedAutoI18n)
1041
- runtimeConfig.autoI18n = resolvedAutoI18n;
1042
- nuxt.options.runtimeConfig.sitemap = runtimeConfig;
1043
- if (config.debug || nuxt.options.dev) {
1044
- addServerHandler({
1045
- route: "/__sitemap__/debug.json",
1046
- handler: resolve("./runtime/server/routes/__sitemap__/debug")
1047
- });
1048
- if (usingMultiSitemaps) {
1049
- addServerHandler({
1050
- route: "/__sitemap__/**:sitemap",
1051
- handler: resolve("./runtime/server/routes/sitemap/[sitemap].xml"),
1052
- lazy: true,
1053
- middleware: true
1054
- });
1055
- }
1056
- setupDevToolsUI(config, resolve);
1057
- }
1058
- const imports = [
1059
- {
1060
- from: resolve("./runtime/server/composables/defineSitemapEventHandler"),
1061
- name: "defineSitemapEventHandler"
1062
- },
1063
- {
1064
- from: resolve("./runtime/server/composables/asSitemapUrl"),
1065
- name: "asSitemapUrl"
1066
- }
1067
- ];
1068
- addServerImports(imports);
1069
- const pagesPromise = createPagesPromise();
1070
- const nitroPromise = createNitroPromise();
1071
- let resolvedConfigUrls = false;
1072
- nuxt.hooks.hook("nitro:config", (nitroConfig) => {
1073
- nitroConfig.virtual["#sitemap-virtual/global-sources.mjs"] = async () => {
1074
- const { prerenderUrls, routeRules: routeRules2 } = generateExtraRoutesFromNuxtConfig();
1075
- const prerenderUrlsFinal = [
1076
- ...prerenderUrls,
1077
- ...((await nitroPromise)._prerenderedRoutes || []).filter((r) => {
1078
- const lastSegment = r.route.split("/").pop();
1079
- const isExplicitFile = !!lastSegment?.match(/\.[0-9a-z]+$/i)?.[0];
1080
- if (isExplicitFile || r.error || ["/200.html", "/404.html", "/index.html"].includes(r.route))
1081
- return false;
1082
- return r.contentType?.includes("text/html");
1083
- }).map((r) => r._sitemap)
1084
- ];
1085
- const pageSource = convertNuxtPagesToSitemapEntries(await pagesPromise, {
1086
- isI18nMapped,
1087
- autoLastmod: config.autoLastmod,
1088
- defaultLocale: nuxtI18nConfig.defaultLocale || "en",
1089
- strategy: nuxtI18nConfig.strategy || "no_prefix",
1090
- routesNameSeparator: nuxtI18nConfig.routesNameSeparator,
1091
- normalisedLocales,
1092
- filter: {
1093
- include: normalizeFilters(config.include),
1094
- exclude: normalizeFilters(config.exclude)
1095
- },
1096
- isI18nMicro: i18nModule === "nuxt-i18n-micro"
1097
- });
1098
- if (!pageSource.length) {
1099
- pageSource.push(nuxt.options.app.baseURL || "/");
1100
- }
1101
- if (!resolvedConfigUrls && config.urls) {
1102
- if (config.urls) {
1103
- userGlobalSources.push({
1104
- context: {
1105
- name: "sitemap:urls",
1106
- description: "Set with the `sitemap.urls` config."
1107
- },
1108
- urls: await resolveUrls(config.urls, { path: "sitemap:urls", logger })
1109
- });
1110
- }
1111
- resolvedConfigUrls = true;
1112
- }
1113
- const globalSources = [
1114
- ...userGlobalSources.map((s) => {
1115
- if (typeof s === "string" || Array.isArray(s)) {
1116
- return {
1117
- sourceType: "user",
1118
- fetch: s
1119
- };
1120
- }
1121
- s.sourceType = "user";
1122
- return s;
1123
- }),
1124
- ...(config.excludeAppSources === true ? [] : [
1125
- ...appGlobalSources,
1126
- {
1127
- context: {
1128
- name: "nuxt:pages",
1129
- description: "Generated from your static page files.",
1130
- tips: [
1131
- "Can be disabled with `{ excludeAppSources: ['nuxt:pages'] }`."
1132
- ]
1133
- },
1134
- urls: pageSource
1135
- },
1136
- {
1137
- context: {
1138
- name: "nuxt:route-rules",
1139
- description: "Generated from your route rules config.",
1140
- tips: [
1141
- "Can be disabled with `{ excludeAppSources: ['nuxt:route-rules'] }`."
1142
- ]
1143
- },
1144
- urls: routeRules2
1145
- },
1146
- {
1147
- context: {
1148
- name: "nuxt:prerender",
1149
- description: "Generated at build time when prerendering.",
1150
- tips: [
1151
- "Can be disabled with `{ excludeAppSources: ['nuxt:prerender'] }`."
1152
- ]
1153
- },
1154
- urls: prerenderUrlsFinal
1155
- }
1156
- ]).filter((s) => !config.excludeAppSources.includes(s.context.name) && (!!s.urls?.length || !!s.fetch)).map((s) => {
1157
- s.sourceType = "app";
1158
- return s;
1159
- })
1160
- ];
1161
- return `export const sources = ${JSON.stringify(globalSources, null, 4)}`;
1162
- };
1163
- const extraSitemapModules = typeof config.sitemaps == "object" ? Object.keys(config.sitemaps).filter((n) => n !== "index") : [];
1164
- const sitemapSources = {};
1165
- nitroConfig.virtual[`#sitemap-virtual/child-sources.mjs`] = async () => {
1166
- for (const sitemapName of extraSitemapModules) {
1167
- sitemapSources[sitemapName] = sitemapSources[sitemapName] || [];
1168
- const definition = config.sitemaps[sitemapName];
1169
- if (!sitemapSources[sitemapName].length) {
1170
- if (definition.urls) {
1171
- sitemapSources[sitemapName].push({
1172
- context: {
1173
- name: `sitemaps:${sitemapName}:urls`,
1174
- description: "Set with the `sitemap.urls` config."
1175
- },
1176
- urls: await resolveUrls(definition.urls, { path: `sitemaps:${sitemapName}:urls`, logger })
1177
- });
1178
- }
1179
- sitemapSources[sitemapName].push(
1180
- ...(definition.sources || []).map((s) => {
1181
- if (typeof s === "string" || Array.isArray(s)) {
1182
- return {
1183
- sourceType: "user",
1184
- fetch: s
1185
- };
1186
- }
1187
- s.sourceType = "user";
1188
- return s;
1189
- })
1190
- );
1191
- }
1192
- }
1193
- return `export const sources = ${JSON.stringify(sitemapSources, null, 4)}`;
1194
- };
1195
- });
1196
- if (config.xsl === "/__sitemap__/style.xsl") {
1197
- addServerHandler({
1198
- route: config.xsl,
1199
- handler: resolve("./runtime/server/routes/sitemap.xsl")
1200
- });
1201
- config.xsl = withBase(config.xsl, nuxt.options.app.baseURL);
1202
- if (prerenderSitemap)
1203
- addPrerenderRoutes(config.xsl);
1204
- }
1205
- addServerHandler({
1206
- route: `/${config.sitemapName}`,
1207
- handler: resolve("./runtime/server/routes/sitemap.xml")
1208
- });
1209
- setupPrerenderHandler({ runtimeConfig, logger });
1210
- }
1211
- });
1212
-
1213
- export { module as default };