-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentlayer.config.ts
More file actions
422 lines (386 loc) · 11.9 KB
/
contentlayer.config.ts
File metadata and controls
422 lines (386 loc) · 11.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
import { defineDocumentType, makeSource } from 'contentlayer2/source-files'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import rehypeExternalLinks from 'rehype-external-links'
import rehypeKatex from 'rehype-katex'
import rehypePrettyCode from 'rehype-pretty-code'
import rehypeSlug from 'rehype-slug'
import remarkBreaks from 'remark-breaks'
import remarkCallout from 'remark-callout'
import remarkGfm from 'remark-gfm'
import remarkLint from 'remark-lint'
import remarkMath from 'remark-math'
import remarkToc from 'remark-toc'
import sharp from 'sharp'
import { visit } from 'unist-util-visit'
import { createHash } from 'crypto'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { join } from 'path'
// 캐시 디렉토리 설정
const CACHE_DIR = '.cache/images'
if (!existsSync(CACHE_DIR)) {
mkdirSync(CACHE_DIR, { recursive: true })
}
// 외부 이미지를 가져와서 블러 처리
const toBlurDataURL = async (url: string) => {
const params = new URL(url).searchParams
const w = Number(params.get('w')) || 16
const h = Number(params.get('h')) || 16
// URL 해시 생성 (캐시 키)
const hash = createHash('md5')
.update(url + '-blur')
.digest('hex')
const cachePath = join(CACHE_DIR, `${hash}.webp`)
// 캐시 확인
if (existsSync(cachePath)) {
const buffer = readFileSync(cachePath)
return `data:image/webp;base64,${buffer.toString('base64')}`
}
// 이미지 요청
const res = await fetch(url)
// 응답 확인
if (!res.ok) return ''
const imageData = await res.arrayBuffer()
const image = sharp(imageData)
const imgAspectRatio = w / h
// Base64 문자열로 변환
const buffer = await image
.resize(8, Math.round(8 / imgAspectRatio))
.webp({
quality: 75,
})
.toBuffer()
// 캐시 저장
writeFileSync(cachePath, buffer)
return `data:image/webp;base64,${buffer.toString('base64')}`
}
const toDataURI = async (url: string) => {
// URL 해시 생성 (캐시 키)
const hash = createHash('md5').update(url).digest('hex')
const cachePath = join(CACHE_DIR, `${hash}.webp`)
// 캐시 확인
if (existsSync(cachePath)) {
const buffer = readFileSync(cachePath)
return `data:image/webp;base64,${buffer.toString('base64')}`
}
// 이미지 요청
const res = await fetch(url)
// 응답 확인
if (!res.ok) return url
// 이미지 데이터 가져오기
const imageData = await res.arrayBuffer()
const image = sharp(imageData)
// Base64 문자열로 변환
const buffer = await image
.webp({
quality: 75,
})
.toBuffer()
// 캐시 저장
writeFileSync(cachePath, buffer)
return `data:image/webp;base64,${buffer.toString('base64')}`
}
const adjustUl = (node: any, index: number | undefined, parent: any) => {
if (index === undefined) return
// 현재 노드가 텍스트만을 갖는지 확인
const isTextOnly =
node.children.length === 1 && node.children[0].type === 'text'
// 다음 노드가 ul 태그인지 확인
const nextNode = parent.children[index + 1]
const isNextNodeUL = nextNode && nextNode.type === 'list'
const className = 'prose-list'
if (isTextOnly && isNextNodeUL) {
// p 태그에 클래스 추가
if (!node.data) node.data = {}
if (!node.data.hProperties) node.data.hProperties = {}
node.data.hProperties.className = (
node.data.hProperties.className || []
).concat(className)
}
}
/**
* @type {import('unified').Plugin<[], Root>}
* @param {string} options.root
*/
const remarkSourceRedirect = () => async (tree: any) => {
const images: any[] = []
visit(tree, 'paragraph', (node, index, parent) => {
const imgs = node.children.filter((child: any) => child.type === 'image')
for (const img of imgs) {
if (img.url.includes('://')) images.push(node)
else {
img.url = `/blog/${img.url.replace(/\.(PNG|JPG|JPEG|png|jpg|jpeg)$/, '.webp')}`
}
}
adjustUl(node, index, parent)
})
visit(tree, 'link', (node: any) => {
const url: string = node.url
if (url.startsWith('books/') || url.startsWith('posts/')) {
let replacedUrl = url.replace(/\.(md)$/, '')
let hostname =
process.env.NODE_ENV === 'production'
? 'https://get6.github.io'
: 'http://localhost:3000'
node.url = `${hostname}/${replacedUrl}`
}
})
// base64는 외부 이미지를 blur 처리하는 용도로 가져와도 좋을 것 같다. 0.1 퀄리티로 아주 작은 이미지를 가져와서 블러 처리
const promises: Promise<any>[] = []
for (const node of images) {
const imgs = node.children.filter((child: any) => child.type === 'image')
for (const img of imgs) {
if (img.url.includes('images.unsplash.com'))
promises.push(
new Promise(async (resolve) => {
img.url = await toDataURI(img.url)
resolve(img.url)
}),
)
}
}
await Promise.all(promises)
}
const isNameImg = (name: string) => name === 'img'
const hasImage = (props: any) => {
return (
props.children instanceof Array &&
(props.children as any[]).some((child) => isNameImg(child.tagName))
)
}
const rehypeImageSize = () => (tree: any) => {
// 이미지를 포함한 p 태그에 클래스 추가
visit(tree, 'element', (node: any) => {
if (node.tagName === 'p' && hasImage(node)) {
const images = node.children.filter((child: any) =>
isNameImg(child.tagName),
)
if (1 < images.length) {
if (node.properties.className)
node.properties.className += ' flex flex-wrap justify-center gap-4'
else node.properties.className = 'flex flex-wrap justify-center gap-4'
}
} else if (isNameImg(node.tagName)) {
const src = node.properties.src
const alt = node.properties.alt
if (src && alt) {
if (alt.toString().includes('|')) {
const width = alt.split('|').map((s: string) => s.trim())[1]
node.properties.width = width
}
} else if (src && !alt) {
node.properties.alt = 'image'
}
}
})
}
// 목차 추출
const getToC = (html: string): ToC[] | null => {
const headers = html.match(/<h([1-6]).*?id=["'](.*?)["'].*?>(.*?)<\/h[1-6]>/g)
if (headers) {
const headerList: ToC[] = headers.map((header) => {
const matches = header.match(
/<h([1-6]).*?id=["'](.*?)["'].*?>(.*?)<\/h[1-6]>/,
)
if (matches) {
const title = matches[3]
return {
level: parseInt(matches[1]),
id: matches[2],
title: title.slice(0, title.indexOf('<')),
}
} else return { level: 0, id: '', title: '' }
})
const filteredList = headerList.filter((header) => header.level !== 0)
if (1 < filteredList.length) return filteredList
}
return null
}
const getSummary = (html: string) => {
// 정규 표현식을 사용하여 HTML 태그 제거
const regex = /<[^>]+>/g
const text = html.replace(regex, '').replace(/#/g, '')
// 공백 제거
return text.replace(/\s+/g, ' ').trim()
}
/** Extract locale from flattenedPath (e.g. "posts/en/slug" → "en", "posts/slug" → "ko") */
const LOCALE_DIRS = ['en', 'ja']
const extractLocale = (flattenedPath: string, prefix: string): string => {
const rest = flattenedPath.replace(new RegExp(`^${prefix}/`), '')
const firstSegment = rest.split('/')[0]
return LOCALE_DIRS.includes(firstSegment) ? firstSegment : 'ko'
}
/** Extract slug, stripping locale dir if present */
const extractSlug = (flattenedPath: string, prefix: string): string => {
const rest = flattenedPath.replace(new RegExp(`^${prefix}/`), '')
const firstSegment = rest.split('/')[0]
if (LOCALE_DIRS.includes(firstSegment)) {
return rest.replace(new RegExp(`^${firstSegment}/`), '')
}
return rest
}
const Post = defineDocumentType(() => ({
name: 'Post',
filePathPattern: `posts/**/*.md`,
fields: {
title: { type: 'string', required: true },
date: { type: 'date', required: true },
tags: {
type: 'list',
required: true,
of: { type: 'string' },
},
series: {
type: 'list',
of: { type: 'string' },
},
series_title: { type: 'string' },
note: { type: 'string' },
},
computedFields: {
locale: {
type: 'string',
resolve: (post) => extractLocale(post._raw.flattenedPath, 'posts'),
},
url: {
type: 'string',
resolve: (post) => {
const locale = extractLocale(post._raw.flattenedPath, 'posts')
const slug = extractSlug(post._raw.flattenedPath, 'posts')
return locale === 'ko' ? `/posts/${slug}` : `/${locale}/posts/${slug}`
},
},
slug: {
type: 'string',
resolve: (post) => extractSlug(post._raw.flattenedPath, 'posts'),
},
cover_image: {
type: 'string',
resolve: async (post) => {
const regex = /!\[[^\]]*\]\((.*?)\)/g
const match = regex.exec(post.body.raw)
if (match) {
return await toDataURI(match[1])
}
return '/images/alt_image.webp'
},
},
summary: {
type: 'string',
resolve: (post) => getSummary(post.body.html),
},
toc: {
type: 'list',
resolve: (post) => getToC(post.body.html),
},
},
}))
const Book = defineDocumentType(() => ({
name: 'Book',
filePathPattern: `books/**/*.md`,
fields: {
created: { type: 'date', required: true },
// tag: {
// type: 'list',
// required: true,
// of: { type: 'string' },
// },
tag: { type: 'string', required: true },
title: { type: 'string', required: true },
subtitle: { type: 'string' },
author: { type: 'string', required: true },
category: { type: 'string', required: true },
total_page: { type: 'number', required: true },
publish_date: { type: 'date', required: true },
cover_url: { type: 'string', required: true },
status: { type: 'string', required: true },
start_read_date: { type: 'date', required: true },
finish_read_date: { type: 'date', required: true },
my_rate: { type: 'number', required: true },
book_note: { type: 'string' },
book_url: { type: 'string', required: true },
},
computedFields: {
locale: {
type: 'string',
resolve: (book) => extractLocale(book._raw.flattenedPath, 'books'),
},
url: {
type: 'string',
resolve: (book) => {
const locale = extractLocale(book._raw.flattenedPath, 'books')
const slug = extractSlug(book._raw.flattenedPath, 'books')
return locale === 'ko' ? `/books/${slug}` : `/${locale}/books/${slug}`
},
},
slug: {
type: 'string',
resolve: (book) => extractSlug(book._raw.flattenedPath, 'books'),
},
summary: {
type: 'string',
resolve: (book) => getSummary(book.body.html),
},
toc: {
type: 'list',
resolve: (book) => getToC(book.body.html),
},
cover_image: {
type: 'string',
resolve: async (book) => await toDataURI(book.cover_url),
},
},
}))
const remarkPlugins = [
remarkGfm,
remarkBreaks,
remarkCallout,
remarkMath,
remarkToc,
remarkSourceRedirect,
remarkLint,
]
const rehypePlugins = [
rehypePrettyCode,
[rehypeKatex, { strict: 'ignore' }],
rehypeImageSize,
rehypeSlug,
[
rehypeAutolinkHeadings,
{
behavior: 'append',
properties: {
className: ['no-underline'],
},
content: {
type: 'element',
tagName: 'span',
properties: {
className: 'no-underline',
},
children: [
{
type: 'text',
value: '#',
},
],
},
},
],
[
rehypeExternalLinks,
{
rel: ['noopener', 'noreferrer'],
target: '_blank',
},
],
]
export default makeSource({
contentDirPath: 'blog',
contentDirExclude: ['.obsidian', 'assets', 'templates'],
documentTypes: [Post, Book],
markdown: {
remarkPlugins: remarkPlugins as any,
rehypePlugins: rehypePlugins as any,
},
date: { timezone: 'Asia/Seoul' },
})