@xexr/blog-platform 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/app/blog/[slug]/page.d.ts +68 -0
  3. package/dist/app/blog/[slug]/page.tsx +155 -113
  4. package/dist/components/ArticleReadingProgress.tsx +208 -0
  5. package/dist/components/ArticleTopActions.tsx +179 -0
  6. package/dist/components/AuthorByline.tsx +569 -0
  7. package/dist/components/ExpandableArticleImage.tsx +79 -0
  8. package/dist/components/Pagination.tsx +236 -0
  9. package/dist/components/TopicArchivePages.tsx +204 -0
  10. package/dist/components/ui/badge.tsx +36 -0
  11. package/dist/components/ui/button.tsx +59 -0
  12. package/dist/components/ui/card.tsx +92 -0
  13. package/dist/components/ui/pagination.tsx +127 -0
  14. package/dist/components/ui/separator.tsx +29 -0
  15. package/dist/index.d.mts +59 -69
  16. package/dist/index.d.ts +59 -69
  17. package/dist/index.js +83 -8
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +83 -8
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/lib/article-ui.ts +158 -0
  22. package/dist/lib/auth.ts +354 -0
  23. package/dist/lib/cors.ts +243 -0
  24. package/dist/lib/database.ts +277 -0
  25. package/dist/lib/init.ts +186 -0
  26. package/dist/lib/mdx.ts +73 -0
  27. package/dist/lib/metadata.ts +558 -0
  28. package/dist/lib/ratelimit.ts +224 -0
  29. package/dist/lib/security-headers.ts +322 -0
  30. package/dist/lib/seo.ts +295 -0
  31. package/dist/lib/sitemap.ts +719 -0
  32. package/dist/lib/storage/drizzle.ts +400 -0
  33. package/dist/lib/structured-data.ts +608 -0
  34. package/dist/lib/topics.ts +56 -0
  35. package/dist/lib/urls.ts +29 -0
  36. package/dist/lib/utils.ts +6 -0
  37. package/dist/lib/version.ts +154 -0
  38. package/dist/types/contracts.ts +256 -0
  39. package/dist/types/index.d.mts +18 -1
  40. package/dist/types/index.d.ts +18 -1
  41. package/dist/types/index.ts +16 -0
  42. package/package.json +14 -9
