-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructuredData.ts
More file actions
662 lines (619 loc) · 17.9 KB
/
Copy pathstructuredData.ts
File metadata and controls
662 lines (619 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
import type { CollectionEntry } from 'astro:content';
import {
SITE_TITLE,
SITE_DESCRIPTION,
SITE_URL,
AUTHOR,
SOCIAL_LINKS,
SEO_CONFIG,
} from '../consts';
import { generateCanonicalUrl, generateImageUrl } from './seo';
// Enhanced structured data options
export interface StructuredDataOptions {
title: string;
description: string;
path: string;
type?: 'website' | 'article' | 'category' | 'tag';
// Article-specific fields
pubDate?: Date;
updatedDate?: Date;
heroImage?: string;
keywords?: string[];
minutesRead?: string; // Reading time from remark plugin
// Collection-specific fields
posts?: CollectionEntry<'blog'>[];
identifier?: string;
// Enhanced fields for better SEO
category?: string[];
tags?: string[];
tableOfContents?: boolean;
hasComments?: boolean;
featured?: boolean;
draft?: boolean;
inLanguage?: string;
wordCount?: number;
}
// Generate enhanced structured data with improved SEO
export function generateStructuredData(options: StructuredDataOptions) {
const {
title,
description,
path,
type = 'website',
pubDate,
updatedDate,
heroImage,
keywords = [],
minutesRead,
posts = [],
identifier,
category = [],
tags = [],
tableOfContents = false,
featured = false,
draft = false,
inLanguage = 'en-US',
wordCount,
} = options;
const url = generateCanonicalUrl(path);
const schemas: any[] = [];
// Base WebSite schema for all pages (no SearchAction — site search is client-only)
schemas.push({
'@context': 'https://schema.org',
'@type': 'WebSite',
name: SITE_TITLE,
description: SITE_DESCRIPTION,
url: SITE_URL,
inLanguage: 'en-US',
publisher: {
'@type': 'Person',
name: AUTHOR.name,
url: AUTHOR.url,
},
});
// Enhanced Organization schema
schemas.push({
'@context': 'https://schema.org',
'@type': 'Organization',
name: SEO_CONFIG.organizationName,
url: SITE_URL,
inLanguage: 'en-US',
logo: {
'@type': 'ImageObject',
url: generateImageUrl(SEO_CONFIG.organizationLogo),
width: SEO_CONFIG.organizationLogoWidth,
height: SEO_CONFIG.organizationLogoHeight,
},
sameAs: Object.values(SOCIAL_LINKS),
// Enhanced organization details
description: SITE_DESCRIPTION,
foundingDate: '2024', // Adjust based on your actual founding date
areaServed: 'Worldwide',
serviceType: 'Personal Blog & Content Creation',
});
// Enhanced Person schema for author
schemas.push({
'@context': 'https://schema.org',
'@type': 'Person',
name: AUTHOR.name,
url: AUTHOR.url,
inLanguage: 'en-US',
sameAs: [SOCIAL_LINKS.twitter, SOCIAL_LINKS.github, SOCIAL_LINKS.bluesky],
jobTitle: 'Software Engineer & Writer',
worksFor: {
'@type': 'Organization',
name: SEO_CONFIG.organizationName,
},
knowsAbout: [
'Software Development',
'Personal Growth',
'Mental Health',
'Parenting',
'Technology',
'Thinking',
'Fatherhood',
'Masculinity',
'Culture',
'Modern Collapse',
'Philosophy',
'Cultural Navigation',
],
// Enhanced author details
description:
'Software engineer and writer exploring fatherhood, masculinity, and modern life through raw, unfiltered reflection.',
alumniOf: {
'@type': 'Organization',
name: 'Software Engineering Community',
},
hasOccupation: {
'@type': 'Occupation',
name: 'Software Engineer',
description: "Building digital solutions and exploring technology's impact on modern life",
},
});
// Type-specific schemas
if (type === 'article' && pubDate) {
// Enhanced BlogPosting schema
const articleSchema = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: title,
description: description,
image: generateImageUrl(heroImage),
datePublished: pubDate.toISOString(),
dateModified: updatedDate?.toISOString() || pubDate.toISOString(),
author: {
'@type': 'Person',
name: AUTHOR.name,
url: AUTHOR.url,
},
publisher: {
'@type': 'Organization',
name: SEO_CONFIG.organizationName,
url: SITE_URL,
logo: {
'@type': 'ImageObject',
url: generateImageUrl(SEO_CONFIG.organizationLogo),
},
},
keywords: keywords.join(', '),
timeRequired: (() => {
if (minutesRead && typeof minutesRead === 'string') {
// Extract minutes from "X min read" format
const match = minutesRead.match(/(\d+)/);
return match ? `PT${match[1]}M` : undefined;
}
return undefined;
})(),
url: url,
inLanguage,
// Prefer primary category; otherwise a short tag summary; else a stable default.
articleSection:
category.length > 0
? category[0]
: tags.length > 0
? tags.slice(0, 3).join(', ')
: 'Personal Growth',
...(typeof wordCount === 'number' && wordCount > 0 && { wordCount }),
// Enhanced article properties
mainEntityOfPage: {
'@type': 'WebPage',
'@id': url,
},
isPartOf: {
'@type': 'Blog',
name: SITE_TITLE,
url: SITE_URL,
},
// Content classification
...(category.length > 0 && {
about: category.map((cat) => ({
'@type': 'Thing',
name: cat,
})),
}),
// Enhanced metadata
...(featured && { isAccessibleForFree: true }),
...(draft && { isAccessibleForFree: false }),
// Reading experience indicators
...(tableOfContents && {
hasPart: {
'@type': 'WebPageElement',
name: 'Table of Contents',
description: 'Structured navigation for this article',
},
}),
};
schemas.push(articleSchema);
// Add breadcrumb schema for blog posts
const breadcrumbSchema = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: [
{
'@type': 'ListItem',
position: 1,
name: 'Home',
item: SITE_URL,
},
...(category.length > 0
? [
{
'@type': 'ListItem',
position: 2,
name: category[0],
item: generateCanonicalUrl(`/category/${category[0]}`),
},
]
: []),
{
'@type': 'ListItem',
position: category.length > 0 ? 3 : 2,
name: title,
item: url,
},
],
};
schemas.push(breadcrumbSchema);
} else if ((type === 'category' || type === 'tag') && posts.length > 0) {
schemas.push({
'@context': 'https://schema.org',
'@type': 'CollectionPage',
name: title,
description: description,
url: url,
mainEntity: {
'@type': 'ItemList',
numberOfItems: posts.length,
itemListElement: posts.map((post, index) => ({
'@type': 'ListItem',
position: index + 1,
item: {
'@type': 'BlogPosting',
headline: post.data.title,
description: post.data.description,
url: generateCanonicalUrl(`/p/${post.id}`),
datePublished: post.data.pubDate.toISOString(),
dateModified: post.data.updatedDate?.toISOString() || post.data.pubDate.toISOString(),
author: {
'@type': 'Person',
name: AUTHOR.name,
url: AUTHOR.url,
},
image: generateImageUrl(post.data.heroImage),
keywords: post.data.tags?.join(', '),
articleSection: post.data.category?.join(', '),
timeRequired: (() => {
if (post.data.minutesRead && typeof post.data.minutesRead === 'string') {
// Extract minutes from "X min read" format
const match = post.data.minutesRead.match(/(\d+)/);
return match ? `PT${match[1]}M` : undefined;
}
return undefined;
})(),
},
})),
},
breadcrumb: {
'@type': 'BreadcrumbList',
itemListElement: [
{
'@type': 'ListItem',
position: 1,
name: 'Home',
item: SITE_URL,
},
{
'@type': 'ListItem',
position: 2,
name: type === 'category' ? 'Categories' : 'Tags',
item: generateCanonicalUrl(type === 'category' ? '/category' : '/tag'),
},
{
'@type': 'ListItem',
position: 3,
name: title,
item: url,
},
],
},
inLanguage: 'en-US',
...(type === 'category' && identifier
? {
about: {
'@type': 'Thing',
name: identifier,
description: description,
},
}
: {}),
...(type === 'tag' && identifier ? { keywords: identifier } : {}),
});
}
return schemas.length === 1 ? schemas[0] : schemas;
}
// Generate FAQ schema for content that might benefit from it
export function generateFAQSchema(questions: Array<{ question: string; answer: string }>) {
if (!questions || questions.length === 0) return null;
return {
'@context': 'https://schema.org',
'@type': 'FAQPage',
mainEntity: questions.map((q) => ({
'@type': 'Question',
name: q.question,
acceptedAnswer: {
'@type': 'Answer',
text: q.answer,
},
})),
};
}
// Generate HowTo schema for tutorial/instructional content
export function generateHowToSchema(options: {
name: string;
description: string;
steps: Array<{ name: string; text: string; image?: string }>;
totalTime?: string;
tools?: string[];
materials?: string[];
}) {
const { name, description, steps, totalTime, tools, materials } = options;
return {
'@context': 'https://schema.org',
'@type': 'HowTo',
name,
description,
...(totalTime && { totalTime }),
...(tools &&
tools.length > 0 && {
tool: tools.map((tool) => ({
'@type': 'HowToTool',
name: tool,
})),
}),
...(materials &&
materials.length > 0 && {
material: materials.map((material) => ({
'@type': 'HowToMaterial',
name: material,
})),
}),
step: steps.map((step, index) => ({
'@type': 'HowToStep',
position: index + 1,
name: step.name,
text: step.text,
...(step.image && {
image: generateImageUrl(step.image),
}),
})),
};
}
// Auto-detect FAQ content from markdown and generate schema
export function autoDetectFAQSchema(content: string): any | null {
// Look for common FAQ patterns in markdown
const faqPatterns = [
// Q&A format with ## or ### headers
/##\s*(?:Q|Question|FAQ|Frequently Asked Question)[:\s]*([^\n]+)/gi,
/###\s*(?:Q|Question|FAQ|Frequently Asked Question)[:\s]*([^\n]+)/gi,
// Bold questions followed by answers
/\*\*([^*]+)\*\*\s*\n+([^*\n]+(?:\n[^*\n]+)*)/g,
// Questions ending with question marks followed by answers
/([^.!?]+\?)\s*\n+([^.!?]+(?:\n[^.!?]+)*)/g,
];
const questions: Array<{ question: string; answer: string }> = [];
// Try to extract questions and answers
for (const pattern of faqPatterns) {
const matches = content.matchAll(pattern);
for (const match of matches) {
if (match[1] && match[2]) {
const question = match[1].trim();
const answer = match[2].trim();
// Filter out very short or very long Q&As
if (
question.length > 10 &&
question.length < 200 &&
answer.length > 20 &&
answer.length < 1000
) {
questions.push({ question, answer });
}
}
}
}
// If we found reasonable FAQ content, generate schema
if (questions.length >= 2) {
return generateFAQSchema(questions);
}
return null;
}
// Generate Review schema for review/rating content
export function generateReviewSchema(options: {
name: string;
description: string;
rating?: number;
bestRating?: number;
worstRating?: number;
author: string;
reviewBody: string;
itemReviewed?: string;
}) {
const {
name,
description,
rating,
bestRating = 5,
worstRating = 1,
author,
reviewBody,
itemReviewed,
} = options;
return {
'@context': 'https://schema.org',
'@type': 'Review',
name,
description,
...(rating && {
reviewRating: {
'@type': 'Rating',
ratingValue: rating,
bestRating,
worstRating,
},
}),
author: {
'@type': 'Person',
name: author,
},
reviewBody,
...(itemReviewed && {
itemReviewed: {
'@type': 'Thing',
name: itemReviewed,
},
}),
};
}
// Generate Article schema for general content (alternative to BlogPosting)
export function generateArticleSchema(options: {
headline: string;
description: string;
image?: string;
datePublished: Date;
dateModified?: Date;
author: string;
publisher: string;
url: string;
articleBody?: string;
wordCount?: number;
keywords?: string[];
articleSection?: string;
}) {
const {
headline,
description,
image,
datePublished,
dateModified,
author,
publisher,
url,
articleBody,
wordCount,
keywords,
articleSection,
} = options;
return {
'@context': 'https://schema.org',
'@type': 'Article',
headline,
description,
...(image && { image: generateImageUrl(image) }),
datePublished: datePublished.toISOString(),
...(dateModified && { dateModified: dateModified.toISOString() }),
author: {
'@type': 'Person',
name: author,
},
publisher: {
'@type': 'Organization',
name: publisher,
},
url,
...(articleBody && { articleBody }),
...(wordCount && { wordCount }),
...(keywords && keywords.length > 0 && { keywords: keywords.join(', ') }),
...(articleSection && { articleSection }),
inLanguage: 'en-US',
};
}
// Enhanced structured data generation with automatic FAQ detection
export function generateEnhancedStructuredData(
options: StructuredDataOptions & { content?: string },
) {
const baseSchemas = generateStructuredData(options);
// If we have content and it's an article, try to auto-detect FAQ content
if (options.content && options.type === 'article') {
const faqSchema = autoDetectFAQSchema(options.content);
if (faqSchema) {
// If baseSchemas is an array, add FAQ schema to it
if (Array.isArray(baseSchemas)) {
return [...baseSchemas, faqSchema];
} else {
return [baseSchemas, faqSchema];
}
}
}
return baseSchemas;
}
// Generate structured data for specific content types
export function generateContentTypeSpecificSchema(contentType: string, options: any) {
switch (contentType) {
case 'tutorial':
case 'how-to':
return generateHowToSchema(options);
case 'review':
return generateReviewSchema(options);
case 'faq':
return generateFAQSchema(options.questions || []);
default:
return null;
}
}
// Validate structured data for common issues
export function validateStructuredData(schema: any): {
isValid: boolean;
errors: string[];
warnings: string[];
} {
const errors: string[] = [];
const warnings: string[] = [];
// Basic validation
if (!schema || typeof schema !== 'object') {
errors.push('Schema must be a valid object');
return { isValid: false, errors, warnings };
}
// Check required fields
if (!schema['@context'] || schema['@context'] !== 'https://schema.org') {
errors.push('Schema must include @context: https://schema.org');
}
if (!schema['@type']) {
errors.push('Schema must include @type');
}
// Validate specific schema types
if (schema['@type'] === 'BlogPosting') {
if (!schema.headline) warnings.push('BlogPosting should include headline');
if (!schema.author) warnings.push('BlogPosting should include author');
if (!schema.datePublished) warnings.push('BlogPosting should include datePublished');
}
if (schema['@type'] === 'Person') {
if (!schema.name) warnings.push('Person should include name');
if (!schema.url) warnings.push('Person should include url');
}
if (schema['@type'] === 'Organization') {
if (!schema.name) warnings.push('Organization should include name');
if (!schema.url) warnings.push('Organization should include url');
}
// Check for common issues
if (schema.url && !schema.url.startsWith('http')) {
warnings.push('URLs should be absolute URLs');
}
if (schema.image && !schema.image.startsWith('http')) {
warnings.push('Image URLs should be absolute URLs');
}
// Check for circular references
const checkCircular = (obj: any, path: string[] = []): boolean => {
if (typeof obj === 'object' && obj !== null) {
for (const key in obj) {
if (path.includes(obj[key])) {
warnings.push(`Potential circular reference detected at ${path.join('.')}.${key}`);
return true;
}
if (typeof obj[key] === 'object' && obj[key] !== null) {
if (checkCircular(obj[key], [...path, key])) {
return true;
}
}
}
}
return false;
};
checkCircular(schema);
return {
isValid: errors.length === 0,
errors,
warnings,
};
}
// Generate structured data summary for debugging
export function generateStructuredDataSummary(schemas: any[]): string {
const summary = schemas.map((schema, index) => {
const validation = validateStructuredData(schema);
return `Schema ${index + 1} (${schema['@type'] || 'Unknown'}): ${
validation.isValid ? 'Valid' : 'Invalid'
}${validation.errors.length > 0 ? ` - Errors: ${validation.errors.join(', ')}` : ''}${
validation.warnings.length > 0 ? ` - Warnings: ${validation.warnings.join(', ')}` : ''
}`;
});
return summary.join('\n');
}