nuxt-simple-sitemap
Version:
Powerfully flexible XML Sitemaps that integrate seamlessly, for Nuxt.
78 lines (77 loc) • 2.38 kB
JavaScript
import { hasProtocol } from "ufo";
import { fixSlashes } from "site-config-stack/urls";
import { mergeOnKey } from "../../utils-pure.mjs";
function resolve(s, resolvers) {
if (typeof s === "undefined")
return s;
s = typeof s === "string" ? s : s.toString();
if (hasProtocol(s, { acceptRelative: true, strict: false }))
return resolvers.fixSlashes(s);
return resolvers.canonicalUrlResolver(s);
}
export function normaliseSitemapUrls(data, resolvers) {
const entries = data.map((e) => typeof e === "string" ? { loc: e } : e).map((e) => {
e = { ...e };
if (e.url) {
e.loc = e.url;
delete e.url;
}
e.loc = fixSlashes(false, e.loc);
return e;
}).filter(Boolean);
function normaliseEntry(e) {
if (e.lastmod) {
const date = normaliseDate(e.lastmod);
if (date)
e.lastmod = date;
else
delete e.lastmod;
}
if (!e.lastmod)
delete e.lastmod;
e.loc = resolve(e.loc, resolvers);
if (e.alternatives) {
e.alternatives = mergeOnKey(e.alternatives.map((e2) => {
const a = { ...e2 };
if (typeof a.href === "string")
a.href = resolve(a.href, resolvers);
else if (typeof a.href === "object" && a.href)
a.href = resolve(a.href.href, resolvers);
return a;
}), "hreflang");
}
if (e.images) {
e.images = mergeOnKey(e.images.map((i) => {
i = { ...i };
i.loc = resolve(i.loc, resolvers);
return i;
}), "loc");
}
if (e.videos) {
e.videos = e.videos.map((v) => {
v = { ...v };
if (v.content_loc)
v.content_loc = resolve(v.content_loc, resolvers);
return v;
});
}
return e;
}
return mergeOnKey(
entries.map(normaliseEntry).map((e) => ({ ...e, _key: `${e._sitemap || ""}${e.loc}` })),
"_key"
);
}
export function normaliseDate(d) {
if (typeof d === "string") {
d = d.replace("Z", "");
d = d.replace(/\.\d+$/, "");
if (d.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/) || d.match(/^\d{4}-\d{2}-\d{2}$/))
return d;
d = new Date(d);
if (Number.isNaN(d.getTime()))
return false;
}
const z = (n) => `0${n}`.slice(-2);
return `${d.getUTCFullYear()}-${z(d.getUTCMonth() + 1)}-${z(d.getUTCDate())}T${z(d.getUTCHours())}:${z(d.getUTCMinutes())}:${z(d.getUTCSeconds())}+00:00`;
}