@@ -0,0 +1,719 @@
1
+ /**
2
+ * Next.js-compatible sitemap generation utilities for blog platform integration.
3
+ *
4
+ * These utilities generate sitemap entries that follow Next.js MetadataRoute.Sitemap
5
+ * conventions, allowing seamless integration with existing Next.js applications.
6
+ *
7
+ * @example Integration with existing Next.js sitemap:
8
+ * ```typescript
9
+ * // app/sitemap.ts
10
+ * import { generateBlogSitemapEntries } from '@xexr/blog-platform';
11
+ * import type { MetadataRoute } from 'next';
12
+ *
13
+ * export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
14
+ * // Your existing routes
15
+ * const staticRoutes = [
16
+ * { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },
17
+ * { url: 'https://yoursite.com/about', lastModified: new Date(), priority: 0.8 }
18
+ * ];
19
+ *
20
+ * // Blog platform entries
21
+ * const blogEntries = await generateBlogSitemapEntries(blogConfig);
22
+ *
23
+ * return [...staticRoutes, ...blogEntries];
24
+ * }
25
+ * ```
26
+ */
27
+
28
+ import type { PublishedArticle, PublishedSite, PublishedAuthor } from '../types/contracts';
29
+ import { generateCanonicalUrl, normalizeDomain, type CanonicalUrlOptions } from './seo';
30
+
31
+ /**
32
+ * Configuration options for sitemap generation.
33
+ */
34
+ export interface SitemapOptions {
35
+ /** Canonical URL configuration */
36
+ canonical?: CanonicalUrlOptions;
37
+
38
+ /** Whether to include author pages in sitemap */
39
+ includeAuthorPages?: boolean;
40
+
41
+ /** Whether to include pagination pages in sitemap */
42
+ includePaginationPages?: boolean;
43
+
44
+ /** Number of articles per page for pagination calculation */
45
+ articlesPerPage?: number;
46
+
47
+ /** Maximum number of sitemap entries (defaults to 50,000 per Google guidelines) */
48
+ maxEntries?: number;
49
+
50
+ /** Change frequency for different page types */
51
+ changeFrequency?: {
52
+ /** Change frequency for blog home page */
53
+ homePage?: SitemapChangeFreq;
54
+ /** Change frequency for article pages */
55
+ articles?: SitemapChangeFreq;
56
+ /** Change frequency for author pages */
57
+ authorPages?: SitemapChangeFreq;
58
+ /** Change frequency for pagination pages */
59
+ paginationPages?: SitemapChangeFreq;
60
+ };
61
+
62
+ /** Priority values for different page types */
63
+ priority?: {
64
+ /** Priority for blog home page (0.0-1.0) */
65
+ homePage?: number;
66
+ /** Priority for article pages (0.0-1.0) */
67
+ articles?: number;
68
+ /** Priority for author pages (0.0-1.0) */
69
+ authorPages?: number;
70
+ /** Priority for pagination pages (0.0-1.0) */
71
+ paginationPages?: number;
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Valid sitemap change frequency values as per XML sitemap standard.
77
+ */
78
+ export type SitemapChangeFreq =
79
+ | 'always'
80
+ | 'hourly'
81
+ | 'daily'
82
+ | 'weekly'
83
+ | 'monthly'
84
+ | 'yearly'
85
+ | 'never';
86
+
87
+ /**
88
+ * Next.js MetadataRoute.Sitemap compatible entry.
89
+ * This matches the expected format for Next.js sitemap generation.
90
+ */
91
+ export interface NextjsSitemapEntry {
92
+ /** The URL of the page */
93
+ url: string;
94
+
95
+ /** Last modification date */
96
+ lastModified?: string | Date;
97
+
98
+ /** Change frequency hint for search engines */
99
+ changeFrequency?: SitemapChangeFreq;
100
+
101
+ /** Priority relative to other URLs on the site (0.0-1.0) */
102
+ priority?: number;
103
+
104
+ /** Alternate language versions (for i18n) */
105
+ alternates?: {
106
+ languages?: Record<string, string>;
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Legacy XML sitemap entry format (for backward compatibility).
112
+ * @deprecated Use NextjsSitemapEntry for new implementations
113
+ */
114
+ export interface SitemapEntry {
115
+ /** The URL of the page */
116
+ loc: string;
117
+
118
+ /** Last modification date as ISO 8601 string */
119
+ lastmod?: string;
120
+
121
+ /** Change frequency hint for search engines */
122
+ changefreq?: SitemapChangeFreq;
123
+
124
+ /** Priority relative to other URLs on the site (0.0-1.0) */
125
+ priority?: number;
126
+ }
127
+
128
+ /**
129
+ * Complete sitemap data structure.
130
+ */
131
+ export interface SitemapData {
132
+ /** All URL entries in the sitemap */
133
+ entries: SitemapEntry[];
134
+
135
+ /** Total number of entries */
136
+ totalEntries: number;
137
+
138
+ /** Whether the sitemap was truncated due to size limits */
139
+ truncated: boolean;
140
+
141
+ /** Generation timestamp */
142
+ generatedAt: string;
143
+
144
+ /** Base URL used for canonical URL generation */
145
+ baseUrl: string;
146
+ }
147
+
148
+ /**
149
+ * Generates Next.js-compatible sitemap entries for blog platform integration.
150
+ *
151
+ * @param site - The published site information
152
+ * @param articles - Array of published articles
153
+ * @param authors - Array of published authors (optional)
154
+ * @param options - Sitemap generation options
155
+ * @returns Array of Next.js MetadataRoute.Sitemap compatible entries
156
+ *
157
+ * @example
158
+ * ```typescript
159
+ * // In your Next.js app/sitemap.ts file:
160
+ * import { generateBlogSitemapEntries } from '@xexr/blog-platform';
161
+ * import type { MetadataRoute } from 'next';
162
+ *
163
+ * export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
164
+ * const blogEntries = await generateBlogSitemapEntries(site, articles, authors, {
165
+ * includeAuthorPages: true,
166
+ * includePaginationPages: true,
167
+ * changeFrequency: { articles: 'monthly' }
168
+ * });
169
+ *
170
+ * return [
171
+ * // Your existing site routes
172
+ * { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },
173
+ * { url: 'https://yoursite.com/about', lastModified: new Date() },
174
+ * // Blog entries
175
+ * ...blogEntries
176
+ * ];
177
+ * }
178
+ * ```
179
+ */
180
+ export async function generateBlogSitemapEntries(
181
+ site: PublishedSite,
182
+ articles: readonly PublishedArticle[],
183
+ authors: readonly PublishedAuthor[] = [],
184
+ options: SitemapOptions = {}
185
+ ): Promise<NextjsSitemapEntry[]> {
186
+ const {
187
+ includeAuthorPages = true,
188
+ includePaginationPages = true,
189
+ articlesPerPage = 10,
190
+ maxEntries = 50000,
191
+ changeFrequency = {},
192
+ priority = {},
193
+ } = options;
194
+
195
+ const entries: NextjsSitemapEntry[] = [];
196
+ const baseUrl = normalizeDomain(
197
+ options.canonical?.domain ?? site.domain,
198
+ options.canonical?.forceHttps ?? true
199
+ );
200
+
201
+ const pathPrefix = options.canonical?.pathPrefix ?? '/blog';
202
+
203
+ // Add blog home page
204
+ entries.push({
205
+ url: `${baseUrl}${pathPrefix}`,
206
+ lastModified: getLatestModificationDate(articles),
207
+ changeFrequency: changeFrequency.homePage ?? 'daily',
208
+ priority: priority.homePage ?? 1.0,
209
+ });
210
+
211
+ // Add individual article pages
212
+ articles.forEach(article => {
213
+ if (entries.length >= maxEntries) return;
214
+
215
+ const articleUrl = generateCanonicalUrl(article, options.canonical);
216
+ entries.push({
217
+ url: articleUrl,
218
+ lastModified: article.updatedAt,
219
+ changeFrequency: changeFrequency.articles ?? 'monthly',
220
+ priority: priority.articles ?? 0.8,
221
+ });
222
+ });
223
+
224
+ // Add author pages if enabled
225
+ if (includeAuthorPages) {
226
+ authors.forEach(author => {
227
+ if (entries.length >= maxEntries) return;
228
+
229
+ const authorUrl = `${baseUrl}${pathPrefix}/authors/${author.slug}`;
230
+
231
+ // Find the latest article by this author for lastModified
232
+ const authorArticles = articles.filter(article =>
233
+ article.author?.id === author.id
234
+ );
235
+ const latestAuthorMod = getLatestModificationDate(authorArticles);
236
+
237
+ entries.push({
238
+ url: authorUrl,
239
+ lastModified: latestAuthorMod,
240
+ changeFrequency: changeFrequency.authorPages ?? 'weekly',
241
+ priority: priority.authorPages ?? 0.6,
242
+ });
243
+ });
244
+ }
245
+
246
+ // Add pagination pages if enabled
247
+ if (includePaginationPages && articles.length > articlesPerPage) {
248
+ const totalPages = Math.ceil(articles.length / articlesPerPage);
249
+
250
+ for (let page = 2; page <= totalPages; page++) {
251
+ if (entries.length >= maxEntries) break;
252
+
253
+ entries.push({
254
+ url: `${baseUrl}${pathPrefix}?page=${page}`,
255
+ lastModified: getLatestModificationDate(articles),
256
+ changeFrequency: changeFrequency.paginationPages ?? 'daily',
257
+ priority: priority.paginationPages ?? 0.5,
258
+ });
259
+ }
260
+ }
261
+
262
+ return entries;
263
+ }
264
+
265
+ /**
266
+ * Legacy sitemap generation for backward compatibility.
267
+ * @deprecated Use generateBlogSitemapEntries for Next.js integration
268
+ *
269
+ * @param site - The published site information
270
+ * @param articles - Array of published articles
271
+ * @param authors - Array of published authors (optional)
272
+ * @param options - Sitemap generation options
273
+ * @returns Complete sitemap data
274
+ */
275
+ export function generateSitemap(
276
+ site: PublishedSite,
277
+ articles: readonly PublishedArticle[],
278
+ authors: readonly PublishedAuthor[] = [],
279
+ options: SitemapOptions = {}
280
+ ): SitemapData {
281
+ const {
282
+ includeAuthorPages = true,
283
+ includePaginationPages = true,
284
+ articlesPerPage = 10,
285
+ maxEntries = 50000,
286
+ changeFrequency = {},
287
+ priority = {},
288
+ } = options;
289
+
290
+ const entries: SitemapEntry[] = [];
291
+ const baseUrl = normalizeDomain(
292
+ options.canonical?.domain ?? site.domain,
293
+ options.canonical?.forceHttps ?? true
294
+ );
295
+
296
+ const pathPrefix = options.canonical?.pathPrefix ?? '/blog';
297
+ const generatedAt = new Date().toISOString();
298
+
299
+ // Calculate total potential entries to determine if truncation will occur
300
+ let potentialEntries = 1; // Home page
301
+ potentialEntries += articles.length; // Article pages
302
+ if (includeAuthorPages) {
303
+ potentialEntries += authors.length; // Author pages
304
+ }
305
+ if (includePaginationPages && articles.length > articlesPerPage) {
306
+ const totalPages = Math.ceil(articles.length / articlesPerPage);
307
+ potentialEntries += totalPages - 1; // Pagination pages (excluding page 1 which is home)
308
+ }
309
+
310
+ const willTruncate = potentialEntries > maxEntries;
311
+
312
+ // Add blog home page
313
+ entries.push({
314
+ loc: `${baseUrl}${pathPrefix}`,
315
+ lastmod: getLatestModificationDate(articles),
316
+ changefreq: changeFrequency.homePage ?? 'daily',
317
+ priority: priority.homePage ?? 1.0,
318
+ });
319
+
320
+ // Add individual article pages
321
+ articles.forEach(article => {
322
+ if (entries.length >= maxEntries) return;
323
+
324
+ const articleUrl = generateCanonicalUrl(article, options.canonical);
325
+ entries.push({
326
+ loc: articleUrl,
327
+ lastmod: article.updatedAt,
328
+ changefreq: changeFrequency.articles ?? 'monthly',
329
+ priority: priority.articles ?? 0.8,
330
+ });
331
+ });
332
+
333
+ // Add author pages if enabled
334
+ if (includeAuthorPages) {
335
+ authors.forEach(author => {
336
+ if (entries.length >= maxEntries) return;
337
+
338
+ const authorUrl = `${baseUrl}${pathPrefix}/authors/${author.slug}`;
339
+
340
+ // Find the latest article by this author for lastmod
341
+ const authorArticles = articles.filter(article =>
342
+ article.author?.id === author.id
343
+ );
344
+ const latestAuthorMod = getLatestModificationDate(authorArticles);
345
+
346
+ entries.push({
347
+ loc: authorUrl,
348
+ lastmod: latestAuthorMod,
349
+ changefreq: changeFrequency.authorPages ?? 'weekly',
350
+ priority: priority.authorPages ?? 0.6,
351
+ });
352
+ });
353
+ }
354
+
355
+ // Add pagination pages if enabled
356
+ if (includePaginationPages && articles.length > articlesPerPage) {
357
+ const totalPages = Math.ceil(articles.length / articlesPerPage);
358
+
359
+ for (let page = 2; page <= totalPages; page++) {
360
+ if (entries.length >= maxEntries) break;
361
+
362
+ entries.push({
363
+ loc: `${baseUrl}${pathPrefix}?page=${page}`,
364
+ lastmod: getLatestModificationDate(articles),
365
+ changefreq: changeFrequency.paginationPages ?? 'daily',
366
+ priority: priority.paginationPages ?? 0.5,
367
+ });
368
+ }
369
+ }
370
+
371
+ return {
372
+ entries,
373
+ totalEntries: entries.length,
374
+ truncated: willTruncate,
375
+ generatedAt,
376
+ baseUrl,
377
+ };
378
+ }
379
+
380
+ /**
381
+ * Converts sitemap data to XML format.
382
+ *
383
+ * @param sitemapData - The sitemap data to convert
384
+ * @returns XML string in sitemap format
385
+ *
386
+ * @example
387
+ * ```typescript
388
+ * const sitemap = generateSitemap(site, articles);
389
+ * const xmlString = sitemapToXml(sitemap);
390
+ * // Use in API route response
391
+ * ```
392
+ */
393
+ export function sitemapToXml(sitemapData: SitemapData): string {
394
+ const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
395
+ const urlsetOpen = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
396
+ const urlsetClose = '</urlset>';
397
+
398
+ const urlEntries = sitemapData.entries.map(entry => {
399
+ const elements: string[] = [];
400
+
401
+ elements.push(` <url>`);
402
+ elements.push(` <loc>${escapeXml(entry.loc)}</loc>`);
403
+
404
+ if (entry.lastmod) {
405
+ elements.push(` <lastmod>${escapeXml(entry.lastmod)}</lastmod>`);
406
+ }
407
+
408
+ if (entry.changefreq) {
409
+ elements.push(` <changefreq>${escapeXml(entry.changefreq)}</changefreq>`);
410
+ }
411
+
412
+ if (entry.priority !== undefined) {
413
+ elements.push(` <priority>${entry.priority.toFixed(1)}</priority>`);
414
+ }
415
+
416
+ elements.push(` </url>`);
417
+
418
+ return elements.join('\n');
419
+ });
420
+
421
+ return [
422
+ xmlHeader,
423
+ urlsetOpen,
424
+ ...urlEntries,
425
+ urlsetClose,
426
+ ].join('\n');
427
+ }
428
+
429
+ /**
430
+ * Generates a sitemap index for large blogs that need multiple sitemaps.
431
+ *
432
+ * @param sitemaps - Array of sitemap information
433
+ * @param baseUrl - Base URL for the site
434
+ * @returns XML string for sitemap index
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * const sitemapIndex = generateSitemapIndex([
439
+ * { url: 'https://example.com/sitemap-articles.xml', lastmod: '2023-01-01T00:00:00Z' },
440
+ * { url: 'https://example.com/sitemap-authors.xml', lastmod: '2023-01-01T00:00:00Z' }
441
+ * ], 'https://example.com');
442
+ * ```
443
+ */
444
+ export function generateSitemapIndex(
445
+ sitemaps: readonly { url: string; lastmod?: string }[],
446
+ _baseUrl: string
447
+ ): string {
448
+ const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
449
+ const indexOpen = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
450
+ const indexClose = '</sitemapindex>';
451
+
452
+ const sitemapEntries = sitemaps.map(sitemap => {
453
+ const elements: string[] = [];
454
+
455
+ elements.push(` <sitemap>`);
456
+ elements.push(` <loc>${escapeXml(sitemap.url)}</loc>`);
457
+
458
+ if (sitemap.lastmod) {
459
+ elements.push(` <lastmod>${escapeXml(sitemap.lastmod)}</lastmod>`);
460
+ }
461
+
462
+ elements.push(` </sitemap>`);
463
+
464
+ return elements.join('\n');
465
+ });
466
+
467
+ return [
468
+ xmlHeader,
469
+ indexOpen,
470
+ ...sitemapEntries,
471
+ indexClose,
472
+ ].join('\n');
473
+ }
474
+
475
+ /**
476
+ * Validates sitemap data for compliance with search engine guidelines.
477
+ *
478
+ * @param sitemapData - The sitemap data to validate
479
+ * @returns Validation results with errors and warnings
480
+ *
481
+ * @example
482
+ * ```typescript
483
+ * const sitemap = generateSitemap(site, articles);
484
+ * const validation = validateSitemap(sitemap);
485
+ *
486
+ * if (validation.errors.length > 0) {
487
+ * console.error('Sitemap errors:', validation.errors);
488
+ * }
489
+ * ```
490
+ */
491
+ export function validateSitemap(sitemapData: SitemapData): {
492
+ valid: boolean;
493
+ errors: string[];
494
+ warnings: string[];
495
+ } {
496
+ const errors: string[] = [];
497
+ const warnings: string[] = [];
498
+
499
+ // Check entry count
500
+ if (sitemapData.entries.length === 0) {
501
+ errors.push('Sitemap must contain at least one URL');
502
+ } else if (sitemapData.entries.length > 50000) {
503
+ errors.push('Sitemap contains more than 50,000 URLs (Google limit)');
504
+ }
505
+
506
+ // Check for truncation
507
+ if (sitemapData.truncated) {
508
+ warnings.push('Sitemap was truncated due to size limits');
509
+ }
510
+
511
+ // Validate individual entries
512
+ sitemapData.entries.forEach((entry, index) => {
513
+ // Validate URL format
514
+ try {
515
+ new URL(entry.loc);
516
+ } catch {
517
+ errors.push(`Invalid URL at entry ${index + 1}: ${entry.loc}`);
518
+ }
519
+
520
+ // Validate priority range
521
+ if (entry.priority !== undefined && (entry.priority < 0 || entry.priority > 1)) {
522
+ errors.push(`Invalid priority at entry ${index + 1}: must be between 0.0 and 1.0`);
523
+ }
524
+
525
+ // Validate lastmod format
526
+ if (entry.lastmod && !isValidISODate(entry.lastmod)) {
527
+ errors.push(`Invalid lastmod date at entry ${index + 1}: ${entry.lastmod}`);
528
+ }
529
+
530
+ // Check URL length (Google limit is 2048 characters)
531
+ if (entry.loc.length > 2048) {
532
+ warnings.push(`URL at entry ${index + 1} exceeds 2048 character limit`);
533
+ }
534
+ });
535
+
536
+ // Check for duplicate URLs
537
+ const urlCounts = new Map<string, number>();
538
+ sitemapData.entries.forEach(entry => {
539
+ const count = urlCounts.get(entry.loc) ?? 0;
540
+ urlCounts.set(entry.loc, count + 1);
541
+ });
542
+
543
+ urlCounts.forEach((count, url) => {
544
+ if (count > 1) {
545
+ errors.push(`Duplicate URL found: ${url} (appears ${count} times)`);
546
+ }
547
+ });
548
+
549
+ return {
550
+ valid: errors.length === 0,
551
+ errors,
552
+ warnings,
553
+ };
554
+ }
555
+
556
+ /**
557
+ * Gets the latest modification date from an array of articles.
558
+ */
559
+ function getLatestModificationDate(articles: readonly PublishedArticle[]): string {
560
+ if (articles.length === 0) {
561
+ return new Date().toISOString();
562
+ }
563
+
564
+ const latestDate = articles.reduce((latest, article) => {
565
+ const articleDate = new Date(article.updatedAt);
566
+ return articleDate > latest ? articleDate : latest;
567
+ }, new Date(articles[0]!.updatedAt));
568
+
569
+ return latestDate.toISOString();
570
+ }
571
+
572
+ /**
573
+ * Creates a separate sitemap specifically for blog content.
574
+ * Useful for large sites that need to split sitemaps by content type.
575
+ *
576
+ * @param site - The published site information
577
+ * @param articles - Array of published articles
578
+ * @param authors - Array of published authors (optional)
579
+ * @param options - Sitemap generation options
580
+ * @returns Next.js sitemap function
581
+ *
582
+ * @example
583
+ * ```typescript
584
+ * // app/blog-sitemap/route.ts - separate blog sitemap endpoint
585
+ * import { createBlogSitemapRoute } from '@xexr/blog-platform';
586
+ *
587
+ * export const GET = createBlogSitemapRoute(site, articles, authors, {
588
+ * includeAuthorPages: true,
589
+ * articlesPerPage: 20
590
+ * });
591
+ * ```
592
+ */
593
+ export function createBlogSitemapRoute(
594
+ site: PublishedSite,
595
+ articles: readonly PublishedArticle[],
596
+ authors: readonly PublishedAuthor[] = [],
597
+ options: SitemapOptions = {}
598
+ ) {
599
+ return async function GET() {
600
+ const entries = await generateBlogSitemapEntries(site, articles, authors, options);
601
+
602
+ // Convert to Next.js sitemap format and return as XML
603
+ const xmlEntries = entries.map(entry => ({
604
+ loc: entry.url,
605
+ lastmod: typeof entry.lastModified === 'string'
606
+ ? entry.lastModified
607
+ : entry.lastModified?.toISOString(),
608
+ changefreq: entry.changeFrequency,
609
+ priority: entry.priority,
610
+ }));
611
+
612
+ const sitemapData = {
613
+ entries: xmlEntries,
614
+ totalEntries: xmlEntries.length,
615
+ truncated: false,
616
+ generatedAt: new Date().toISOString(),
617
+ baseUrl: normalizeDomain(
618
+ options.canonical?.domain ?? site.domain,
619
+ options.canonical?.forceHttps ?? true
620
+ ),
621
+ };
622
+
623
+ const xml = sitemapToXml(sitemapData);
624
+
625
+ return new Response(xml, {
626
+ headers: {
627
+ 'Content-Type': 'application/xml',
628
+ 'Cache-Control': 'public, max-age=3600, s-maxage=3600',
629
+ },
630
+ });
631
+ };
632
+ }
633
+
634
+ /**
635
+ * Configuration interface for blog data fetching.
636
+ * Used to fetch blog data for sitemap generation.
637
+ */
638
+ export interface BlogSitemapConfig {
639
+ /** Function to fetch site data */
640
+ getSite: () => Promise<PublishedSite>;
641
+
642
+ /** Function to fetch published articles */
643
+ getArticles: () => Promise<readonly PublishedArticle[]>;
644
+
645
+ /** Function to fetch authors (optional) */
646
+ getAuthors?: () => Promise<readonly PublishedAuthor[]>;
647
+
648
+ /** Sitemap generation options */
649
+ options?: SitemapOptions;
650
+ }
651
+
652
+ /**
653
+ * Higher-order function that creates a Next.js sitemap function with data fetching.
654
+ * Ideal for dynamic blog content that needs to be fetched at sitemap generation time.
655
+ *
656
+ * @param config - Configuration for fetching blog data
657
+ * @returns Next.js sitemap function
658
+ *
659
+ * @example
660
+ * ```typescript
661
+ * // app/sitemap.ts
662
+ * import { createDynamicBlogSitemap } from '@xexr/blog-platform';
663
+ * import { getBlogData } from './lib/blog';
664
+ *
665
+ * export default createDynamicBlogSitemap({
666
+ * getSite: () => getBlogData().site,
667
+ * getArticles: () => getBlogData().articles,
668
+ * getAuthors: () => getBlogData().authors,
669
+ * options: {
670
+ * includeAuthorPages: true,
671
+ * changeFrequency: { articles: 'weekly' }
672
+ * }
673
+ * });
674
+ * ```
675
+ */
676
+ export function createDynamicBlogSitemap(config: BlogSitemapConfig) {
677
+ return async function sitemap(): Promise<NextjsSitemapEntry[]> {
678
+ const site = await config.getSite();
679
+ const articles = await config.getArticles();
680
+ const authors = config.getAuthors ? await config.getAuthors() : [];
681
+
682
+ return generateBlogSitemapEntries(site, articles, authors, config.options);
683
+ };
684
+ }
685
+
686
+ /**
687
+ * Escapes special XML characters for safe inclusion in XML content.
688
+ */
689
+ function escapeXml(text: string): string {
690
+ const xmlEscapes: Record<string, string> = {
691
+ '&': '&amp;',
692
+ '<': '&lt;',
693
+ '>': '&gt;',
694
+ '"': '&quot;',
695
+ "'": '&#x27;',
696
+ };
697
+
698
+ return text.replace(/[&<>"']/g, char => xmlEscapes[char] ?? char);
699
+ }
700
+
701
+ /**
702
+ * Validates if a string is a valid ISO 8601 date.
703
+ */
704
+ function isValidISODate(dateString: string): boolean {
705
+ try {
706
+ const date = new Date(dateString);
707
+ const isoString = date.toISOString();
708
+
709
+ // Handle both formats: with and without milliseconds
710
+ // 2023-01-01T00:00:00.000Z and 2023-01-01T00:00:00Z are both valid
711
+ const normalizedInput = dateString.endsWith('Z') && !dateString.includes('.')
712
+ ? dateString.replace('Z', '.000Z')
713
+ : dateString;
714
+
715
+ return isoString === normalizedInput && !isNaN(date.getTime());
716
+ } catch {
717
+ return false;
718
+ }
719
+ }