@xexr/blog-platform 1.0.12 → 1.0.13

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.
@@ -0,0 +1,422 @@
1
+ import { PublishedArticle, PublishedSite, PublishedAuthor } from './types/index.mjs';
2
+
3
+ /**
4
+ * SEO utilities for canonical URL generation and validation.
5
+ *
6
+ * These utilities ensure proper canonical URL structure for SEO optimization,
7
+ * preventing duplicate content issues and improving search engine indexing.
8
+ */
9
+
10
+ /**
11
+ * Configuration options for canonical URL generation.
12
+ */
13
+ interface CanonicalUrlOptions {
14
+ /** Whether to force HTTPS protocol (default: true) */
15
+ forceHttps?: boolean;
16
+ /** Whether to remove trailing slashes (default: true) */
17
+ removeTrailingSlash?: boolean;
18
+ /** Custom domain override (uses site.domain if not provided) */
19
+ domain?: string;
20
+ /** Custom path prefix (default: '/blog') */
21
+ pathPrefix?: string;
22
+ }
23
+ /**
24
+ * Normalizes a domain by ensuring proper protocol and removing trailing slashes.
25
+ *
26
+ * @param domain - The domain to normalize
27
+ * @param forceHttps - Whether to force HTTPS protocol
28
+ * @returns The normalized domain
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * normalizeDomain('example.com') // 'https://example.com'
33
+ * normalizeDomain('http://example.com/') // 'https://example.com'
34
+ * normalizeDomain('https://example.com', false) // 'https://example.com'
35
+ * ```
36
+ */
37
+ declare function normalizeDomain(domain: string, forceHttps?: boolean): string;
38
+ /**
39
+ * Validates and normalizes a slug for URL usage.
40
+ *
41
+ * @param slug - The slug to validate and normalize
42
+ * @returns The normalized slug
43
+ * @throws Error if slug is invalid
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * normalizeSlug('hello-world') // 'hello-world'
48
+ * normalizeSlug('Hello World!') // throws Error
49
+ * normalizeSlug('hello--world') // 'hello-world'
50
+ * ```
51
+ */
52
+ declare function normalizeSlug(slug: string): string;
53
+ /**
54
+ * Generates a canonical URL for an article.
55
+ *
56
+ * @param article - The published article
57
+ * @param options - Configuration options for URL generation
58
+ * @returns The canonical URL
59
+ * @throws Error if article or site data is invalid
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const article = {
64
+ * slug: 'hello-world',
65
+ * site: { domain: 'example.com' },
66
+ * // ... other fields
67
+ * };
68
+ *
69
+ * generateCanonicalUrl(article)
70
+ * // 'https://example.com/blog/hello-world'
71
+ *
72
+ * generateCanonicalUrl(article, { pathPrefix: '/posts' })
73
+ * // 'https://example.com/posts/hello-world'
74
+ * ```
75
+ */
76
+ declare function generateCanonicalUrl(article: PublishedArticle, options?: CanonicalUrlOptions): string;
77
+ /**
78
+ * Generates a canonical URL for an article from site and slug data.
79
+ * Useful when you don't have a full PublishedArticle object.
80
+ *
81
+ * @param site - The published site
82
+ * @param slug - The article slug
83
+ * @param options - Configuration options for URL generation
84
+ * @returns The canonical URL
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const site = { domain: 'example.com', ... };
89
+ * generateCanonicalUrlFromSlug(site, 'hello-world')
90
+ * // 'https://example.com/blog/hello-world'
91
+ * ```
92
+ */
93
+ declare function generateCanonicalUrlFromSlug(site: PublishedSite, slug: string, options?: CanonicalUrlOptions): string;
94
+ /**
95
+ * Validates if a URL is a valid canonical URL format.
96
+ *
97
+ * @param url - The URL to validate
98
+ * @returns True if the URL is valid for canonical use
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * isValidCanonicalUrl('https://example.com/blog/hello-world') // true
103
+ * isValidCanonicalUrl('http://example.com/blog/hello-world') // true
104
+ * isValidCanonicalUrl('example.com/blog/hello-world') // false (missing protocol)
105
+ * isValidCanonicalUrl('https://example.com/blog/hello world') // false (spaces)
106
+ * ```
107
+ */
108
+ declare function isValidCanonicalUrl(url: string): boolean;
109
+ /**
110
+ * Extracts the base URL (protocol + hostname + port) from a canonical URL.
111
+ *
112
+ * @param canonicalUrl - The canonical URL
113
+ * @returns The base URL
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * getBaseUrl('https://example.com/blog/hello-world') // 'https://example.com'
118
+ * getBaseUrl('https://blog.example.com:8080/posts/test') // 'https://blog.example.com:8080'
119
+ * ```
120
+ */
121
+ declare function getBaseUrl(canonicalUrl: string): string;
122
+ /**
123
+ * Updates an article's canonical URL in its meta field.
124
+ *
125
+ * @param article - The article to update
126
+ * @param options - Configuration options for URL generation
127
+ * @returns A new article object with updated canonical URL
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const updatedArticle = updateArticleCanonicalUrl(article);
132
+ * console.log(updatedArticle.meta.canonicalUrl); // Generated canonical URL
133
+ * ```
134
+ */
135
+ declare function updateArticleCanonicalUrl(article: PublishedArticle, options?: CanonicalUrlOptions): PublishedArticle;
136
+
137
+ /**
138
+ * Next.js-compatible sitemap generation utilities for blog platform integration.
139
+ *
140
+ * These utilities generate sitemap entries that follow Next.js MetadataRoute.Sitemap
141
+ * conventions, allowing seamless integration with existing Next.js applications.
142
+ *
143
+ * @example Integration with existing Next.js sitemap:
144
+ * ```typescript
145
+ * // app/sitemap.ts
146
+ * import { generateBlogSitemapEntries } from '@xexr/blog-platform';
147
+ * import type { MetadataRoute } from 'next';
148
+ *
149
+ * export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
150
+ * // Your existing routes
151
+ * const staticRoutes = [
152
+ * { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },
153
+ * { url: 'https://yoursite.com/about', lastModified: new Date(), priority: 0.8 }
154
+ * ];
155
+ *
156
+ * // Blog platform entries
157
+ * const blogEntries = await generateBlogSitemapEntries(blogConfig);
158
+ *
159
+ * return [...staticRoutes, ...blogEntries];
160
+ * }
161
+ * ```
162
+ */
163
+
164
+ /**
165
+ * Configuration options for sitemap generation.
166
+ */
167
+ interface SitemapOptions {
168
+ /** Canonical URL configuration */
169
+ canonical?: CanonicalUrlOptions;
170
+ /** Whether to include author pages in sitemap */
171
+ includeAuthorPages?: boolean;
172
+ /** Whether to include topic pages in sitemap */
173
+ includeTopicPages?: boolean;
174
+ /** Whether to include pagination pages in sitemap */
175
+ includePaginationPages?: boolean;
176
+ /** Number of articles per page for pagination calculation */
177
+ articlesPerPage?: number;
178
+ /** Maximum number of sitemap entries (defaults to 50,000 per Google guidelines) */
179
+ maxEntries?: number;
180
+ /** Change frequency for different page types */
181
+ changeFrequency?: {
182
+ /** Change frequency for blog home page */
183
+ homePage?: SitemapChangeFreq;
184
+ /** Change frequency for article pages */
185
+ articles?: SitemapChangeFreq;
186
+ /** Change frequency for author pages */
187
+ authorPages?: SitemapChangeFreq;
188
+ /** Change frequency for topic index and archive pages */
189
+ topicPages?: SitemapChangeFreq;
190
+ /** Change frequency for pagination pages */
191
+ paginationPages?: SitemapChangeFreq;
192
+ };
193
+ /** Priority values for different page types */
194
+ priority?: {
195
+ /** Priority for blog home page (0.0-1.0) */
196
+ homePage?: number;
197
+ /** Priority for article pages (0.0-1.0) */
198
+ articles?: number;
199
+ /** Priority for author pages (0.0-1.0) */
200
+ authorPages?: number;
201
+ /** Priority for topic index and archive pages (0.0-1.0) */
202
+ topicPages?: number;
203
+ /** Priority for pagination pages (0.0-1.0) */
204
+ paginationPages?: number;
205
+ };
206
+ }
207
+ /**
208
+ * Valid sitemap change frequency values as per XML sitemap standard.
209
+ */
210
+ type SitemapChangeFreq = "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
211
+ /**
212
+ * Next.js MetadataRoute.Sitemap compatible entry.
213
+ * This matches the expected format for Next.js sitemap generation.
214
+ */
215
+ interface NextjsSitemapEntry {
216
+ /** The URL of the page */
217
+ url: string;
218
+ /** Last modification date */
219
+ lastModified?: string | Date;
220
+ /** Change frequency hint for search engines */
221
+ changeFrequency?: SitemapChangeFreq;
222
+ /** Priority relative to other URLs on the site (0.0-1.0) */
223
+ priority?: number;
224
+ /** Alternate language versions (for i18n) */
225
+ alternates?: {
226
+ languages?: Record<string, string>;
227
+ };
228
+ }
229
+ /**
230
+ * Legacy XML sitemap entry format (for backward compatibility).
231
+ * @deprecated Use NextjsSitemapEntry for new implementations
232
+ */
233
+ interface SitemapEntry {
234
+ /** The URL of the page */
235
+ loc: string;
236
+ /** Last modification date as ISO 8601 string */
237
+ lastmod?: string;
238
+ /** Change frequency hint for search engines */
239
+ changefreq?: SitemapChangeFreq;
240
+ /** Priority relative to other URLs on the site (0.0-1.0) */
241
+ priority?: number;
242
+ }
243
+ /**
244
+ * Complete sitemap data structure.
245
+ */
246
+ interface SitemapData {
247
+ /** All URL entries in the sitemap */
248
+ entries: SitemapEntry[];
249
+ /** Total number of entries */
250
+ totalEntries: number;
251
+ /** Whether the sitemap was truncated due to size limits */
252
+ truncated: boolean;
253
+ /** Generation timestamp */
254
+ generatedAt: string;
255
+ /** Base URL used for canonical URL generation */
256
+ baseUrl: string;
257
+ }
258
+ /**
259
+ * Generates Next.js-compatible sitemap entries for blog platform integration.
260
+ *
261
+ * @param site - The published site information
262
+ * @param articles - Array of published articles
263
+ * @param authors - Array of published authors (optional)
264
+ * @param options - Sitemap generation options
265
+ * @returns Array of Next.js MetadataRoute.Sitemap compatible entries
266
+ *
267
+ * @example
268
+ * ```typescript
269
+ * // In your Next.js app/sitemap.ts file:
270
+ * import { generateBlogSitemapEntries } from '@xexr/blog-platform';
271
+ * import type { MetadataRoute } from 'next';
272
+ *
273
+ * export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
274
+ * const blogEntries = await generateBlogSitemapEntries(site, articles, authors, {
275
+ * includeAuthorPages: true,
276
+ * includePaginationPages: true,
277
+ * changeFrequency: { articles: 'monthly' }
278
+ * });
279
+ *
280
+ * return [
281
+ * // Your existing site routes
282
+ * { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },
283
+ * { url: 'https://yoursite.com/about', lastModified: new Date() },
284
+ * // Blog entries
285
+ * ...blogEntries
286
+ * ];
287
+ * }
288
+ * ```
289
+ */
290
+ declare function generateBlogSitemapEntries(site: PublishedSite, articles: readonly PublishedArticle[], authors?: readonly PublishedAuthor[], options?: SitemapOptions): Promise<NextjsSitemapEntry[]>;
291
+ /**
292
+ * Legacy sitemap generation for backward compatibility.
293
+ * @deprecated Use generateBlogSitemapEntries for Next.js integration
294
+ *
295
+ * @param site - The published site information
296
+ * @param articles - Array of published articles
297
+ * @param authors - Array of published authors (optional)
298
+ * @param options - Sitemap generation options
299
+ * @returns Complete sitemap data
300
+ */
301
+ declare function generateSitemap(site: PublishedSite, articles: readonly PublishedArticle[], authors?: readonly PublishedAuthor[], options?: SitemapOptions): SitemapData;
302
+ /**
303
+ * Converts sitemap data to XML format.
304
+ *
305
+ * @param sitemapData - The sitemap data to convert
306
+ * @returns XML string in sitemap format
307
+ *
308
+ * @example
309
+ * ```typescript
310
+ * const sitemap = generateSitemap(site, articles);
311
+ * const xmlString = sitemapToXml(sitemap);
312
+ * // Use in API route response
313
+ * ```
314
+ */
315
+ declare function sitemapToXml(sitemapData: SitemapData): string;
316
+ /**
317
+ * Generates a sitemap index for large blogs that need multiple sitemaps.
318
+ *
319
+ * @param sitemaps - Array of sitemap information
320
+ * @param baseUrl - Base URL for the site
321
+ * @returns XML string for sitemap index
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * const sitemapIndex = generateSitemapIndex([
326
+ * { url: 'https://example.com/sitemap-articles.xml', lastmod: '2023-01-01T00:00:00Z' },
327
+ * { url: 'https://example.com/sitemap-authors.xml', lastmod: '2023-01-01T00:00:00Z' }
328
+ * ], 'https://example.com');
329
+ * ```
330
+ */
331
+ declare function generateSitemapIndex(sitemaps: readonly {
332
+ url: string;
333
+ lastmod?: string;
334
+ }[], _baseUrl: string): string;
335
+ /**
336
+ * Validates sitemap data for compliance with search engine guidelines.
337
+ *
338
+ * @param sitemapData - The sitemap data to validate
339
+ * @returns Validation results with errors and warnings
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * const sitemap = generateSitemap(site, articles);
344
+ * const validation = validateSitemap(sitemap);
345
+ *
346
+ * if (validation.errors.length > 0) {
347
+ * console.error('Sitemap errors:', validation.errors);
348
+ * }
349
+ * ```
350
+ */
351
+ declare function validateSitemap(sitemapData: SitemapData): {
352
+ valid: boolean;
353
+ errors: string[];
354
+ warnings: string[];
355
+ };
356
+ /**
357
+ * Creates a separate sitemap specifically for blog content.
358
+ * Useful for large sites that need to split sitemaps by content type.
359
+ *
360
+ * @param site - The published site information
361
+ * @param articles - Array of published articles
362
+ * @param authors - Array of published authors (optional)
363
+ * @param options - Sitemap generation options
364
+ * @returns Next.js sitemap function
365
+ *
366
+ * @example
367
+ * ```typescript
368
+ * // app/blog-sitemap/route.ts - separate blog sitemap endpoint
369
+ * import { createBlogSitemapRoute } from '@xexr/blog-platform';
370
+ *
371
+ * export const GET = createBlogSitemapRoute(site, articles, authors, {
372
+ * includeAuthorPages: true,
373
+ * articlesPerPage: 20
374
+ * });
375
+ * ```
376
+ */
377
+ declare function createBlogSitemapRoute(site: PublishedSite, articles: readonly PublishedArticle[], authors?: readonly PublishedAuthor[], options?: SitemapOptions): () => Promise<Response>;
378
+ /**
379
+ * Configuration interface for blog data fetching.
380
+ * Used to fetch blog data for sitemap generation.
381
+ */
382
+ interface BlogSitemapConfig {
383
+ /** Static host app routes to include before Bloggy routes */
384
+ staticRoutes?: readonly NextjsSitemapEntry[];
385
+ /** Function to fetch static host app routes */
386
+ getStaticRoutes?: () => Promise<readonly NextjsSitemapEntry[]>;
387
+ /** Function to fetch site data */
388
+ getSite: () => Promise<PublishedSite>;
389
+ /** Function to fetch published articles */
390
+ getArticles: () => Promise<readonly PublishedArticle[]>;
391
+ /** Function to fetch authors (optional) */
392
+ getAuthors?: () => Promise<readonly PublishedAuthor[]>;
393
+ /** Sitemap generation options */
394
+ options?: SitemapOptions;
395
+ }
396
+ /**
397
+ * Higher-order function that creates a Next.js sitemap function with data fetching.
398
+ * Ideal for dynamic blog content that needs to be fetched at sitemap generation time.
399
+ *
400
+ * @param config - Configuration for fetching blog data
401
+ * @returns Next.js sitemap function
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * // app/sitemap.ts
406
+ * import { createDynamicBlogSitemap } from '@xexr/blog-platform';
407
+ * import { getBlogData } from './lib/blog';
408
+ *
409
+ * export default createDynamicBlogSitemap({
410
+ * getSite: () => getBlogData().site,
411
+ * getArticles: () => getBlogData().articles,
412
+ * getAuthors: () => getBlogData().authors,
413
+ * options: {
414
+ * includeAuthorPages: true,
415
+ * changeFrequency: { articles: 'weekly' }
416
+ * }
417
+ * });
418
+ * ```
419
+ */
420
+ declare function createDynamicBlogSitemap(config: BlogSitemapConfig): () => Promise<NextjsSitemapEntry[]>;
421
+
422
+ export { type BlogSitemapConfig as B, type CanonicalUrlOptions as C, type NextjsSitemapEntry as N, type SitemapChangeFreq as S, type SitemapData as a, type SitemapEntry as b, type SitemapOptions as c, createBlogSitemapRoute as d, createDynamicBlogSitemap as e, generateCanonicalUrl as f, generateBlogSitemapEntries as g, generateCanonicalUrlFromSlug as h, generateSitemap as i, generateSitemapIndex as j, getBaseUrl as k, isValidCanonicalUrl as l, normalizeSlug as m, normalizeDomain as n, sitemapToXml as s, updateArticleCanonicalUrl as u, validateSitemap as v };
@@ -0,0 +1,2 @@
1
+ import './types/index.mjs';
2
+ export { B as BlogSitemapConfig, N as NextjsSitemapEntry, S as SitemapChangeFreq, a as SitemapData, b as SitemapEntry, c as SitemapOptions, d as createBlogSitemapRoute, e as createDynamicBlogSitemap, g as generateBlogSitemapEntries, i as generateSitemap, j as generateSitemapIndex, s as sitemapToXml, v as validateSitemap } from './sitemap-Dz9DB7py.mjs';
@@ -0,0 +1,2 @@
1
+ import './types/index.js';
2
+ export { B as BlogSitemapConfig, N as NextjsSitemapEntry, S as SitemapChangeFreq, a as SitemapData, b as SitemapEntry, c as SitemapOptions, d as createBlogSitemapRoute, e as createDynamicBlogSitemap, g as generateBlogSitemapEntries, i as generateSitemap, j as generateSitemapIndex, s as sitemapToXml, v as validateSitemap } from './sitemap-BPTdXb9C.js';
@@ -0,0 +1,6 @@
1
+ 'use strict';function O(e){let t=new Map;for(let r of e)r.author?.slug&&t.set(r.author.slug,q(t.get(r.author.slug),r.author));return Array.from(t.values()).sort((r,i)=>r.name.localeCompare(i.name))}function q(e,t){return e?{...e,bio:e.bio??t.bio,avatarUrl:e.avatarUrl??t.avatarUrl,pronouns:e.pronouns??t.pronouns,socialLinks:e.socialLinks??t.socialLinks,toneAdjectives:e.toneAdjectives.length>0?e.toneAdjectives:t.toneAdjectives}:t}function x(e,t=true){let r=e.trim();return r=r.replace(/\/+$/,""),/^https?:\/\//.exec(r)||(r=`${t?"https":"http"}://${r}`),t&&r.startsWith("http://")&&(r=r.replace("http://","https://")),r}function F(e){let t=e.trim();if(!t)throw new Error("Slug cannot be empty");if(!/^[a-z0-9-]+$/.test(t))throw new Error("Slug can only contain lowercase letters, numbers, and hyphens");let i=t.replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!i)throw new Error("Slug cannot consist only of hyphens");return i}function _(e,t={}){let{forceHttps:r=true,removeTrailingSlash:i=true,domain:o=e.site.domain,pathPrefix:n="/blog"}=t;if(!o)throw new Error("Domain is required for canonical URL generation");if(!e.slug)throw new Error("Article slug is required for canonical URL generation");let l=x(o,r),u=F(e.slug),c=n.replace(/^(?!\/)/,"/").replace(/\/+$/,""),a=`${l}${c}/${u}`;return i&&(a=a.replace(/\/+$/,"")),a}function T(e){let t=new Map;for(let r of e)for(let i of r.topics??[])t.has(i.slug)||t.set(i.slug,i);return Array.from(t.values()).sort((r,i)=>r.name.localeCompare(i.name))}function L(e="/blog"){let t=e.trim();return !t||t==="/"?"":t.replace(/^(?!\/)/,"/").replace(/\/+$/,"")}function b(e,t){let r=L(e),i=t?.replace(/^\/+/,"").replace(/\/+$/,"");return i?`${r}/${i}`.replace(/\/+/g,"/"):r||"/"}function v(e,t){return b(e,`authors/${t}`)}async function U(e,t,r=[],i={}){let{includeAuthorPages:o=true,includeTopicPages:n=true,includePaginationPages:l=true,articlesPerPage:u=10,maxEntries:c=5e4,changeFrequency:a={},priority:g={}}=i,s=[],m=x(i.canonical?.domain??e.domain,i.canonical?.forceHttps??true),f=i.canonical?.pathPrefix??"/blog",R=r.length>0?r:O(t),y=T([...t]);if(s.push({url:`${m}${f}`,lastModified:P(t),changeFrequency:a.homePage??"daily",priority:g.homePage??1}),t.forEach(p=>{if(s.length>=c)return;let d=_(p,i.canonical);s.push({url:d,lastModified:p.updatedAt,changeFrequency:a.articles??"monthly",priority:g.articles??.8});}),n&&y.length>0&&(s.length<c&&s.push({url:`${m}${b(f,"topics")}`,lastModified:P(t),changeFrequency:a.topicPages??"weekly",priority:g.topicPages??.6}),y.forEach(p=>{if(s.length>=c)return;let d=t.filter(S=>(S.topics??[]).some(h=>h.slug===p.slug));s.push({url:`${m}${b(f,`topics/${p.slug}`)}`,lastModified:P(d),changeFrequency:a.topicPages??"weekly",priority:g.topicPages??.6});})),o&&R.length>0&&(s.length<c&&s.push({url:`${m}${b(f,"authors")}`,lastModified:P(t),changeFrequency:a.authorPages??"weekly",priority:g.authorPages??.6}),R.forEach(p=>{if(s.length>=c)return;let d=`${m}${v(f,p.slug)}`,S=t.filter(A=>A.author?.id===p.id),h=P(S);s.push({url:d,lastModified:h,changeFrequency:a.authorPages??"weekly",priority:g.authorPages??.6});})),l&&t.length>u){let p=Math.ceil(t.length/u);for(let d=2;d<=p&&!(s.length>=c);d++)s.push({url:`${m}${f}?page=${d}`,lastModified:P(t),changeFrequency:a.paginationPages??"daily",priority:g.paginationPages??.5});}return s}function X(e,t,r=[],i={}){let{includeAuthorPages:o=true,includeTopicPages:n=true,includePaginationPages:l=true,articlesPerPage:u=10,maxEntries:c=5e4,changeFrequency:a={},priority:g={}}=i,s=[],m=x(i.canonical?.domain??e.domain,i.canonical?.forceHttps??true),f=i.canonical?.pathPrefix??"/blog",R=new Date().toISOString(),y=r.length>0?r:O(t),p=T([...t]),d=1;if(d+=t.length,n&&p.length>0&&(d+=p.length+1),o&&(d+=y.length>0?y.length+1:0),l&&t.length>u){let h=Math.ceil(t.length/u);d+=h-1;}let S=d>c;if(s.push({loc:`${m}${f}`,lastmod:P(t),changefreq:a.homePage??"daily",priority:g.homePage??1}),t.forEach(h=>{if(s.length>=c)return;let A=_(h,i.canonical);s.push({loc:A,lastmod:h.updatedAt,changefreq:a.articles??"monthly",priority:g.articles??.8});}),n&&p.length>0&&(s.length<c&&s.push({loc:`${m}${b(f,"topics")}`,lastmod:P(t),changefreq:a.topicPages??"weekly",priority:g.topicPages??.6}),p.forEach(h=>{if(s.length>=c)return;let A=t.filter($=>($.topics??[]).some(E=>E.slug===h.slug));s.push({loc:`${m}${b(f,`topics/${h.slug}`)}`,lastmod:P(A),changefreq:a.topicPages??"weekly",priority:g.topicPages??.6});})),o&&y.length>0&&(s.length<c&&s.push({loc:`${m}${b(f,"authors")}`,lastmod:P(t),changefreq:a.authorPages??"weekly",priority:g.authorPages??.6}),y.forEach(h=>{if(s.length>=c)return;let A=`${m}${v(f,h.slug)}`,$=t.filter(B=>B.author?.id===h.id),E=P($);s.push({loc:A,lastmod:E,changefreq:a.authorPages??"weekly",priority:g.authorPages??.6});})),l&&t.length>u){let h=Math.ceil(t.length/u);for(let A=2;A<=h&&!(s.length>=c);A++)s.push({loc:`${m}${f}?page=${A}`,lastmod:P(t),changefreq:a.paginationPages??"daily",priority:g.paginationPages??.5});}return {entries:s,totalEntries:s.length,truncated:S,generatedAt:R,baseUrl:m}}function C(e){let t='<?xml version="1.0" encoding="UTF-8"?>',r='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',i="</urlset>",o=e.entries.map(n=>{let l=[];return l.push(" <url>"),l.push(` <loc>${w(n.loc)}</loc>`),n.lastmod&&l.push(` <lastmod>${w(n.lastmod)}</lastmod>`),n.changefreq&&l.push(` <changefreq>${w(n.changefreq)}</changefreq>`),n.priority!==void 0&&l.push(` <priority>${n.priority.toFixed(1)}</priority>`),l.push(" </url>"),l.join(`
2
+ `)});return [t,r,...o,i].join(`
3
+ `)}function J(e,t){let r='<?xml version="1.0" encoding="UTF-8"?>',i='<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',o="</sitemapindex>",n=e.map(l=>{let u=[];return u.push(" <sitemap>"),u.push(` <loc>${w(l.url)}</loc>`),l.lastmod&&u.push(` <lastmod>${w(l.lastmod)}</lastmod>`),u.push(" </sitemap>"),u.join(`
4
+ `)});return [r,i,...n,o].join(`
5
+ `)}function Q(e){let t=[],r=[];e.entries.length===0?t.push("Sitemap must contain at least one URL"):e.entries.length>5e4&&t.push("Sitemap contains more than 50,000 URLs (Google limit)"),e.truncated&&r.push("Sitemap was truncated due to size limits"),e.entries.forEach((o,n)=>{try{new URL(o.loc);}catch{t.push(`Invalid URL at entry ${n+1}: ${o.loc}`);}o.priority!==void 0&&(o.priority<0||o.priority>1)&&t.push(`Invalid priority at entry ${n+1}: must be between 0.0 and 1.0`),o.lastmod&&!M(o.lastmod)&&t.push(`Invalid lastmod date at entry ${n+1}: ${o.lastmod}`),o.loc.length>2048&&r.push(`URL at entry ${n+1} exceeds 2048 character limit`);});let i=new Map;return e.entries.forEach(o=>{let n=i.get(o.loc)??0;i.set(o.loc,n+1);}),i.forEach((o,n)=>{o>1&&t.push(`Duplicate URL found: ${n} (appears ${o} times)`);}),{valid:t.length===0,errors:t,warnings:r}}function P(e){return e.length===0?new Date().toISOString():e.reduce((r,i)=>{let o=new Date(i.updatedAt);return o>r?o:r},new Date(e[0].updatedAt)).toISOString()}function Y(e,t,r=[],i={}){return async function(){let l=(await U(e,t,r,i)).map(a=>({loc:a.url,lastmod:typeof a.lastModified=="string"?a.lastModified:a.lastModified?.toISOString(),changefreq:a.changeFrequency,priority:a.priority})),u={entries:l,totalEntries:l.length,generatedAt:new Date().toISOString(),baseUrl:x(i.canonical?.domain??e.domain,i.canonical?.forceHttps??true)},c=C(u);return new Response(c,{headers:{"Content-Type":"application/xml","Cache-Control":"public, max-age=3600, s-maxage=3600"}})}}function K(e){return async function(){let r=[...e.staticRoutes??[],...e.getStaticRoutes?await e.getStaticRoutes():[]],i=await e.getSite(),o=await e.getArticles(),n=e.getAuthors?await e.getAuthors():[];return [...r,...await U(i,o,n,e.options)]}}function w(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function M(e){try{let t=new Date(e),r=t.toISOString(),i=e.endsWith("Z")&&!e.includes(".")?e.replace("Z",".000Z"):e;return r===i&&!isNaN(t.getTime())}catch{return false}}exports.createBlogSitemapRoute=Y;exports.createDynamicBlogSitemap=K;exports.generateBlogSitemapEntries=U;exports.generateSitemap=X;exports.generateSitemapIndex=J;exports.sitemapToXml=C;exports.validateSitemap=Q;//# sourceMappingURL=sitemap.js.map
6
+ //# sourceMappingURL=sitemap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/authors.ts","../src/lib/seo.ts","../src/lib/topics.ts","../src/lib/urls.ts","../src/lib/sitemap.ts"],"names":["getAuthorsFromArticles","articles","authorsBySlug","article","mergeAuthorProfile","a","b","current","next","normalizeDomain","domain","forceHttps","normalized","normalizeSlug","slug","trimmed","clean","generateCanonicalUrl","options","removeTrailingSlash","pathPrefix","normalizedDomain","normalizedSlug","cleanPrefix","canonicalUrl","getAllTopics","topicsBySlug","topic","normalizeBlogBasePath","basePath","buildBlogPath","normalizedBasePath","cleanSlug","buildAuthorPath","authorSlug","generateBlogSitemapEntries","site","authors","includeAuthorPages","includeTopicPages","includePaginationPages","articlesPerPage","maxEntries","changeFrequency","priority","entries","baseUrl","sitemapAuthors","sitemapTopics","getLatestModificationDate","articleUrl","topicArticles","candidate","author","authorUrl","authorArticles","latestAuthorMod","totalPages","page","generateSitemap","generatedAt","potentialEntries","willTruncate","sitemapToXml","sitemapData","xmlHeader","urlsetOpen","urlsetClose","urlEntries","entry","elements","escapeXml","generateSitemapIndex","sitemaps","_baseUrl","indexOpen","indexClose","sitemapEntries","sitemap","validateSitemap","errors","warnings","index","isValidISODate","urlCounts","count","url","latest","articleDate","createBlogSitemapRoute","xmlEntries","xml","createDynamicBlogSitemap","config","staticRoutes","text","xmlEscapes","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A,CAChDA,EAAW,OAAA,CAAQ,GAAA,CAAK,OAAO,CAAA,CAC/BA,CAAAA,CAEN,OAAOE,IAAcC,CAAAA,EAAmB,CAAC,KAAA,CAAMF,CAAAA,CAAK,OAAA,EAAS,CAC/D,CAAA,KAAQ,CACN,OAAO,MACT,CACF","file":"sitemap.js","sourcesContent":["import type { BlogPlatformStorage } from \"./database\";\nimport { getStorage } from \"./database\";\nimport type { PublishedArticle, PublishedAuthor } from \"../types/contracts\";\n\nexport interface AuthorArchive {\n author: PublishedAuthor;\n articles: PublishedArticle[];\n}\n\nexport interface AuthorArchiveOptions {\n limit?: number;\n offset?: number;\n}\n\nexport function getAuthorsFromArticles(\n articles: readonly PublishedArticle[],\n): PublishedAuthor[] {\n const authorsBySlug = new Map<string, PublishedAuthor>();\n\n for (const article of articles) {\n if (article.author?.slug) {\n authorsBySlug.set(\n article.author.slug,\n mergeAuthorProfile(\n authorsBySlug.get(article.author.slug),\n article.author,\n ),\n );\n }\n }\n\n return Array.from(authorsBySlug.values()).sort((a, b) =>\n a.name.localeCompare(b.name),\n );\n}\n\nexport function getAuthorArchive(\n slug: string,\n articles: readonly PublishedArticle[],\n): AuthorArchive | null {\n const authorArticles = articles\n .filter((article) => article.author?.slug === slug)\n .sort(\n (a, b) =>\n new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime(),\n );\n\n const author = authorArticles.reduce<PublishedAuthor | null>(\n (preferredAuthor, article) =>\n article.author\n ? mergeAuthorProfile(preferredAuthor, article.author)\n : preferredAuthor,\n null,\n );\n\n if (!author) {\n return null;\n }\n\n return {\n author,\n articles: authorArticles,\n };\n}\n\nexport async function loadAuthorArchive(\n slug: string,\n options: AuthorArchiveOptions = {},\n storage: BlogPlatformStorage = getStorage(),\n): Promise<AuthorArchive | null> {\n const { articles } = await storage.listArticles({\n limit: options.limit ?? 1000,\n offset: options.offset ?? 0,\n sortBy: \"publishedAt\",\n order: \"desc\",\n });\n\n return getAuthorArchive(slug, articles);\n}\n\nfunction mergeAuthorProfile(\n current: PublishedAuthor | null | undefined,\n next: PublishedAuthor,\n): PublishedAuthor {\n if (!current) {\n return next;\n }\n\n return {\n ...current,\n bio: current.bio ?? next.bio,\n avatarUrl: current.avatarUrl ?? next.avatarUrl,\n pronouns: current.pronouns ?? next.pronouns,\n socialLinks: current.socialLinks ?? next.socialLinks,\n toneAdjectives:\n current.toneAdjectives.length > 0\n ? current.toneAdjectives\n : next.toneAdjectives,\n };\n}\n","/**\n * SEO utilities for canonical URL generation and validation.\n *\n * These utilities ensure proper canonical URL structure for SEO optimization,\n * preventing duplicate content issues and improving search engine indexing.\n */\n\nimport type { PublishedArticle, PublishedSite } from '../types/contracts';\n\n/**\n * Configuration options for canonical URL generation.\n */\nexport interface CanonicalUrlOptions {\n /** Whether to force HTTPS protocol (default: true) */\n forceHttps?: boolean;\n\n /** Whether to remove trailing slashes (default: true) */\n removeTrailingSlash?: boolean;\n\n /** Custom domain override (uses site.domain if not provided) */\n domain?: string;\n\n /** Custom path prefix (default: '/blog') */\n pathPrefix?: string;\n}\n\n/**\n * Normalizes a domain by ensuring proper protocol and removing trailing slashes.\n *\n * @param domain - The domain to normalize\n * @param forceHttps - Whether to force HTTPS protocol\n * @returns The normalized domain\n *\n * @example\n * ```typescript\n * normalizeDomain('example.com') // 'https://example.com'\n * normalizeDomain('http://example.com/') // 'https://example.com'\n * normalizeDomain('https://example.com', false) // 'https://example.com'\n * ```\n */\nexport function normalizeDomain(domain: string, forceHttps = true): string {\n let normalized = domain.trim();\n\n // Remove trailing slashes\n normalized = normalized.replace(/\\/+$/, '');\n\n // Add protocol if missing\n if (!/^https?:\\/\\//.exec(normalized)) {\n normalized = `${forceHttps ? 'https' : 'http'}://${normalized}`;\n }\n\n // Force HTTPS if requested\n if (forceHttps && normalized.startsWith('http://')) {\n normalized = normalized.replace('http://', 'https://');\n }\n\n return normalized;\n}\n\n/**\n * Validates and normalizes a slug for URL usage.\n *\n * @param slug - The slug to validate and normalize\n * @returns The normalized slug\n * @throws Error if slug is invalid\n *\n * @example\n * ```typescript\n * normalizeSlug('hello-world') // 'hello-world'\n * normalizeSlug('Hello World!') // throws Error\n * normalizeSlug('hello--world') // 'hello-world'\n * ```\n */\nexport function normalizeSlug(slug: string): string {\n const trimmed = slug.trim();\n\n if (!trimmed) {\n throw new Error('Slug cannot be empty');\n }\n\n // Check if slug contains only valid characters\n if (!/^[a-z0-9-]+$/.test(trimmed)) {\n throw new Error('Slug can only contain lowercase letters, numbers, and hyphens');\n }\n\n // Remove multiple consecutive hyphens\n const normalized = trimmed.replace(/-+/g, '-');\n\n // Remove leading/trailing hyphens\n const clean = normalized.replace(/^-+|-+$/g, '');\n\n if (!clean) {\n throw new Error('Slug cannot consist only of hyphens');\n }\n\n return clean;\n}\n\n/**\n * Generates a canonical URL for an article.\n *\n * @param article - The published article\n * @param options - Configuration options for URL generation\n * @returns The canonical URL\n * @throws Error if article or site data is invalid\n *\n * @example\n * ```typescript\n * const article = {\n * slug: 'hello-world',\n * site: { domain: 'example.com' },\n * // ... other fields\n * };\n *\n * generateCanonicalUrl(article)\n * // 'https://example.com/blog/hello-world'\n *\n * generateCanonicalUrl(article, { pathPrefix: '/posts' })\n * // 'https://example.com/posts/hello-world'\n * ```\n */\nexport function generateCanonicalUrl(\n article: PublishedArticle,\n options: CanonicalUrlOptions = {}\n): string {\n const {\n forceHttps = true,\n removeTrailingSlash = true,\n domain = article.site.domain,\n pathPrefix = '/blog'\n } = options;\n\n if (!domain) {\n throw new Error('Domain is required for canonical URL generation');\n }\n\n if (!article.slug) {\n throw new Error('Article slug is required for canonical URL generation');\n }\n\n // Validate and normalize inputs\n const normalizedDomain = normalizeDomain(domain, forceHttps);\n const normalizedSlug = normalizeSlug(article.slug);\n\n // Ensure path prefix starts with '/' and doesn't end with '/'\n const cleanPrefix = pathPrefix\n .replace(/^(?!\\/)/, '/') // Add leading slash if missing\n .replace(/\\/+$/, ''); // Remove trailing slashes\n\n // Construct the canonical URL\n let canonicalUrl = `${normalizedDomain}${cleanPrefix}/${normalizedSlug}`;\n\n // Remove trailing slash if requested\n if (removeTrailingSlash) {\n canonicalUrl = canonicalUrl.replace(/\\/+$/, '');\n }\n\n return canonicalUrl;\n}\n\n/**\n * Generates a canonical URL for an article from site and slug data.\n * Useful when you don't have a full PublishedArticle object.\n *\n * @param site - The published site\n * @param slug - The article slug\n * @param options - Configuration options for URL generation\n * @returns The canonical URL\n *\n * @example\n * ```typescript\n * const site = { domain: 'example.com', ... };\n * generateCanonicalUrlFromSlug(site, 'hello-world')\n * // 'https://example.com/blog/hello-world'\n * ```\n */\nexport function generateCanonicalUrlFromSlug(\n site: PublishedSite,\n slug: string,\n options: CanonicalUrlOptions = {}\n): string {\n return generateCanonicalUrl(\n {\n slug,\n site,\n // Minimal required fields for canonical URL generation\n id: '',\n title: '',\n excerpt: '',\n content: '',\n readingSeconds: 0,\n wordCount: 0,\n publishedAt: '',\n updatedAt: '',\n author: null,\n meta: { keywords: [] },\n version: 1\n },\n options\n );\n}\n\n/**\n * Validates if a URL is a valid canonical URL format.\n *\n * @param url - The URL to validate\n * @returns True if the URL is valid for canonical use\n *\n * @example\n * ```typescript\n * isValidCanonicalUrl('https://example.com/blog/hello-world') // true\n * isValidCanonicalUrl('http://example.com/blog/hello-world') // true\n * isValidCanonicalUrl('example.com/blog/hello-world') // false (missing protocol)\n * isValidCanonicalUrl('https://example.com/blog/hello world') // false (spaces)\n * ```\n */\nexport function isValidCanonicalUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n\n // Must be HTTP or HTTPS\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n return false;\n }\n\n // Must have a valid hostname (not empty or just slashes)\n if (!parsed.hostname || parsed.hostname.length === 0) {\n return false;\n }\n\n // Check for URLs with empty hostname like 'https:///path'\n if (/^https?:\\/\\/\\//.exec(url) && !/^https?:\\/\\/[^\\/]/.exec(url)) {\n return false;\n }\n\n // Path should not contain unencoded spaces or other problematic characters\n // Check the original URL string since URL constructor auto-encodes\n if (url.includes(' ')) {\n return false;\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Extracts the base URL (protocol + hostname + port) from a canonical URL.\n *\n * @param canonicalUrl - The canonical URL\n * @returns The base URL\n *\n * @example\n * ```typescript\n * getBaseUrl('https://example.com/blog/hello-world') // 'https://example.com'\n * getBaseUrl('https://blog.example.com:8080/posts/test') // 'https://blog.example.com:8080'\n * ```\n */\nexport function getBaseUrl(canonicalUrl: string): string {\n try {\n const parsed = new URL(canonicalUrl);\n return `${parsed.protocol}//${parsed.host}`;\n } catch {\n throw new Error('Invalid canonical URL provided');\n }\n}\n\n/**\n * Updates an article's canonical URL in its meta field.\n *\n * @param article - The article to update\n * @param options - Configuration options for URL generation\n * @returns A new article object with updated canonical URL\n *\n * @example\n * ```typescript\n * const updatedArticle = updateArticleCanonicalUrl(article);\n * console.log(updatedArticle.meta.canonicalUrl); // Generated canonical URL\n * ```\n */\nexport function updateArticleCanonicalUrl(\n article: PublishedArticle,\n options: CanonicalUrlOptions = {}\n): PublishedArticle {\n const canonicalUrl = generateCanonicalUrl(article, options);\n\n return {\n ...article,\n meta: {\n ...article.meta,\n canonicalUrl\n }\n };\n}","import type { PublishedArticle, PublishedTopic } from \"../types/contracts\";\n\nexport interface TopicArchive {\n topic: PublishedTopic;\n articles: PublishedArticle[];\n}\n\nexport function getArticlePrimaryTopic(\n article: PublishedArticle,\n): PublishedTopic | null {\n const topics = article.topics ?? [];\n return topics.find((topic) => topic.isPrimary) ?? topics[0] ?? null;\n}\n\nexport function getAllTopics(articles: PublishedArticle[]): PublishedTopic[] {\n const topicsBySlug = new Map<string, PublishedTopic>();\n\n for (const article of articles) {\n for (const topic of article.topics ?? []) {\n if (!topicsBySlug.has(topic.slug)) {\n topicsBySlug.set(topic.slug, topic);\n }\n }\n }\n\n return Array.from(topicsBySlug.values()).sort((a, b) =>\n a.name.localeCompare(b.name),\n );\n}\n\nexport function getTopicArchive(\n articles: PublishedArticle[],\n topicSlug: string,\n): TopicArchive | null {\n const matchingArticles = articles.filter((article) =>\n (article.topics ?? []).some((topic) => topic.slug === topicSlug),\n );\n\n if (matchingArticles.length === 0) {\n return null;\n }\n\n const topic =\n matchingArticles\n .flatMap((article) => article.topics ?? [])\n .find((candidate) => candidate.slug === topicSlug) ?? null;\n\n if (!topic) {\n return null;\n }\n\n return {\n topic,\n articles: matchingArticles,\n };\n}\n","/**\n * URL helpers shared by package UI, metadata, and sitemap integrations.\n */\n\nexport function normalizeBlogBasePath(basePath = \"/blog\"): string {\n const trimmed = basePath.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n\n return trimmed.replace(/^(?!\\/)/, \"/\").replace(/\\/+$/, \"\");\n}\n\nexport function buildBlogPath(\n basePath: string | undefined,\n slug?: string,\n): string {\n const normalizedBasePath = normalizeBlogBasePath(basePath);\n const cleanSlug = slug?.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n\n if (!cleanSlug) {\n return normalizedBasePath || \"/\";\n }\n\n return `${normalizedBasePath}/${cleanSlug}`.replace(/\\/+/g, \"/\");\n}\n\nexport function buildAuthorPath(\n basePath: string | undefined,\n authorSlug: string,\n): string {\n return buildBlogPath(basePath, `authors/${authorSlug}`);\n}\n\nexport function getPathPrefixFromBlogUrl(blogUrl: string): string {\n const parsed = new URL(blogUrl);\n return normalizeBlogBasePath(parsed.pathname);\n}\n","/**\n * Next.js-compatible sitemap generation utilities for blog platform integration.\n *\n * These utilities generate sitemap entries that follow Next.js MetadataRoute.Sitemap\n * conventions, allowing seamless integration with existing Next.js applications.\n *\n * @example Integration with existing Next.js sitemap:\n * ```typescript\n * // app/sitemap.ts\n * import { generateBlogSitemapEntries } from '@xexr/blog-platform';\n * import type { MetadataRoute } from 'next';\n *\n * export default async function sitemap(): Promise<MetadataRoute.Sitemap> {\n * // Your existing routes\n * const staticRoutes = [\n * { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },\n * { url: 'https://yoursite.com/about', lastModified: new Date(), priority: 0.8 }\n * ];\n *\n * // Blog platform entries\n * const blogEntries = await generateBlogSitemapEntries(blogConfig);\n *\n * return [...staticRoutes, ...blogEntries];\n * }\n * ```\n */\n\nimport type {\n PublishedArticle,\n PublishedSite,\n PublishedAuthor,\n} from \"../types/contracts\";\nimport { getAuthorsFromArticles } from \"./authors\";\nimport {\n generateCanonicalUrl,\n normalizeDomain,\n type CanonicalUrlOptions,\n} from \"./seo\";\nimport { getAllTopics } from \"./topics\";\nimport { buildAuthorPath, buildBlogPath } from \"./urls\";\n\n/**\n * Configuration options for sitemap generation.\n */\nexport interface SitemapOptions {\n /** Canonical URL configuration */\n canonical?: CanonicalUrlOptions;\n\n /** Whether to include author pages in sitemap */\n includeAuthorPages?: boolean;\n\n /** Whether to include topic pages in sitemap */\n includeTopicPages?: boolean;\n\n /** Whether to include pagination pages in sitemap */\n includePaginationPages?: boolean;\n\n /** Number of articles per page for pagination calculation */\n articlesPerPage?: number;\n\n /** Maximum number of sitemap entries (defaults to 50,000 per Google guidelines) */\n maxEntries?: number;\n\n /** Change frequency for different page types */\n changeFrequency?: {\n /** Change frequency for blog home page */\n homePage?: SitemapChangeFreq;\n /** Change frequency for article pages */\n articles?: SitemapChangeFreq;\n /** Change frequency for author pages */\n authorPages?: SitemapChangeFreq;\n /** Change frequency for topic index and archive pages */\n topicPages?: SitemapChangeFreq;\n /** Change frequency for pagination pages */\n paginationPages?: SitemapChangeFreq;\n };\n\n /** Priority values for different page types */\n priority?: {\n /** Priority for blog home page (0.0-1.0) */\n homePage?: number;\n /** Priority for article pages (0.0-1.0) */\n articles?: number;\n /** Priority for author pages (0.0-1.0) */\n authorPages?: number;\n /** Priority for topic index and archive pages (0.0-1.0) */\n topicPages?: number;\n /** Priority for pagination pages (0.0-1.0) */\n paginationPages?: number;\n };\n}\n\n/**\n * Valid sitemap change frequency values as per XML sitemap standard.\n */\nexport type SitemapChangeFreq =\n | \"always\"\n | \"hourly\"\n | \"daily\"\n | \"weekly\"\n | \"monthly\"\n | \"yearly\"\n | \"never\";\n\n/**\n * Next.js MetadataRoute.Sitemap compatible entry.\n * This matches the expected format for Next.js sitemap generation.\n */\nexport interface NextjsSitemapEntry {\n /** The URL of the page */\n url: string;\n\n /** Last modification date */\n lastModified?: string | Date;\n\n /** Change frequency hint for search engines */\n changeFrequency?: SitemapChangeFreq;\n\n /** Priority relative to other URLs on the site (0.0-1.0) */\n priority?: number;\n\n /** Alternate language versions (for i18n) */\n alternates?: {\n languages?: Record<string, string>;\n };\n}\n\n/**\n * Legacy XML sitemap entry format (for backward compatibility).\n * @deprecated Use NextjsSitemapEntry for new implementations\n */\nexport interface SitemapEntry {\n /** The URL of the page */\n loc: string;\n\n /** Last modification date as ISO 8601 string */\n lastmod?: string;\n\n /** Change frequency hint for search engines */\n changefreq?: SitemapChangeFreq;\n\n /** Priority relative to other URLs on the site (0.0-1.0) */\n priority?: number;\n}\n\n/**\n * Complete sitemap data structure.\n */\nexport interface SitemapData {\n /** All URL entries in the sitemap */\n entries: SitemapEntry[];\n\n /** Total number of entries */\n totalEntries: number;\n\n /** Whether the sitemap was truncated due to size limits */\n truncated: boolean;\n\n /** Generation timestamp */\n generatedAt: string;\n\n /** Base URL used for canonical URL generation */\n baseUrl: string;\n}\n\n/**\n * Generates Next.js-compatible sitemap entries for blog platform integration.\n *\n * @param site - The published site information\n * @param articles - Array of published articles\n * @param authors - Array of published authors (optional)\n * @param options - Sitemap generation options\n * @returns Array of Next.js MetadataRoute.Sitemap compatible entries\n *\n * @example\n * ```typescript\n * // In your Next.js app/sitemap.ts file:\n * import { generateBlogSitemapEntries } from '@xexr/blog-platform';\n * import type { MetadataRoute } from 'next';\n *\n * export default async function sitemap(): Promise<MetadataRoute.Sitemap> {\n * const blogEntries = await generateBlogSitemapEntries(site, articles, authors, {\n * includeAuthorPages: true,\n * includePaginationPages: true,\n * changeFrequency: { articles: 'monthly' }\n * });\n *\n * return [\n * // Your existing site routes\n * { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },\n * { url: 'https://yoursite.com/about', lastModified: new Date() },\n * // Blog entries\n * ...blogEntries\n * ];\n * }\n * ```\n */\nexport async function generateBlogSitemapEntries(\n site: PublishedSite,\n articles: readonly PublishedArticle[],\n authors: readonly PublishedAuthor[] = [],\n options: SitemapOptions = {},\n): Promise<NextjsSitemapEntry[]> {\n const {\n includeAuthorPages = true,\n includeTopicPages = true,\n includePaginationPages = true,\n articlesPerPage = 10,\n maxEntries = 50000,\n changeFrequency = {},\n priority = {},\n } = options;\n\n const entries: NextjsSitemapEntry[] = [];\n const baseUrl = normalizeDomain(\n options.canonical?.domain ?? site.domain,\n options.canonical?.forceHttps ?? true,\n );\n\n const pathPrefix = options.canonical?.pathPrefix ?? \"/blog\";\n const sitemapAuthors =\n authors.length > 0 ? authors : getAuthorsFromArticles(articles);\n const sitemapTopics = getAllTopics([...articles]);\n\n // Add blog home page\n entries.push({\n url: `${baseUrl}${pathPrefix}`,\n lastModified: getLatestModificationDate(articles),\n changeFrequency: changeFrequency.homePage ?? \"daily\",\n priority: priority.homePage ?? 1.0,\n });\n\n // Add individual article pages\n articles.forEach((article) => {\n if (entries.length >= maxEntries) return;\n\n const articleUrl = generateCanonicalUrl(article, options.canonical);\n entries.push({\n url: articleUrl,\n lastModified: article.updatedAt,\n changeFrequency: changeFrequency.articles ?? \"monthly\",\n priority: priority.articles ?? 0.8,\n });\n });\n\n if (includeTopicPages && sitemapTopics.length > 0) {\n if (entries.length < maxEntries) {\n entries.push({\n url: `${baseUrl}${buildBlogPath(pathPrefix, \"topics\")}`,\n lastModified: getLatestModificationDate(articles),\n changeFrequency: changeFrequency.topicPages ?? \"weekly\",\n priority: priority.topicPages ?? 0.6,\n });\n }\n\n sitemapTopics.forEach((topic) => {\n if (entries.length >= maxEntries) return;\n\n const topicArticles = articles.filter((article) =>\n (article.topics ?? []).some((candidate) => candidate.slug === topic.slug),\n );\n\n entries.push({\n url: `${baseUrl}${buildBlogPath(pathPrefix, `topics/${topic.slug}`)}`,\n lastModified: getLatestModificationDate(topicArticles),\n changeFrequency: changeFrequency.topicPages ?? \"weekly\",\n priority: priority.topicPages ?? 0.6,\n });\n });\n }\n\n // Add author pages if enabled\n if (includeAuthorPages && sitemapAuthors.length > 0) {\n if (entries.length < maxEntries) {\n entries.push({\n url: `${baseUrl}${buildBlogPath(pathPrefix, \"authors\")}`,\n lastModified: getLatestModificationDate(articles),\n changeFrequency: changeFrequency.authorPages ?? \"weekly\",\n priority: priority.authorPages ?? 0.6,\n });\n }\n\n sitemapAuthors.forEach((author) => {\n if (entries.length >= maxEntries) return;\n\n const authorUrl = `${baseUrl}${buildAuthorPath(pathPrefix, author.slug)}`;\n\n // Find the latest article by this author for lastModified\n const authorArticles = articles.filter(\n (article) => article.author?.id === author.id,\n );\n const latestAuthorMod = getLatestModificationDate(authorArticles);\n\n entries.push({\n url: authorUrl,\n lastModified: latestAuthorMod,\n changeFrequency: changeFrequency.authorPages ?? \"weekly\",\n priority: priority.authorPages ?? 0.6,\n });\n });\n }\n\n // Add pagination pages if enabled\n if (includePaginationPages && articles.length > articlesPerPage) {\n const totalPages = Math.ceil(articles.length / articlesPerPage);\n\n for (let page = 2; page <= totalPages; page++) {\n if (entries.length >= maxEntries) break;\n\n entries.push({\n url: `${baseUrl}${pathPrefix}?page=${page}`,\n lastModified: getLatestModificationDate(articles),\n changeFrequency: changeFrequency.paginationPages ?? \"daily\",\n priority: priority.paginationPages ?? 0.5,\n });\n }\n }\n\n return entries;\n}\n\n/**\n * Legacy sitemap generation for backward compatibility.\n * @deprecated Use generateBlogSitemapEntries for Next.js integration\n *\n * @param site - The published site information\n * @param articles - Array of published articles\n * @param authors - Array of published authors (optional)\n * @param options - Sitemap generation options\n * @returns Complete sitemap data\n */\nexport function generateSitemap(\n site: PublishedSite,\n articles: readonly PublishedArticle[],\n authors: readonly PublishedAuthor[] = [],\n options: SitemapOptions = {},\n): SitemapData {\n const {\n includeAuthorPages = true,\n includeTopicPages = true,\n includePaginationPages = true,\n articlesPerPage = 10,\n maxEntries = 50000,\n changeFrequency = {},\n priority = {},\n } = options;\n\n const entries: SitemapEntry[] = [];\n const baseUrl = normalizeDomain(\n options.canonical?.domain ?? site.domain,\n options.canonical?.forceHttps ?? true,\n );\n\n const pathPrefix = options.canonical?.pathPrefix ?? \"/blog\";\n const generatedAt = new Date().toISOString();\n const sitemapAuthors =\n authors.length > 0 ? authors : getAuthorsFromArticles(articles);\n const sitemapTopics = getAllTopics([...articles]);\n\n // Calculate total potential entries to determine if truncation will occur\n let potentialEntries = 1; // Home page\n potentialEntries += articles.length; // Article pages\n if (includeTopicPages && sitemapTopics.length > 0) {\n potentialEntries += sitemapTopics.length + 1; // Topic index + topic pages\n }\n if (includeAuthorPages) {\n potentialEntries += sitemapAuthors.length > 0 ? sitemapAuthors.length + 1 : 0; // Authors index + author pages\n }\n if (includePaginationPages && articles.length > articlesPerPage) {\n const totalPages = Math.ceil(articles.length / articlesPerPage);\n potentialEntries += totalPages - 1; // Pagination pages (excluding page 1 which is home)\n }\n\n const willTruncate = potentialEntries > maxEntries;\n\n // Add blog home page\n entries.push({\n loc: `${baseUrl}${pathPrefix}`,\n lastmod: getLatestModificationDate(articles),\n changefreq: changeFrequency.homePage ?? \"daily\",\n priority: priority.homePage ?? 1.0,\n });\n\n // Add individual article pages\n articles.forEach((article) => {\n if (entries.length >= maxEntries) return;\n\n const articleUrl = generateCanonicalUrl(article, options.canonical);\n entries.push({\n loc: articleUrl,\n lastmod: article.updatedAt,\n changefreq: changeFrequency.articles ?? \"monthly\",\n priority: priority.articles ?? 0.8,\n });\n });\n\n if (includeTopicPages && sitemapTopics.length > 0) {\n if (entries.length < maxEntries) {\n entries.push({\n loc: `${baseUrl}${buildBlogPath(pathPrefix, \"topics\")}`,\n lastmod: getLatestModificationDate(articles),\n changefreq: changeFrequency.topicPages ?? \"weekly\",\n priority: priority.topicPages ?? 0.6,\n });\n }\n\n sitemapTopics.forEach((topic) => {\n if (entries.length >= maxEntries) return;\n\n const topicArticles = articles.filter((article) =>\n (article.topics ?? []).some((candidate) => candidate.slug === topic.slug),\n );\n\n entries.push({\n loc: `${baseUrl}${buildBlogPath(pathPrefix, `topics/${topic.slug}`)}`,\n lastmod: getLatestModificationDate(topicArticles),\n changefreq: changeFrequency.topicPages ?? \"weekly\",\n priority: priority.topicPages ?? 0.6,\n });\n });\n }\n\n // Add author pages if enabled\n if (includeAuthorPages && sitemapAuthors.length > 0) {\n if (entries.length < maxEntries) {\n entries.push({\n loc: `${baseUrl}${buildBlogPath(pathPrefix, \"authors\")}`,\n lastmod: getLatestModificationDate(articles),\n changefreq: changeFrequency.authorPages ?? \"weekly\",\n priority: priority.authorPages ?? 0.6,\n });\n }\n\n sitemapAuthors.forEach((author) => {\n if (entries.length >= maxEntries) return;\n\n const authorUrl = `${baseUrl}${buildAuthorPath(pathPrefix, author.slug)}`;\n\n // Find the latest article by this author for lastmod\n const authorArticles = articles.filter(\n (article) => article.author?.id === author.id,\n );\n const latestAuthorMod = getLatestModificationDate(authorArticles);\n\n entries.push({\n loc: authorUrl,\n lastmod: latestAuthorMod,\n changefreq: changeFrequency.authorPages ?? \"weekly\",\n priority: priority.authorPages ?? 0.6,\n });\n });\n }\n\n // Add pagination pages if enabled\n if (includePaginationPages && articles.length > articlesPerPage) {\n const totalPages = Math.ceil(articles.length / articlesPerPage);\n\n for (let page = 2; page <= totalPages; page++) {\n if (entries.length >= maxEntries) break;\n\n entries.push({\n loc: `${baseUrl}${pathPrefix}?page=${page}`,\n lastmod: getLatestModificationDate(articles),\n changefreq: changeFrequency.paginationPages ?? \"daily\",\n priority: priority.paginationPages ?? 0.5,\n });\n }\n }\n\n return {\n entries,\n totalEntries: entries.length,\n truncated: willTruncate,\n generatedAt,\n baseUrl,\n };\n}\n\n/**\n * Converts sitemap data to XML format.\n *\n * @param sitemapData - The sitemap data to convert\n * @returns XML string in sitemap format\n *\n * @example\n * ```typescript\n * const sitemap = generateSitemap(site, articles);\n * const xmlString = sitemapToXml(sitemap);\n * // Use in API route response\n * ```\n */\nexport function sitemapToXml(sitemapData: SitemapData): string {\n const xmlHeader = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n const urlsetOpen =\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">';\n const urlsetClose = \"</urlset>\";\n\n const urlEntries = sitemapData.entries.map((entry) => {\n const elements: string[] = [];\n\n elements.push(` <url>`);\n elements.push(` <loc>${escapeXml(entry.loc)}</loc>`);\n\n if (entry.lastmod) {\n elements.push(` <lastmod>${escapeXml(entry.lastmod)}</lastmod>`);\n }\n\n if (entry.changefreq) {\n elements.push(\n ` <changefreq>${escapeXml(entry.changefreq)}</changefreq>`,\n );\n }\n\n if (entry.priority !== undefined) {\n elements.push(` <priority>${entry.priority.toFixed(1)}</priority>`);\n }\n\n elements.push(` </url>`);\n\n return elements.join(\"\\n\");\n });\n\n return [xmlHeader, urlsetOpen, ...urlEntries, urlsetClose].join(\"\\n\");\n}\n\n/**\n * Generates a sitemap index for large blogs that need multiple sitemaps.\n *\n * @param sitemaps - Array of sitemap information\n * @param baseUrl - Base URL for the site\n * @returns XML string for sitemap index\n *\n * @example\n * ```typescript\n * const sitemapIndex = generateSitemapIndex([\n * { url: 'https://example.com/sitemap-articles.xml', lastmod: '2023-01-01T00:00:00Z' },\n * { url: 'https://example.com/sitemap-authors.xml', lastmod: '2023-01-01T00:00:00Z' }\n * ], 'https://example.com');\n * ```\n */\nexport function generateSitemapIndex(\n sitemaps: readonly { url: string; lastmod?: string }[],\n _baseUrl: string,\n): string {\n const xmlHeader = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n const indexOpen =\n '<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">';\n const indexClose = \"</sitemapindex>\";\n\n const sitemapEntries = sitemaps.map((sitemap) => {\n const elements: string[] = [];\n\n elements.push(` <sitemap>`);\n elements.push(` <loc>${escapeXml(sitemap.url)}</loc>`);\n\n if (sitemap.lastmod) {\n elements.push(` <lastmod>${escapeXml(sitemap.lastmod)}</lastmod>`);\n }\n\n elements.push(` </sitemap>`);\n\n return elements.join(\"\\n\");\n });\n\n return [xmlHeader, indexOpen, ...sitemapEntries, indexClose].join(\"\\n\");\n}\n\n/**\n * Validates sitemap data for compliance with search engine guidelines.\n *\n * @param sitemapData - The sitemap data to validate\n * @returns Validation results with errors and warnings\n *\n * @example\n * ```typescript\n * const sitemap = generateSitemap(site, articles);\n * const validation = validateSitemap(sitemap);\n *\n * if (validation.errors.length > 0) {\n * console.error('Sitemap errors:', validation.errors);\n * }\n * ```\n */\nexport function validateSitemap(sitemapData: SitemapData): {\n valid: boolean;\n errors: string[];\n warnings: string[];\n} {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Check entry count\n if (sitemapData.entries.length === 0) {\n errors.push(\"Sitemap must contain at least one URL\");\n } else if (sitemapData.entries.length > 50000) {\n errors.push(\"Sitemap contains more than 50,000 URLs (Google limit)\");\n }\n\n // Check for truncation\n if (sitemapData.truncated) {\n warnings.push(\"Sitemap was truncated due to size limits\");\n }\n\n // Validate individual entries\n sitemapData.entries.forEach((entry, index) => {\n // Validate URL format\n try {\n new URL(entry.loc);\n } catch {\n errors.push(`Invalid URL at entry ${index + 1}: ${entry.loc}`);\n }\n\n // Validate priority range\n if (\n entry.priority !== undefined &&\n (entry.priority < 0 || entry.priority > 1)\n ) {\n errors.push(\n `Invalid priority at entry ${index + 1}: must be between 0.0 and 1.0`,\n );\n }\n\n // Validate lastmod format\n if (entry.lastmod && !isValidISODate(entry.lastmod)) {\n errors.push(\n `Invalid lastmod date at entry ${index + 1}: ${entry.lastmod}`,\n );\n }\n\n // Check URL length (Google limit is 2048 characters)\n if (entry.loc.length > 2048) {\n warnings.push(`URL at entry ${index + 1} exceeds 2048 character limit`);\n }\n });\n\n // Check for duplicate URLs\n const urlCounts = new Map<string, number>();\n sitemapData.entries.forEach((entry) => {\n const count = urlCounts.get(entry.loc) ?? 0;\n urlCounts.set(entry.loc, count + 1);\n });\n\n urlCounts.forEach((count, url) => {\n if (count > 1) {\n errors.push(`Duplicate URL found: ${url} (appears ${count} times)`);\n }\n });\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Gets the latest modification date from an array of articles.\n */\nfunction getLatestModificationDate(\n articles: readonly PublishedArticle[],\n): string {\n if (articles.length === 0) {\n return new Date().toISOString();\n }\n\n const latestDate = articles.reduce((latest, article) => {\n const articleDate = new Date(article.updatedAt);\n return articleDate > latest ? articleDate : latest;\n }, new Date(articles[0]!.updatedAt));\n\n return latestDate.toISOString();\n}\n\n/**\n * Creates a separate sitemap specifically for blog content.\n * Useful for large sites that need to split sitemaps by content type.\n *\n * @param site - The published site information\n * @param articles - Array of published articles\n * @param authors - Array of published authors (optional)\n * @param options - Sitemap generation options\n * @returns Next.js sitemap function\n *\n * @example\n * ```typescript\n * // app/blog-sitemap/route.ts - separate blog sitemap endpoint\n * import { createBlogSitemapRoute } from '@xexr/blog-platform';\n *\n * export const GET = createBlogSitemapRoute(site, articles, authors, {\n * includeAuthorPages: true,\n * articlesPerPage: 20\n * });\n * ```\n */\nexport function createBlogSitemapRoute(\n site: PublishedSite,\n articles: readonly PublishedArticle[],\n authors: readonly PublishedAuthor[] = [],\n options: SitemapOptions = {},\n) {\n return async function GET() {\n const entries = await generateBlogSitemapEntries(\n site,\n articles,\n authors,\n options,\n );\n\n // Convert to Next.js sitemap format and return as XML\n const xmlEntries = entries.map((entry) => ({\n loc: entry.url,\n lastmod:\n typeof entry.lastModified === \"string\"\n ? entry.lastModified\n : entry.lastModified?.toISOString(),\n changefreq: entry.changeFrequency,\n priority: entry.priority,\n }));\n\n const sitemapData = {\n entries: xmlEntries,\n totalEntries: xmlEntries.length,\n truncated: false,\n generatedAt: new Date().toISOString(),\n baseUrl: normalizeDomain(\n options.canonical?.domain ?? site.domain,\n options.canonical?.forceHttps ?? true,\n ),\n };\n\n const xml = sitemapToXml(sitemapData);\n\n return new Response(xml, {\n headers: {\n \"Content-Type\": \"application/xml\",\n \"Cache-Control\": \"public, max-age=3600, s-maxage=3600\",\n },\n });\n };\n}\n\n/**\n * Configuration interface for blog data fetching.\n * Used to fetch blog data for sitemap generation.\n */\nexport interface BlogSitemapConfig {\n /** Static host app routes to include before Bloggy routes */\n staticRoutes?: readonly NextjsSitemapEntry[];\n\n /** Function to fetch static host app routes */\n getStaticRoutes?: () => Promise<readonly NextjsSitemapEntry[]>;\n\n /** Function to fetch site data */\n getSite: () => Promise<PublishedSite>;\n\n /** Function to fetch published articles */\n getArticles: () => Promise<readonly PublishedArticle[]>;\n\n /** Function to fetch authors (optional) */\n getAuthors?: () => Promise<readonly PublishedAuthor[]>;\n\n /** Sitemap generation options */\n options?: SitemapOptions;\n}\n\n/**\n * Higher-order function that creates a Next.js sitemap function with data fetching.\n * Ideal for dynamic blog content that needs to be fetched at sitemap generation time.\n *\n * @param config - Configuration for fetching blog data\n * @returns Next.js sitemap function\n *\n * @example\n * ```typescript\n * // app/sitemap.ts\n * import { createDynamicBlogSitemap } from '@xexr/blog-platform';\n * import { getBlogData } from './lib/blog';\n *\n * export default createDynamicBlogSitemap({\n * getSite: () => getBlogData().site,\n * getArticles: () => getBlogData().articles,\n * getAuthors: () => getBlogData().authors,\n * options: {\n * includeAuthorPages: true,\n * changeFrequency: { articles: 'weekly' }\n * }\n * });\n * ```\n */\nexport function createDynamicBlogSitemap(config: BlogSitemapConfig) {\n return async function sitemap(): Promise<NextjsSitemapEntry[]> {\n const staticRoutes = [\n ...(config.staticRoutes ?? []),\n ...(config.getStaticRoutes ? await config.getStaticRoutes() : []),\n ];\n const site = await config.getSite();\n const articles = await config.getArticles();\n const authors = config.getAuthors ? await config.getAuthors() : [];\n\n return [\n ...staticRoutes,\n ...(await generateBlogSitemapEntries(\n site,\n articles,\n authors,\n config.options,\n )),\n ];\n };\n}\n\n/**\n * Escapes special XML characters for safe inclusion in XML content.\n */\nfunction escapeXml(text: string): string {\n const xmlEscapes: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#x27;\",\n };\n\n return text.replace(/[&<>\"']/g, (char) => xmlEscapes[char] ?? char);\n}\n\n/**\n * Validates if a string is a valid ISO 8601 date.\n */\nfunction isValidISODate(dateString: string): boolean {\n try {\n const date = new Date(dateString);\n const isoString = date.toISOString();\n\n // Handle both formats: with and without milliseconds\n // 2023-01-01T00:00:00.000Z and 2023-01-01T00:00:00Z are both valid\n const normalizedInput =\n dateString.endsWith(\"Z\") && !dateString.includes(\".\")\n ? dateString.replace(\"Z\", \".000Z\")\n : dateString;\n\n return isoString === normalizedInput && !isNaN(date.getTime());\n } catch {\n return false;\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ function O(e){let t=new Map;for(let r of e)r.author?.slug&&t.set(r.author.slug,q(t.get(r.author.slug),r.author));return Array.from(t.values()).sort((r,i)=>r.name.localeCompare(i.name))}function q(e,t){return e?{...e,bio:e.bio??t.bio,avatarUrl:e.avatarUrl??t.avatarUrl,pronouns:e.pronouns??t.pronouns,socialLinks:e.socialLinks??t.socialLinks,toneAdjectives:e.toneAdjectives.length>0?e.toneAdjectives:t.toneAdjectives}:t}function x(e,t=true){let r=e.trim();return r=r.replace(/\/+$/,""),/^https?:\/\//.exec(r)||(r=`${t?"https":"http"}://${r}`),t&&r.startsWith("http://")&&(r=r.replace("http://","https://")),r}function F(e){let t=e.trim();if(!t)throw new Error("Slug cannot be empty");if(!/^[a-z0-9-]+$/.test(t))throw new Error("Slug can only contain lowercase letters, numbers, and hyphens");let i=t.replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!i)throw new Error("Slug cannot consist only of hyphens");return i}function _(e,t={}){let{forceHttps:r=true,removeTrailingSlash:i=true,domain:o=e.site.domain,pathPrefix:n="/blog"}=t;if(!o)throw new Error("Domain is required for canonical URL generation");if(!e.slug)throw new Error("Article slug is required for canonical URL generation");let l=x(o,r),u=F(e.slug),c=n.replace(/^(?!\/)/,"/").replace(/\/+$/,""),a=`${l}${c}/${u}`;return i&&(a=a.replace(/\/+$/,"")),a}function T(e){let t=new Map;for(let r of e)for(let i of r.topics??[])t.has(i.slug)||t.set(i.slug,i);return Array.from(t.values()).sort((r,i)=>r.name.localeCompare(i.name))}function L(e="/blog"){let t=e.trim();return !t||t==="/"?"":t.replace(/^(?!\/)/,"/").replace(/\/+$/,"")}function b(e,t){let r=L(e),i=t?.replace(/^\/+/,"").replace(/\/+$/,"");return i?`${r}/${i}`.replace(/\/+/g,"/"):r||"/"}function v(e,t){return b(e,`authors/${t}`)}async function U(e,t,r=[],i={}){let{includeAuthorPages:o=true,includeTopicPages:n=true,includePaginationPages:l=true,articlesPerPage:u=10,maxEntries:c=5e4,changeFrequency:a={},priority:g={}}=i,s=[],m=x(i.canonical?.domain??e.domain,i.canonical?.forceHttps??true),f=i.canonical?.pathPrefix??"/blog",R=r.length>0?r:O(t),y=T([...t]);if(s.push({url:`${m}${f}`,lastModified:P(t),changeFrequency:a.homePage??"daily",priority:g.homePage??1}),t.forEach(p=>{if(s.length>=c)return;let d=_(p,i.canonical);s.push({url:d,lastModified:p.updatedAt,changeFrequency:a.articles??"monthly",priority:g.articles??.8});}),n&&y.length>0&&(s.length<c&&s.push({url:`${m}${b(f,"topics")}`,lastModified:P(t),changeFrequency:a.topicPages??"weekly",priority:g.topicPages??.6}),y.forEach(p=>{if(s.length>=c)return;let d=t.filter(S=>(S.topics??[]).some(h=>h.slug===p.slug));s.push({url:`${m}${b(f,`topics/${p.slug}`)}`,lastModified:P(d),changeFrequency:a.topicPages??"weekly",priority:g.topicPages??.6});})),o&&R.length>0&&(s.length<c&&s.push({url:`${m}${b(f,"authors")}`,lastModified:P(t),changeFrequency:a.authorPages??"weekly",priority:g.authorPages??.6}),R.forEach(p=>{if(s.length>=c)return;let d=`${m}${v(f,p.slug)}`,S=t.filter(A=>A.author?.id===p.id),h=P(S);s.push({url:d,lastModified:h,changeFrequency:a.authorPages??"weekly",priority:g.authorPages??.6});})),l&&t.length>u){let p=Math.ceil(t.length/u);for(let d=2;d<=p&&!(s.length>=c);d++)s.push({url:`${m}${f}?page=${d}`,lastModified:P(t),changeFrequency:a.paginationPages??"daily",priority:g.paginationPages??.5});}return s}function X(e,t,r=[],i={}){let{includeAuthorPages:o=true,includeTopicPages:n=true,includePaginationPages:l=true,articlesPerPage:u=10,maxEntries:c=5e4,changeFrequency:a={},priority:g={}}=i,s=[],m=x(i.canonical?.domain??e.domain,i.canonical?.forceHttps??true),f=i.canonical?.pathPrefix??"/blog",R=new Date().toISOString(),y=r.length>0?r:O(t),p=T([...t]),d=1;if(d+=t.length,n&&p.length>0&&(d+=p.length+1),o&&(d+=y.length>0?y.length+1:0),l&&t.length>u){let h=Math.ceil(t.length/u);d+=h-1;}let S=d>c;if(s.push({loc:`${m}${f}`,lastmod:P(t),changefreq:a.homePage??"daily",priority:g.homePage??1}),t.forEach(h=>{if(s.length>=c)return;let A=_(h,i.canonical);s.push({loc:A,lastmod:h.updatedAt,changefreq:a.articles??"monthly",priority:g.articles??.8});}),n&&p.length>0&&(s.length<c&&s.push({loc:`${m}${b(f,"topics")}`,lastmod:P(t),changefreq:a.topicPages??"weekly",priority:g.topicPages??.6}),p.forEach(h=>{if(s.length>=c)return;let A=t.filter($=>($.topics??[]).some(E=>E.slug===h.slug));s.push({loc:`${m}${b(f,`topics/${h.slug}`)}`,lastmod:P(A),changefreq:a.topicPages??"weekly",priority:g.topicPages??.6});})),o&&y.length>0&&(s.length<c&&s.push({loc:`${m}${b(f,"authors")}`,lastmod:P(t),changefreq:a.authorPages??"weekly",priority:g.authorPages??.6}),y.forEach(h=>{if(s.length>=c)return;let A=`${m}${v(f,h.slug)}`,$=t.filter(B=>B.author?.id===h.id),E=P($);s.push({loc:A,lastmod:E,changefreq:a.authorPages??"weekly",priority:g.authorPages??.6});})),l&&t.length>u){let h=Math.ceil(t.length/u);for(let A=2;A<=h&&!(s.length>=c);A++)s.push({loc:`${m}${f}?page=${A}`,lastmod:P(t),changefreq:a.paginationPages??"daily",priority:g.paginationPages??.5});}return {entries:s,totalEntries:s.length,truncated:S,generatedAt:R,baseUrl:m}}function C(e){let t='<?xml version="1.0" encoding="UTF-8"?>',r='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',i="</urlset>",o=e.entries.map(n=>{let l=[];return l.push(" <url>"),l.push(` <loc>${w(n.loc)}</loc>`),n.lastmod&&l.push(` <lastmod>${w(n.lastmod)}</lastmod>`),n.changefreq&&l.push(` <changefreq>${w(n.changefreq)}</changefreq>`),n.priority!==void 0&&l.push(` <priority>${n.priority.toFixed(1)}</priority>`),l.push(" </url>"),l.join(`
2
+ `)});return [t,r,...o,i].join(`
3
+ `)}function J(e,t){let r='<?xml version="1.0" encoding="UTF-8"?>',i='<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',o="</sitemapindex>",n=e.map(l=>{let u=[];return u.push(" <sitemap>"),u.push(` <loc>${w(l.url)}</loc>`),l.lastmod&&u.push(` <lastmod>${w(l.lastmod)}</lastmod>`),u.push(" </sitemap>"),u.join(`
4
+ `)});return [r,i,...n,o].join(`
5
+ `)}function Q(e){let t=[],r=[];e.entries.length===0?t.push("Sitemap must contain at least one URL"):e.entries.length>5e4&&t.push("Sitemap contains more than 50,000 URLs (Google limit)"),e.truncated&&r.push("Sitemap was truncated due to size limits"),e.entries.forEach((o,n)=>{try{new URL(o.loc);}catch{t.push(`Invalid URL at entry ${n+1}: ${o.loc}`);}o.priority!==void 0&&(o.priority<0||o.priority>1)&&t.push(`Invalid priority at entry ${n+1}: must be between 0.0 and 1.0`),o.lastmod&&!M(o.lastmod)&&t.push(`Invalid lastmod date at entry ${n+1}: ${o.lastmod}`),o.loc.length>2048&&r.push(`URL at entry ${n+1} exceeds 2048 character limit`);});let i=new Map;return e.entries.forEach(o=>{let n=i.get(o.loc)??0;i.set(o.loc,n+1);}),i.forEach((o,n)=>{o>1&&t.push(`Duplicate URL found: ${n} (appears ${o} times)`);}),{valid:t.length===0,errors:t,warnings:r}}function P(e){return e.length===0?new Date().toISOString():e.reduce((r,i)=>{let o=new Date(i.updatedAt);return o>r?o:r},new Date(e[0].updatedAt)).toISOString()}function Y(e,t,r=[],i={}){return async function(){let l=(await U(e,t,r,i)).map(a=>({loc:a.url,lastmod:typeof a.lastModified=="string"?a.lastModified:a.lastModified?.toISOString(),changefreq:a.changeFrequency,priority:a.priority})),u={entries:l,totalEntries:l.length,generatedAt:new Date().toISOString(),baseUrl:x(i.canonical?.domain??e.domain,i.canonical?.forceHttps??true)},c=C(u);return new Response(c,{headers:{"Content-Type":"application/xml","Cache-Control":"public, max-age=3600, s-maxage=3600"}})}}function K(e){return async function(){let r=[...e.staticRoutes??[],...e.getStaticRoutes?await e.getStaticRoutes():[]],i=await e.getSite(),o=await e.getArticles(),n=e.getAuthors?await e.getAuthors():[];return [...r,...await U(i,o,n,e.options)]}}function w(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function M(e){try{let t=new Date(e),r=t.toISOString(),i=e.endsWith("Z")&&!e.includes(".")?e.replace("Z",".000Z"):e;return r===i&&!isNaN(t.getTime())}catch{return false}}export{Y as createBlogSitemapRoute,K as createDynamicBlogSitemap,U as generateBlogSitemapEntries,X as generateSitemap,J as generateSitemapIndex,C as sitemapToXml,Q as validateSitemap};//# sourceMappingURL=sitemap.mjs.map
6
+ //# sourceMappingURL=sitemap.mjs.map