-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathblog.ts
More file actions
274 lines (241 loc) · 8.59 KB
/
blog.ts
File metadata and controls
274 lines (241 loc) · 8.59 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
import { join } from 'node:path'
import Markdown from 'unplugin-vue-markdown/vite'
import { addTemplate, addVitePlugin, defineNuxtModule, useNuxt, createResolver } from 'nuxt/kit'
import shiki from '@shikijs/markdown-exit'
import MarkdownItAnchor from 'markdown-it-anchor'
import { defu } from 'defu'
import { read } from 'gray-matter'
import { array, safeParse } from 'valibot'
import { Feed } from 'feed'
import {
AuthorSchema,
RawBlogPostSchema,
type Author,
type BlogPostFrontmatter,
type ResolvedAuthor,
} from '../shared/schemas/blog'
import { isProduction } from '../config/env'
import { BLUESKY_API } from '../shared/utils/constants'
import { glob, mkdir, writeFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import crypto from 'node:crypto'
/**
* Fetches Bluesky avatars for a set of authors at build time.
* Returns a map of handle → avatar URL.
*/
async function fetchBlueskyAvatars(
imagesDir: string,
handles: string[],
): Promise<Map<string, string>> {
const avatarMap = new Map<string, string>()
if (handles.length === 0) return avatarMap
try {
const params = new URLSearchParams()
for (const handle of handles) {
params.append('actors', handle)
}
const response = await fetch(
`${BLUESKY_API}/xrpc/app.bsky.actor.getProfiles?${params.toString()}`,
)
if (!response.ok) {
console.warn(`[blog] Failed to fetch Bluesky profiles: ${response.status}`)
return avatarMap
}
const data = (await response.json()) as { profiles: Array<{ handle: string; avatar?: string }> }
for (const profile of data.profiles) {
if (profile.avatar) {
const hash = crypto.createHash('sha256').update(profile.avatar).digest('hex')
const dest = join(imagesDir, `${hash}.png`)
if (!existsSync(dest)) {
const res = await fetch(`${profile.avatar}@png`)
if (!res.ok || !res.body) {
console.warn(`[blog] Failed to fetch Bluesky avatar: ${profile.avatar}@png`)
continue
}
await writeFile(join(imagesDir, `${hash}.png`), res.body)
}
avatarMap.set(profile.handle, `/blog/avatar/${hash}.png`)
}
}
} catch (error) {
console.warn(`[blog] Failed to fetch Bluesky avatars:`, error)
}
return avatarMap
}
/**
* Resolves authors with their Bluesky avatars and profile URLs.
*/
function resolveAuthors(authors: Author[], avatarMap: Map<string, string>): ResolvedAuthor[] {
return authors.map(author => ({
...author,
avatar: author.blueskyHandle ? (avatarMap.get(author.blueskyHandle) ?? null) : null,
profileUrl: author.blueskyHandle ? `https://bsky.app/profile/${author.blueskyHandle}` : null,
}))
}
/**
* Scans the blog directory for .md files and extracts validated frontmatter.
* Returns all posts (including drafts) sorted by date descending.
* Resolves Bluesky avatars at build time.
*/
async function loadBlogPosts(
blogDir: string,
options: {
imagesDir: string
resolveAvatars: boolean
},
): Promise<BlogPostFrontmatter[]> {
const { imagesDir, resolveAvatars } = options
const files = await Array.fromAsync(glob(join(blogDir, '**/*.md').replace(/\\/g, '/')))
// First pass: extract raw frontmatter and collect all Bluesky handles
const rawPosts: Array<{ frontmatter: Record<string, unknown> }> = []
const allHandles = new Set<string>()
for (const file of files) {
const { data: frontmatter } = read(file)
// Normalise slug → path (same logic as standard-site-sync)
if (typeof frontmatter.slug === 'string' && !frontmatter.path) {
frontmatter.path = `/blog/${frontmatter.slug}`
}
// Normalise date to ISO string
if (frontmatter.date) {
const raw = frontmatter.date
frontmatter.date = new Date(raw instanceof Date ? raw : String(raw)).toISOString()
}
// Validate authors before resolving so we can extract handles
const authorsResult = safeParse(array(AuthorSchema), frontmatter.authors)
if (authorsResult.success) {
for (const author of authorsResult.output) {
if (author.blueskyHandle) {
allHandles.add(author.blueskyHandle)
}
}
}
rawPosts.push({ frontmatter })
}
// Batch-fetch all Bluesky avatars in a single request when avatar resolution is enabled.
const avatarMap = resolveAvatars
? await fetchBlueskyAvatars(imagesDir, [...allHandles])
: new Map<string, string>()
// Second pass: validate with raw schema, then enrich authors with avatars
const posts: BlogPostFrontmatter[] = []
for (const { frontmatter } of rawPosts) {
const result = safeParse(RawBlogPostSchema, frontmatter)
if (!result.success) continue
posts.push({
...result.output,
authors: resolveAuthors(result.output.authors, avatarMap),
})
}
// Sort newest first
posts.sort((a, b) => Date.parse(b.date) - Date.parse(a.date))
return posts
}
export default defineNuxtModule({
meta: {
name: 'blog',
},
async setup() {
const nuxt = useNuxt()
const resolver = createResolver(import.meta.url)
const blogDir = resolver.resolve('../app/pages/blog')
const blogImagesDir = resolver.resolve('../public/blog/avatar')
const publicDir = resolver.resolve('../public')
const resolveAvatars = !nuxt.options._prepare
nuxt.options.extensions.push('.md')
nuxt.options.vite.vue = defu(nuxt.options.vite.vue, {
include: [/\.vue($|\?)/, /\.(md|markdown)($|\?)/],
})
if (resolveAvatars && !existsSync(blogImagesDir)) {
await mkdir(blogImagesDir, { recursive: true })
}
addVitePlugin(() =>
Markdown({
include: [/\.(md|markdown)($|\?)/],
wrapperComponent: 'BlogPostWrapper',
wrapperClasses: 'text-fg-muted leading-relaxed',
async markdownSetup(md) {
md.use(
await shiki({
themes: {
dark: 'github-dark',
light: 'github-light',
},
}),
)
md.use(MarkdownItAnchor as any)
},
}),
)
// Load posts once with resolved Bluesky avatars (shared across template + route rules)
const allPosts = await loadBlogPosts(blogDir, {
imagesDir: blogImagesDir,
resolveAvatars,
})
// Expose frontmatter for the `/blog` listing page.
const showDrafts = nuxt.options.dev || !isProduction
addTemplate({
filename: 'blog/posts.ts',
write: true,
getContents: () => {
const posts = allPosts.filter(p => showDrafts || !p.draft)
return [
`import type { BlogPostFrontmatter } from '#shared/schemas/blog'`,
``,
`export const posts: BlogPostFrontmatter[] = ${JSON.stringify(posts, null, 2)}`,
].join('\n')
},
})
nuxt.options.alias['#blog/posts'] = join(nuxt.options.buildDir, 'blog/posts')
// Add X-Robots-Tag header for draft posts to prevent indexing
for (const post of allPosts) {
if (post.draft) {
nuxt.options.routeRules ||= {}
nuxt.options.routeRules[`/blog/${post.slug}`] = {
headers: { 'X-Robots-Tag': 'noindex, nofollow' },
}
}
}
// Generate content for RSS, Atom and JSON feeds
const feed = new Feed({
title: 'Blog - npmx',
description: 'a fast, modern browser for the npm registry',
id: 'https://npmx.dev/',
link: 'https://npmx.dev/',
language: 'en',
image: 'https://npmx.dev/logo.svg',
favicon: 'https://npmx.dev/favicon.ico',
feedLinks: {
rss: 'https://npmx.dev/rss.xml',
atom: 'https://npmx.dev/atom.xml',
json: 'https://npmx.dev/feed.json',
},
})
allPosts
.filter(post => !post.draft)
.forEach(post => {
feed.addItem({
title: post.title,
id: new URL(post.path, 'https://npmx.dev').toString(),
link: new URL(post.path, 'https://npmx.dev').toString(),
description: post.description,
author: post.authors.map(author => ({
name: author.name,
link: author.profileUrl ?? undefined,
// author.avatar is a relative URL - make it absolute to work in feed readers
avatar: author.avatar
? new URL(author.avatar, 'https://npmx.dev').toString()
: undefined,
})),
date: new Date(post.date),
image: post.image,
})
})
const rssPath = 'rss.xml'
const atomPath = 'atom.xml'
const jsonFeedPath = 'feed.json'
await Promise.all([
writeFile(join(publicDir, rssPath), feed.rss2()),
writeFile(join(publicDir, atomPath), feed.atom1()),
writeFile(join(publicDir, jsonFeedPath), feed.json1()),
])
},
})