-
-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathscrape-tkdodo-blog-images.ts
More file actions
292 lines (239 loc) · 7.14 KB
/
Copy pathscrape-tkdodo-blog-images.ts
File metadata and controls
292 lines (239 loc) · 7.14 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
/**
* Scrapes the current TkDodo RSS posts that tanstack.com includes as external
* blog cards, downloads their article hero images, and writes the generated
* slug-to-image map used by the external blog parser.
*
* Run with: pnpm exec tsx scripts/scrape-tkdodo-blog-images.ts
*/
import { mkdir, writeFile } from 'node:fs/promises'
import { extname, resolve } from 'node:path'
import { load, type CheerioAPI } from 'cheerio'
type FeedItem = {
title: string
link: string
categories: Array<string>
}
type ImageEntry = {
imageUrl: string
localPath: string
slug: string
title: string
}
const FEED_URL = 'https://tkdodo.eu/blog/rss.xml'
const SOURCE_SLUG_PREFIX = 'tkdodo'
const ASSET_DIR = resolve(process.cwd(), 'public/blog-assets/tkdodosblog')
const PUBLIC_ASSET_PREFIX = '/blog-assets/tkdodosblog'
const GENERATED_MAP_PATH = resolve(
process.cwd(),
'src/utils/external-blog-post-images.generated.ts',
)
function normalizeSearchValue(value: string) {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.trim()
}
function includesPhrase(value: string, phrase: string) {
return value.includes(normalizeSearchValue(phrase))
}
function hasWord(value: string, word: string) {
return new RegExp(`\\b${word}\\b`).test(value)
}
function shouldIncludePost(item: FeedItem) {
const signal = normalizeSearchValue(
`${item.title} ${item.link} ${item.categories.join(' ')}`,
)
return (
includesPhrase(signal, 'react query') ||
includesPhrase(signal, 'tanstack query') ||
includesPhrase(signal, 'tan stack query') ||
hasWord(signal, 'query') ||
hasWord(signal, 'queries') ||
includesPhrase(signal, 'tanstack router') ||
includesPhrase(signal, 'tan stack router') ||
hasWord(signal, 'router')
)
}
function slugify(value: string) {
return normalizeSearchValue(value).replace(/\s+/g, '-')
}
function getExternalPostSlug(item: FeedItem) {
try {
const pathnameSlug = new URL(item.link).pathname
.split('/')
.filter(Boolean)
.pop()
if (pathnameSlug) {
return `${SOURCE_SLUG_PREFIX}-${pathnameSlug}`
}
} catch {
// Fall through to the title slug.
}
return `${SOURCE_SLUG_PREFIX}-${slugify(item.title)}`
}
async function fetchText(url: string) {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`)
}
return response.text()
}
async function fetchImage(url: string) {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`)
}
return {
bytes: Buffer.from(await response.arrayBuffer()),
contentType: response.headers.get('content-type') ?? undefined,
}
}
function toAbsoluteUrl(url: string, baseUrl: string) {
return new URL(url, baseUrl).toString()
}
function decodeNetlifyImageSource(src: string, baseUrl: string) {
try {
const url = new URL(src, baseUrl)
const originalUrl = url.searchParams.get('url')
return originalUrl ? toAbsoluteUrl(originalUrl, baseUrl) : undefined
} catch {
return undefined
}
}
function getImageSource(
$: CheerioAPI,
image: Parameters<CheerioAPI>[0],
baseUrl: string,
) {
const $image = $(image)
const source =
$image.attr('url') ??
decodeNetlifyImageSource($image.attr('src') ?? '', baseUrl) ??
$image.attr('src')
return source ? toAbsoluteUrl(source, baseUrl) : undefined
}
function getOgImage($: CheerioAPI, baseUrl: string) {
const image =
$('meta[property="og:image"]').attr('content') ??
$('meta[name="twitter:image"]').attr('content')
return image ? toAbsoluteUrl(image, baseUrl) : undefined
}
function getArticleHeroImageUrl(html: string, articleUrl: string) {
const $ = load(html)
for (const image of $('article img').toArray()) {
const imageUrl = getImageSource($, image, articleUrl)
if (!imageUrl) {
continue
}
const isBlogImage =
imageUrl.includes('/blog/_astro/') ||
imageUrl.includes('/blog/og-images/')
const isReferralImage =
imageUrl.includes('/query-gg.') || imageUrl.includes('/bytes.')
if (isBlogImage && !isReferralImage) {
return imageUrl
}
}
return getOgImage($, articleUrl)
}
function parseFeed(feed: string) {
const $ = load(feed, { xmlMode: true })
return $('item')
.toArray()
.map((item): FeedItem => {
const $item = $(item)
return {
title: $item.children('title').first().text().trim(),
link: $item.children('link').first().text().trim(),
categories: $item
.children('category')
.toArray()
.map((category) => $(category).text().trim())
.filter(Boolean),
}
})
.filter((item) => item.title && item.link && shouldIncludePost(item))
}
function getExtension(url: string, contentType: string | undefined) {
const pathnameExtension = extname(new URL(url).pathname)
if (pathnameExtension) {
return pathnameExtension
}
switch (contentType?.split(';')[0]) {
case 'image/jpeg':
return '.jpg'
case 'image/png':
return '.png'
case 'image/webp':
return '.webp'
default:
return '.jpg'
}
}
function sanitizeFileName(value: string) {
return value.replace(/[^a-z0-9._-]+/gi, '-')
}
function quoteTs(value: string) {
return JSON.stringify(value)
}
function renderGeneratedMap(entries: Array<ImageEntry>) {
const sortedEntries = [...entries].sort((a, b) =>
a.slug.localeCompare(b.slug),
)
const lines = [
'// Generated by scripts/scrape-tkdodo-blog-images.ts. Do not edit manually.',
'export const externalBlogPostHeaderImages = {',
' tkdodo: {',
...sortedEntries.map(
(entry) => ` ${quoteTs(entry.slug)}: ${quoteTs(entry.localPath)},`,
),
' },',
'} as const satisfies Record<string, Record<string, string>>',
'',
]
return lines.join('\n')
}
async function scrapePostImage(
item: FeedItem,
): Promise<ImageEntry | undefined> {
const slug = getExternalPostSlug(item)
const html = await fetchText(item.link)
const imageUrl = getArticleHeroImageUrl(html, item.link)
if (!imageUrl) {
console.warn(`[skip] ${slug}: no article image found`)
return undefined
}
const image = await fetchImage(imageUrl)
const fileSlug = slug.replace(`${SOURCE_SLUG_PREFIX}-`, '')
const fileName = `${sanitizeFileName(fileSlug)}${getExtension(
imageUrl,
image.contentType,
)}`
const localPath = `${PUBLIC_ASSET_PREFIX}/${fileName}`
await writeFile(resolve(ASSET_DIR, fileName), image.bytes)
console.log(`[ok] ${slug} -> ${localPath}`)
return {
imageUrl,
localPath,
slug,
title: item.title,
}
}
async function main() {
await mkdir(ASSET_DIR, { recursive: true })
const items = parseFeed(await fetchText(FEED_URL))
const entries: Array<ImageEntry> = []
console.log(`Found ${items.length} matching TkDodo posts`)
for (const item of items) {
const entry = await scrapePostImage(item)
if (entry) {
entries.push(entry)
}
}
await writeFile(GENERATED_MAP_PATH, renderGeneratedMap(entries))
console.log(`Wrote ${entries.length} image mappings to ${GENERATED_MAP_PATH}`)
}
main().catch((error) => {
console.error(error)
process.exit(1)
})