the validationlab.eu marketing site: 3 audience pages (en) + legal skeletons, i18n scaffold (25 locales, subdirectory scheme), structured frontmatter blocks, Zoho Flow lead forms with capability tagging + honeypot, sitemap/hreflang/JSON-LD/robots, cookie-gated analytics plumbing
This commit is contained in:
1 parent
95af7107d0
commit
477bf5114f
1076 files changed
+227743
-110
No files matched your search
+10
@@ -0,0 +1,10 @@
|
||||
export declare const SITEMAP_CONFIG_DEFAULTS: {
|
||||
filenameBase: string;
|
||||
entryLimit: number;
|
||||
namespaces: {
|
||||
news: true;
|
||||
xhtml: true;
|
||||
image: true;
|
||||
video: true;
|
||||
};
|
||||
};
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export const SITEMAP_CONFIG_DEFAULTS = {
|
||||
filenameBase: "sitemap",
|
||||
entryLimit: 45e3,
|
||||
namespaces: {
|
||||
news: true,
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true
|
||||
}
|
||||
};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { SitemapItem, SitemapOptions } from './index.js';
|
||||
/** Construct sitemap.xml given a set of URLs */
|
||||
export declare function generateSitemap(pages: string[], finalSiteUrl: string, opts?: SitemapOptions): SitemapItem[];
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { parseI18nUrl } from "./utils/parse-i18n-url.js";
|
||||
/** Construct sitemap.xml given a set of URLs */
|
||||
export function generateSitemap(pages, finalSiteUrl, opts) {
|
||||
const { changefreq, priority, lastmod: lastmodSrc, i18n } = opts ?? {};
|
||||
// TODO: find way to respect <link rel="canonical"> URLs here
|
||||
const urls = [...pages];
|
||||
urls.sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
|
||||
const lastmod = lastmodSrc?.toISOString();
|
||||
// Parse URLs for i18n matching later
|
||||
const { defaultLocale, locales } = i18n ?? {};
|
||||
let getI18nLinks;
|
||||
if (defaultLocale && locales) {
|
||||
getI18nLinks = createGetI18nLinks(urls, defaultLocale, locales, finalSiteUrl);
|
||||
}
|
||||
const urlData = urls.map((url, i) => ({
|
||||
url,
|
||||
links: getI18nLinks?.(i),
|
||||
lastmod,
|
||||
priority,
|
||||
changefreq
|
||||
}));
|
||||
return urlData;
|
||||
}
|
||||
function createGetI18nLinks(urls, defaultLocale, locales, finalSiteUrl) {
|
||||
// `parsedI18nUrls` will have the same length as `urls`, matching correspondingly
|
||||
const parsedI18nUrls = urls.map((url) => parseI18nUrl(url, defaultLocale, locales, finalSiteUrl));
|
||||
// Cache as multiple i18n URLs with the same path will have the same links
|
||||
const i18nPathToLinksCache = new Map();
|
||||
return (urlIndex) => {
|
||||
const i18nUrl = parsedI18nUrls[urlIndex];
|
||||
if (!i18nUrl) {
|
||||
return undefined;
|
||||
}
|
||||
const cached = i18nPathToLinksCache.get(i18nUrl.path);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
// Find all URLs with the same path (without the locale part), e.g. /en/foo and /es/foo
|
||||
const links = [];
|
||||
for (let i = 0; i < parsedI18nUrls.length; i++) {
|
||||
const parsed = parsedI18nUrls[i];
|
||||
if (parsed?.path === i18nUrl.path) {
|
||||
links.push({
|
||||
url: urls[i],
|
||||
lang: locales[parsed.locale]
|
||||
});
|
||||
}
|
||||
}
|
||||
// If 0 or 1 (which is itself), return undefined to not create any links.
|
||||
// We also don't need to cache this as we know there's no other URLs that would've match this.
|
||||
if (links.length <= 1) {
|
||||
return undefined;
|
||||
}
|
||||
i18nPathToLinksCache.set(i18nUrl.path, links);
|
||||
return links;
|
||||
};
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import type { AstroIntegration } from 'astro';
|
||||
import type { EnumChangefreq, LinkItem as LinkItemBase, SitemapItemLoose } from 'sitemap';
|
||||
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 = {
|
||||
filenameBase?: string;
|
||||
filter?(page: string): boolean;
|
||||
customSitemaps?: string[];
|
||||
customPages?: string[];
|
||||
i18n?: {
|
||||
defaultLocale: string;
|
||||
locales: Record<string, string>;
|
||||
};
|
||||
entryLimit?: number;
|
||||
changefreq?: ChangeFreq;
|
||||
lastmod?: Date;
|
||||
priority?: number;
|
||||
serialize?(item: SitemapItem): SitemapItem | Promise<SitemapItem | undefined> | undefined;
|
||||
xslURL?: string;
|
||||
chunks?: Record<string, (item: SitemapItem) => SitemapItem | Promise<SitemapItem | undefined> | undefined>;
|
||||
namespaces?: {
|
||||
news?: boolean;
|
||||
xhtml?: boolean;
|
||||
image?: boolean;
|
||||
video?: boolean;
|
||||
};
|
||||
} | undefined;
|
||||
declare const createPlugin: (options?: SitemapOptions) => AstroIntegration;
|
||||
export default createPlugin;
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ZodError } from "zod/v4";
|
||||
import { generateSitemap } from "./generate-sitemap.js";
|
||||
import { validateOptions } from "./validate-options.js";
|
||||
import { writeSitemap } from "./write-sitemap.js";
|
||||
import { writeSitemapChunk } from "./write-sitemap-chunk.js";
|
||||
export { EnumChangefreq as ChangeFreqEnum } from "sitemap";
|
||||
function formatConfigErrorMessage(err) {
|
||||
const errorList = err.issues.map((issue) => ` ${issue.path.join(".")} ${issue.message + "."}`);
|
||||
return errorList.join("\n");
|
||||
}
|
||||
const PKG_NAME = "@astrojs/sitemap";
|
||||
const STATUS_CODE_PAGES = new Set(["404", "500"]);
|
||||
const isStatusCodePage = (locales) => {
|
||||
const statusPathNames = new Set(locales.flatMap((locale) => [...STATUS_CODE_PAGES].map((page) => `${locale}/${page}`)).concat([...STATUS_CODE_PAGES]));
|
||||
return (pathname) => {
|
||||
if (pathname.endsWith("/")) {
|
||||
pathname = pathname.slice(0, -1);
|
||||
}
|
||||
if (pathname.startsWith("/")) {
|
||||
pathname = pathname.slice(1);
|
||||
}
|
||||
return statusPathNames.has(pathname);
|
||||
};
|
||||
};
|
||||
const createPlugin = (options) => {
|
||||
let _routes;
|
||||
let config;
|
||||
return {
|
||||
name: PKG_NAME,
|
||||
hooks: {
|
||||
"astro:routes:resolved": ({ routes }) => {
|
||||
_routes = routes;
|
||||
},
|
||||
"astro:config:done": async ({ config: cfg }) => {
|
||||
config = cfg;
|
||||
},
|
||||
"astro:build:done": async ({ dir, 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 { filenameBase, filter, customPages, customSitemaps, serialize, entryLimit, chunks } = opts;
|
||||
const outFile = `${filenameBase}-index.xml`;
|
||||
const finalSiteUrl = new URL(config.base, config.site);
|
||||
const shouldIgnoreStatus = isStatusCodePage(Object.keys(opts.i18n?.locales ?? {}));
|
||||
let pageUrls = pages.filter((p) => !shouldIgnoreStatus(p.pathname)).map((p) => {
|
||||
if (p.pathname !== "" && !finalSiteUrl.pathname.endsWith("/")) finalSiteUrl.pathname += "/";
|
||||
if (p.pathname.startsWith("/")) p.pathname = p.pathname.slice(1);
|
||||
const fullPath = finalSiteUrl.pathname + p.pathname;
|
||||
return new URL(fullPath, finalSiteUrl).href;
|
||||
});
|
||||
const addRouteUrl = (urls, r) => {
|
||||
/**
|
||||
* Dynamic URLs have entries with `undefined` pathnames
|
||||
*/
|
||||
if (r.pathname) {
|
||||
if (shouldIgnoreStatus(r.pathname ?? r.pattern)) return;
|
||||
// `finalSiteUrl` may end with a trailing slash
|
||||
// or not because of base paths.
|
||||
let fullPath = finalSiteUrl.pathname;
|
||||
if (fullPath.endsWith("/")) fullPath += r.generate(r.pathname).substring(1);
|
||||
else fullPath += r.generate(r.pathname);
|
||||
const 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);
|
||||
}
|
||||
}
|
||||
};
|
||||
const routeUrls = _routes.reduce((urls, r) => {
|
||||
// Only expose pages, not endpoints or redirects
|
||||
if (r.type !== "page") return urls;
|
||||
addRouteUrl(urls, r);
|
||||
// Include i18n fallback routes (e.g. /fr/ falling back to /en/)
|
||||
for (const fallbackRoute of r.fallbackRoutes ?? []) {
|
||||
addRouteUrl(urls, fallbackRoute);
|
||||
}
|
||||
return urls;
|
||||
}, []);
|
||||
pageUrls = Array.from(new Set([
|
||||
...pageUrls,
|
||||
...routeUrls,
|
||||
...customPages ?? []
|
||||
]));
|
||||
if (filter) {
|
||||
pageUrls = pageUrls.filter((value) => filter(value));
|
||||
}
|
||||
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 = [];
|
||||
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.toString()}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const destDir = fileURLToPath(dir);
|
||||
const lastmod = opts.lastmod?.toISOString();
|
||||
const xslURL = opts.xslURL ? new URL(opts.xslURL, finalSiteUrl).href : undefined;
|
||||
if (chunks) {
|
||||
try {
|
||||
const groupedUrlCollection = new Set();
|
||||
const chunksItem = {};
|
||||
for (const [key, cb] of Object.entries(chunks)) {
|
||||
// Create a new, separate collection for each key
|
||||
const collection = [];
|
||||
for (const item of urlData) {
|
||||
// Await the asynchronous operation
|
||||
const collect = await Promise.resolve(cb(item));
|
||||
if (collect) {
|
||||
collection.push(collect);
|
||||
}
|
||||
}
|
||||
// Assign the specific collection to its key
|
||||
chunksItem[key] = collection;
|
||||
for (const { url } of collection) {
|
||||
groupedUrlCollection.add(url);
|
||||
}
|
||||
}
|
||||
chunksItem["pages"] = urlData.filter((urlDataItem) => !groupedUrlCollection.has(urlDataItem.url));
|
||||
// Process each chunk here
|
||||
await writeSitemapChunk({
|
||||
filenameBase,
|
||||
hostname: finalSiteUrl.href,
|
||||
sitemapHostname: finalSiteUrl.href,
|
||||
sourceData: chunksItem,
|
||||
destinationDir: destDir,
|
||||
publicBasePath: config.base,
|
||||
customSitemaps,
|
||||
limit: entryLimit,
|
||||
xslURL,
|
||||
lastmod,
|
||||
namespaces: opts.namespaces
|
||||
});
|
||||
logger.info(`\`${outFile}\` created at \`${path.relative(process.cwd(), destDir)}\``);
|
||||
return;
|
||||
} catch (err) {
|
||||
logger.error(`Error chunking sitemaps\n${err.toString()}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await writeSitemap({
|
||||
filenameBase,
|
||||
hostname: finalSiteUrl.href,
|
||||
destinationDir: destDir,
|
||||
publicBasePath: config.base,
|
||||
sourceData: urlData,
|
||||
limit: entryLimit,
|
||||
customSitemaps,
|
||||
xslURL,
|
||||
lastmod,
|
||||
namespaces: opts.namespaces
|
||||
});
|
||||
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;
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import { EnumChangefreq as ChangeFreq } from 'sitemap';
|
||||
import * as z from 'zod/v4';
|
||||
export declare const SitemapOptionsSchema: z.ZodDefault<z.ZodObject<{
|
||||
filenameBase: z.ZodPrefault<z.ZodString>;
|
||||
filter: z.ZodOptional<z.ZodFunction<z.ZodTuple<readonly [z.ZodString], null>, z.ZodBoolean>>;
|
||||
customSitemaps: z.ZodOptional<z.ZodArray<z.ZodURL>>;
|
||||
customPages: z.ZodOptional<z.ZodArray<z.ZodURL>>;
|
||||
canonicalURL: z.ZodOptional<z.ZodURL>;
|
||||
xslURL: z.ZodOptional<z.ZodString>;
|
||||
i18n: z.ZodOptional<z.ZodObject<{
|
||||
defaultLocale: z.ZodString;
|
||||
locales: z.ZodRecord<z.ZodString, z.ZodString>;
|
||||
}, z.core.$strip>>;
|
||||
entryLimit: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
||||
serialize: z.ZodOptional<z.ZodFunction<z.ZodTuple<readonly [z.ZodAny], null>, z.ZodAny>>;
|
||||
changefreq: z.ZodOptional<z.ZodEnum<typeof ChangeFreq>>;
|
||||
lastmod: z.ZodOptional<z.ZodDate>;
|
||||
priority: z.ZodOptional<z.ZodNumber>;
|
||||
namespaces: z.ZodDefault<z.ZodOptional<z.ZodObject<{
|
||||
news: z.ZodOptional<z.ZodBoolean>;
|
||||
xhtml: z.ZodOptional<z.ZodBoolean>;
|
||||
image: z.ZodOptional<z.ZodBoolean>;
|
||||
video: z.ZodOptional<z.ZodBoolean>;
|
||||
}, z.core.$strip>>>;
|
||||
chunks: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodFunction<z.ZodTuple<readonly [z.ZodAny], null>, z.ZodAny>>>;
|
||||
}, z.core.$strict>>;
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { EnumChangefreq as ChangeFreq } from "sitemap";
|
||||
import * as z from "zod/v4";
|
||||
import { SITEMAP_CONFIG_DEFAULTS } from "./config-defaults.js";
|
||||
const localeKeySchema = z.string().min(1);
|
||||
export const SitemapOptionsSchema = z.object({
|
||||
filenameBase: z.string().prefault(SITEMAP_CONFIG_DEFAULTS.filenameBase),
|
||||
filter: z.function({
|
||||
input: [z.string()],
|
||||
output: z.boolean()
|
||||
}).optional(),
|
||||
customSitemaps: z.array(z.url()).optional(),
|
||||
customPages: z.array(z.url()).optional(),
|
||||
canonicalURL: z.url().optional(),
|
||||
xslURL: z.string().optional(),
|
||||
i18n: z.object({
|
||||
defaultLocale: localeKeySchema,
|
||||
locales: z.record(localeKeySchema, z.string().min(2).regex(/^[a-zA-Z\-]+$/gm, { message: "Only English alphabet symbols and hyphen allowed" }))
|
||||
}).refine((val) => !val || Object.hasOwn(val.locales, val.defaultLocale), { message: "`defaultLocale` must exist in `locales` keys" }).optional(),
|
||||
entryLimit: z.number().nonnegative().optional().default(SITEMAP_CONFIG_DEFAULTS.entryLimit),
|
||||
serialize: z.function({
|
||||
input: [z.any()],
|
||||
output: z.any()
|
||||
}).optional(),
|
||||
changefreq: z.enum(ChangeFreq).optional(),
|
||||
lastmod: z.date().optional(),
|
||||
priority: z.number().min(0).max(1).optional(),
|
||||
namespaces: z.object({
|
||||
news: z.boolean().optional(),
|
||||
xhtml: z.boolean().optional(),
|
||||
image: z.boolean().optional(),
|
||||
video: z.boolean().optional()
|
||||
}).optional().default(SITEMAP_CONFIG_DEFAULTS.namespaces),
|
||||
chunks: z.record(z.string(), z.function({
|
||||
input: [z.any()],
|
||||
output: z.any()
|
||||
})).optional()
|
||||
}).strict().default(SITEMAP_CONFIG_DEFAULTS);
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import type { SitemapItem } from '../index.js';
|
||||
/**
|
||||
* Returns the most recent `lastmod` among the given sitemap items as an
|
||||
* ISO 8601 string, or `undefined` when none of them carry a valid `lastmod`.
|
||||
*
|
||||
* Used to stamp each `<sitemap>` entry in the sitemap index with the freshest
|
||||
* date present in the child sitemap it points to, so search engines can tell
|
||||
* which child sitemaps actually changed without refetching all of them.
|
||||
*/
|
||||
export declare function getLatestLastmod(items: SitemapItem[]): string | undefined;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Returns the most recent `lastmod` among the given sitemap items as an
|
||||
* ISO 8601 string, or `undefined` when none of them carry a valid `lastmod`.
|
||||
*
|
||||
* Used to stamp each `<sitemap>` entry in the sitemap index with the freshest
|
||||
* date present in the child sitemap it points to, so search engines can tell
|
||||
* which child sitemaps actually changed without refetching all of them.
|
||||
*/
|
||||
export function getLatestLastmod(items) {
|
||||
let latest;
|
||||
for (const item of items) {
|
||||
if (!item.lastmod) continue;
|
||||
const time = new Date(item.lastmod).getTime();
|
||||
if (Number.isNaN(time)) continue;
|
||||
if (latest === undefined || time > latest) {
|
||||
latest = time;
|
||||
}
|
||||
}
|
||||
return latest === undefined ? undefined : new Date(latest).toISOString();
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
interface ParsedI18nUrl {
|
||||
locale: string;
|
||||
path: string;
|
||||
}
|
||||
export declare function parseI18nUrl(url: string, defaultLocale: string, locales: Record<string, string>, base: string): ParsedI18nUrl | undefined;
|
||||
export {};
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
// NOTE: The parameters have been schema-validated with Zod
|
||||
export function parseI18nUrl(url, defaultLocale, locales, base) {
|
||||
if (!url.startsWith(base)) {
|
||||
return undefined;
|
||||
}
|
||||
let s = url.slice(base.length);
|
||||
// Handle root URL
|
||||
if (!s || s === "/") {
|
||||
return {
|
||||
locale: defaultLocale,
|
||||
path: "/"
|
||||
};
|
||||
}
|
||||
if (s[0] !== "/") {
|
||||
s = "/" + s;
|
||||
}
|
||||
// Get locale from path, e.g.
|
||||
// "/en-US/" -> "en-US"
|
||||
// "/en-US/foo" -> "en-US"
|
||||
const locale = s.split("/")[1];
|
||||
// `Object.hasOwn`, not `in`: a page such as `/constructor/` or `/toString/`
|
||||
// would otherwise match a property of `Object.prototype`.
|
||||
if (Object.hasOwn(locales, locale)) {
|
||||
// "/en-US/foo" -> "/foo"
|
||||
let path = s.slice(1 + locale.length);
|
||||
if (!path) {
|
||||
path = "/";
|
||||
}
|
||||
return {
|
||||
locale,
|
||||
path
|
||||
};
|
||||
}
|
||||
return {
|
||||
locale: defaultLocale,
|
||||
path: s
|
||||
};
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import * as z from "zod/v4";
|
||||
import { SitemapOptionsSchema } from "./schema.js";
|
||||
// @internal
|
||||
export const validateOptions = (site, opts) => {
|
||||
const result = SitemapOptionsSchema.parse(opts);
|
||||
z.object({
|
||||
site: z.string().optional(),
|
||||
canonicalURL: z.string().optional()
|
||||
}).refine((options) => options.site || options.canonicalURL, { message: "Required `site` astro.config option or `canonicalURL` integration option" }).parse({
|
||||
site,
|
||||
canonicalURL: result.canonicalURL
|
||||
});
|
||||
return result;
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import type { SitemapItem } from './index.js';
|
||||
type WriteSitemapChunkConfig = {
|
||||
filenameBase: string;
|
||||
hostname: string;
|
||||
sitemapHostname?: string;
|
||||
sourceData: Record<string, SitemapItem[]>;
|
||||
destinationDir: string;
|
||||
customSitemaps?: string[];
|
||||
publicBasePath?: string;
|
||||
limit?: number;
|
||||
xslURL?: string;
|
||||
lastmod?: string;
|
||||
namespaces?: {
|
||||
news?: boolean;
|
||||
xhtml?: boolean;
|
||||
image?: boolean;
|
||||
video?: boolean;
|
||||
};
|
||||
};
|
||||
export declare function writeSitemapChunk({ filenameBase, hostname, sitemapHostname, sourceData, destinationDir, limit, customSitemaps, publicBasePath, xslURL: xslUrl, lastmod, namespaces, }: WriteSitemapChunkConfig): Promise<void>;
|
||||
export {};
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { normalize, resolve } from "node:path";
|
||||
import { pipeline, Readable } from "node:stream";
|
||||
import { promisify } from "node:util";
|
||||
import { SitemapAndIndexStream, SitemapIndexStream, SitemapStream } from "sitemap";
|
||||
import { getLatestLastmod } from "./utils/lastmod.js";
|
||||
// adapted from sitemap.js/sitemap-simple
|
||||
export async function writeSitemapChunk({ filenameBase, hostname, sitemapHostname = hostname, sourceData, destinationDir, limit = 5e4, customSitemaps = [], publicBasePath = "./", xslURL: xslUrl, lastmod, namespaces = {
|
||||
news: true,
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true
|
||||
} }) {
|
||||
await mkdir(destinationDir, { recursive: true });
|
||||
// Normalize publicBasePath
|
||||
let normalizedPublicBasePath = publicBasePath;
|
||||
if (!normalizedPublicBasePath.endsWith("/")) {
|
||||
normalizedPublicBasePath += "/";
|
||||
}
|
||||
// Array to collect all sitemap URLs for the index
|
||||
const sitemapUrls = [];
|
||||
// Process each chunk separately
|
||||
for (const [chunkName, items] of Object.entries(sourceData)) {
|
||||
const sitemapAndIndexStream = new SitemapAndIndexStream({
|
||||
limit,
|
||||
xslUrl,
|
||||
getSitemapStream: (i) => {
|
||||
const sitemapStream = new SitemapStream({
|
||||
hostname,
|
||||
xslUrl,
|
||||
// Custom namespace handling
|
||||
xmlns: {
|
||||
news: namespaces?.news !== false,
|
||||
xhtml: namespaces?.xhtml !== false,
|
||||
image: namespaces?.image !== false,
|
||||
video: namespaces?.video !== false
|
||||
}
|
||||
});
|
||||
const path = `./${filenameBase}-${chunkName}-${i}.xml`;
|
||||
const writePath = resolve(destinationDir, path);
|
||||
const publicPath = normalize(normalizedPublicBasePath + path);
|
||||
const stream = sitemapStream.pipe(createWriteStream(writePath));
|
||||
const url = new URL(publicPath, sitemapHostname).toString();
|
||||
// Stamp this index entry with the freshest lastmod among the
|
||||
// URLs that land in this file (items are written in order,
|
||||
// `limit` per file), falling back to the global `lastmod`.
|
||||
const fileLastmod = getLatestLastmod(items.slice(i * limit, (i + 1) * limit)) ?? lastmod;
|
||||
// Collect this sitemap URL for the index
|
||||
sitemapUrls.push({
|
||||
url,
|
||||
lastmod: fileLastmod
|
||||
});
|
||||
return [
|
||||
{
|
||||
url,
|
||||
lastmod: fileLastmod
|
||||
},
|
||||
sitemapStream,
|
||||
stream
|
||||
];
|
||||
}
|
||||
});
|
||||
// Create a readable stream from this chunk's items
|
||||
const dataStream = Readable.from(items);
|
||||
// Write this chunk's sitemap(s)
|
||||
await promisify(pipeline)(dataStream, sitemapAndIndexStream);
|
||||
}
|
||||
// Now create the sitemap index with all the generated sitemaps
|
||||
const indexStream = new SitemapIndexStream({ xslUrl });
|
||||
const indexPath = resolve(destinationDir, `./${filenameBase}-index.xml`);
|
||||
const indexWriteStream = createWriteStream(indexPath);
|
||||
// Add custom sitemaps to the index
|
||||
for (const url of customSitemaps) {
|
||||
indexStream.write({
|
||||
url,
|
||||
lastmod
|
||||
});
|
||||
}
|
||||
// Add all generated sitemaps to the index
|
||||
for (const sitemapUrl of sitemapUrls) {
|
||||
indexStream.write(sitemapUrl);
|
||||
}
|
||||
indexStream.end();
|
||||
return await promisify(pipeline)(indexStream, indexWriteStream);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import type { SitemapItem } from './index.js';
|
||||
type WriteSitemapConfig = {
|
||||
filenameBase: string;
|
||||
hostname: string;
|
||||
sitemapHostname?: string;
|
||||
customSitemaps?: string[];
|
||||
sourceData: SitemapItem[];
|
||||
destinationDir: string;
|
||||
publicBasePath?: string;
|
||||
limit?: number;
|
||||
xslURL?: string;
|
||||
lastmod?: string;
|
||||
namespaces?: {
|
||||
news?: boolean;
|
||||
xhtml?: boolean;
|
||||
image?: boolean;
|
||||
video?: boolean;
|
||||
};
|
||||
};
|
||||
export declare function writeSitemap({ filenameBase, hostname, sitemapHostname, sourceData, destinationDir, limit, customSitemaps, publicBasePath, xslURL: xslUrl, lastmod, namespaces, }: WriteSitemapConfig): Promise<void>;
|
||||
export {};
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { normalize, resolve } from "node:path";
|
||||
import { pipeline, Readable } from "node:stream";
|
||||
import { promisify } from "node:util";
|
||||
import { SitemapAndIndexStream, SitemapIndexStream, SitemapStream } from "sitemap";
|
||||
import { getLatestLastmod } from "./utils/lastmod.js";
|
||||
// adapted from sitemap.js/sitemap-simple
|
||||
export async function writeSitemap({ filenameBase, hostname, sitemapHostname = hostname, sourceData, destinationDir, limit = 5e4, customSitemaps = [], publicBasePath = "./", xslURL: xslUrl, lastmod, namespaces = {
|
||||
news: true,
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true
|
||||
} }) {
|
||||
await mkdir(destinationDir, { recursive: true });
|
||||
const sitemapAndIndexStream = new SitemapAndIndexStream({
|
||||
limit,
|
||||
xslUrl,
|
||||
getSitemapStream: (i) => {
|
||||
const sitemapStream = new SitemapStream({
|
||||
hostname,
|
||||
xslUrl,
|
||||
// Custom namespace handling
|
||||
xmlns: {
|
||||
news: namespaces?.news !== false,
|
||||
xhtml: namespaces?.xhtml !== false,
|
||||
image: namespaces?.image !== false,
|
||||
video: namespaces?.video !== false
|
||||
}
|
||||
});
|
||||
const path = `./${filenameBase}-${i}.xml`;
|
||||
const writePath = resolve(destinationDir, path);
|
||||
if (!publicBasePath.endsWith("/")) {
|
||||
publicBasePath += "/";
|
||||
}
|
||||
const publicPath = normalize(publicBasePath + path);
|
||||
const stream = sitemapStream.pipe(createWriteStream(writePath));
|
||||
const url = new URL(publicPath, sitemapHostname).toString();
|
||||
// Stamp this index entry with the freshest lastmod among the URLs
|
||||
// that land in this file (items are written in order, `limit` per
|
||||
// file), falling back to the configured global `lastmod`.
|
||||
const fileLastmod = getLatestLastmod(sourceData.slice(i * limit, (i + 1) * limit)) ?? lastmod;
|
||||
return [
|
||||
{
|
||||
url,
|
||||
lastmod: fileLastmod
|
||||
},
|
||||
sitemapStream,
|
||||
stream
|
||||
];
|
||||
}
|
||||
});
|
||||
const src = Readable.from(sourceData);
|
||||
const indexPath = resolve(destinationDir, `./${filenameBase}-index.xml`);
|
||||
for (const url of customSitemaps) {
|
||||
SitemapIndexStream.prototype._transform.call(sitemapAndIndexStream, {
|
||||
url,
|
||||
lastmod
|
||||
}, "utf8", () => {});
|
||||
}
|
||||
return promisify(pipeline)(src, sitemapAndIndexStream, createWriteStream(indexPath));
|
||||
}
|
||||
Reference in new issue
Block a user