-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseo.ts
More file actions
217 lines (190 loc) · 6.47 KB
/
Copy pathseo.ts
File metadata and controls
217 lines (190 loc) · 6.47 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
import { SITE_TITLE, SITE_DESCRIPTION, SITE_URL, AUTHOR, SEO_CONFIG } from '../consts';
import { SOCIAL_IMAGE_MANIFEST } from '../data/socialImageManifest';
// Simplified SEO configuration interface
export interface SEOConfig {
title: string;
description?: string;
path?: string;
heroImage?: string; // Primary image for social sharing
imageAlt?: string;
author?: string;
keywords?: string[];
pubDate?: Date;
updatedDate?: Date;
type?: 'website' | 'article';
locale?: string;
robots?: string;
}
// Simplified meta tags interface
export interface MetaTags {
title: string;
description: string;
canonical: string;
ogImage: string;
ogImageAlt: string;
author: string;
keywords: string;
pubDate?: string;
updatedDate?: string;
robots: string;
locale: string;
ogType: 'website' | 'article';
}
/** Strip trailing slashes except for the site root. */
export function normalizeSeoPath(path: string): string {
if (!path || path === '/') return '/';
// Absolute URLs: normalize pathname only
if (/^https?:\/\//i.test(path)) {
const url = new URL(path);
url.pathname = url.pathname.length > 1 ? url.pathname.replace(/\/+$/, '') : '/';
return `${url.pathname}${url.search}${url.hash}`;
}
const [pathname, ...rest] = path.split('?');
const cleanPath = pathname.length > 1 ? pathname.replace(/\/+$/, '') : '/';
return rest.length ? `${cleanPath}?${rest.join('?')}` : cleanPath;
}
// Generate canonical URL (always absolute, no trailing slash except homepage)
export function generateCanonicalUrl(path: string): string {
const normalized = normalizeSeoPath(path);
return new URL(normalized, SITE_URL).href;
}
// Generate image URL for social/meta tags, with proper heroImage prioritization.
// Uses a build-time manifest to map AVIF (and other) originals to social-safe JPEG/PNG variants.
export function generateImageUrl(heroImage?: string): string {
// Priority: heroImage > default social image
const originalPath = heroImage || SEO_CONFIG.defaultImage;
// If we have a generated social-safe variant for this path, prefer it.
// Keys are web paths like "/foo/bar.avif".
const socialPath = SOCIAL_IMAGE_MANIFEST[originalPath] || originalPath;
return new URL(socialPath, SITE_URL).href;
}
// Detect Open Graph type
export function detectOGType(pubDate?: Date, type?: string): 'article' | 'website' {
return pubDate || type === 'article' ? 'article' : 'website';
}
// Generate optimized meta tags
export function generateMetaTags(config: SEOConfig): MetaTags {
const {
title,
description = SITE_DESCRIPTION,
path,
heroImage,
imageAlt,
author = AUTHOR.name,
keywords = [],
pubDate,
updatedDate,
type,
locale = SEO_CONFIG.defaultLocale,
robots = SEO_CONFIG.defaultRobots,
} = config;
// Special handling for homepage and different page types
const isHomepage = path === '/' || path === '';
const isAboutPage = path === '/about' || title.toLowerCase().includes('about antonio');
const titleSuffix = 'Notes by Antonio Rodriguez Martinez';
let fullTitle: string;
if (isHomepage) {
fullTitle = titleSuffix;
} else if (isAboutPage) {
fullTitle = 'About Antonio Rodriguez Martinez';
} else {
fullTitle = `${title} | ${titleSuffix}`;
}
const canonical = path ? generateCanonicalUrl(path) : '';
const ogImage = generateImageUrl(heroImage);
const ogImageAlt = imageAlt || `${title} - ${SITE_TITLE}`;
const ogType = detectOGType(pubDate, type);
return {
title: fullTitle,
description,
canonical,
ogImage,
ogImageAlt,
author,
keywords: keywords.join(', '),
pubDate: pubDate?.toISOString(),
updatedDate: updatedDate?.toISOString(),
robots,
locale,
ogType,
};
}
export interface HreflangAlternate {
hreflang: string;
href: string;
}
// Generate keywords from tags and categories
export function generateKeywords(tags?: string[], categories?: string[]): string[] {
const keywords: string[] = [];
if (tags) keywords.push(...tags);
if (categories) keywords.push(...categories);
return [...new Set(keywords)]; // Remove duplicates
}
// Generate image alt text
export function generateImageAlt(title: string): string {
return `${title} - ${SITE_TITLE}`;
}
// Generate enhanced sitemap data with priority and change frequency
export function generateSitemapData(
urls: Array<{
url: string;
lastmod?: Date;
changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
priority?: number;
type?: 'article' | 'category' | 'tag' | 'page';
}>,
) {
return urls.map(({ url, lastmod, changefreq, priority, type }) => ({
url,
lastmod: lastmod?.toISOString(),
changefreq: changefreq || (type === 'article' ? 'monthly' : 'weekly'),
priority: priority || (type === 'article' ? 0.8 : 0.6),
}));
}
// Generate robots.txt content with enhanced directives
export function generateRobotsTxt(sitemapUrl: string, additionalRules?: string[]) {
const baseRules = [
'User-agent: *',
'Allow: /',
// Utility pages (/test-theme, /tag-management) use meta noindex instead of Disallow
// so crawlers can see and honor the robots directive.
'Disallow: /temp/',
'Disallow: /dev/',
'Allow: /rss.xml',
'Allow: /feed.json',
`Sitemap: ${sitemapUrl}`,
];
return [...baseRules, ...(additionalRules || [])].join('\n');
}
// Generate enhanced meta description with better length optimization
export function generateOptimizedDescription(description: string, maxLength: number = 160): string {
if (description.length <= maxLength) return description;
// Try to break at sentence boundaries
const sentences = description.split(/[.!?]+/);
let optimized = '';
for (const sentence of sentences) {
const testLength = optimized.length + sentence.length + 1;
if (testLength <= maxLength) {
optimized += (optimized ? '. ' : '') + sentence;
} else {
break;
}
}
// If we still don't have a good length, truncate at word boundary
if (optimized.length < maxLength * 0.7) {
const words = description.split(' ');
optimized = '';
for (const word of words) {
const testLength = optimized.length + word.length + 1;
if (testLength <= maxLength) {
optimized += (optimized ? ' ' : '') + word;
} else {
break;
}
}
}
return optimized || description.substring(0, maxLength - 3) + '...';
}
// Constants for consistent usage
export const DEFAULT_ROBOTS = SEO_CONFIG.defaultRobots;
export const DEFAULT_LOCALE = SEO_CONFIG.defaultLocale;