-
Notifications
You must be signed in to change notification settings - Fork 0
/
predeploy.cjs
389 lines (341 loc) · 15 KB
/
predeploy.cjs
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
const fs = require('fs');
const slugify = require('slugify');
const sanitize = require('sanitize-filename');
const showdown = require('showdown')
const showdown_md_converter = new showdown.Converter();
const { markdownToTxt } = require('markdown-to-txt');
const YAML = require('yaml');
const _ = require('lodash');
const BLOG_CONFIG = YAML.parse( fs.readFileSync(`./blog/metadata.yml`, 'utf8') )
const tailwind_inject = {
h1: `mt-3 pt-4 scroll-m-20 text-2xl font-bold tracking-tight border-b pb-2 border-gray-400`,
h2: `mt-3 pt-4 scroll-m-20 border-b pb-2 text-2xl font-semibold tracking-tight transition-colors first:mt-0`,
h3: `mt-3 pt-4 scroll-m-20 text-xl font-semibold tracking-tight`,
h4: `mt-3 pt-4 scroll-m-20 text-xl font-medium tracking-tight`,
h5: `mt-3 pt-4 scroll-m-20 text-lg font-medium tracking-tight`,
h6: `mt-3 pt-4 scroll-m-20 font-medium tracking-tight`,
p: `text-lg p-2 px-4 pt-0 leading-7 [&:not(:first-child)]:mt-6`,
blockquote: `mt-6 border-l-2 pl-6 italic`,
table: `my-6 w-full overflow-y-auto`,
tr: `m-0 border-t p-0 even:bg-muted`,
th: `border px-4 py-2 text-left font-bold [&[align=center]]:text-center [&[align=right]]:text-right`,
td: `border px-4 py-2 text-left [&[align=center]]:text-center [&[align=right]]:text-right`,
ul: `my-6 ml-6 list-disc [&>li]:mt-2`,
code: `relative bg-gray-200 p-4 font-mono text-sm`,
lead: `text-xl text-muted-foreground`,
small: `text-sm font-medium leading-none`,
a: `text-blue-700 font-medium hover:text-blue-900 duration-200`,
}
function _list_folders(path) {
return fs.readdirSync(path).filter(function (file) {
return fs.statSync(path+'/'+file).isDirectory();
});
}
function _list_files(path){
return fs.readdirSync( path , {withFileTypes: true}).filter(item => !item.isDirectory()).map(item => item.name)
}
const _chunk = (array, size) =>
array.reduce((acc, _, i) => {
if (i % size === 0) acc.push(array.slice(i, i + size))
return acc
}, [])
// later -----------------------------------------------------------------------------
// generate og image from text data
function generate_social_img(){true}
// search engine
function build_search(){true}
// ------------------------------------------------------------------------------------------------------------------
function md_convert(md){
const postConvertYoutubeRegex = /<p><a href="https:\/\/youtu\.be\/([a-zA-Z0-9_-]+)">([^<]+)<\/a><\/p>|<p><a href="https:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)">([^<]+)<\/a><\/p>/g;
const postConvertImgRegex = /<p><img src="(.+?)" alt="(.+?)" \/><\/p>/g;
let html = showdown_md_converter.makeHtml(md)
.replace(postConvertYoutubeRegex, (match, videoId1, textInsideLink1, videoId2, textInsideLink2) => {
const videoId = videoId1 || videoId2;
const textInsideLink = textInsideLink1 || textInsideLink2;
return `<div class="font-normal py-4 text-center"><iframe src="https://www.youtube.com/embed/${videoId}" class="w-full xl:w-8/12 h-[25vh] xl:h-[40vh] py-2 mx-auto text-center" frameborder="0" allowfullscreen></iframe><div class="italic pt-2 my-2">${textInsideLink}</div></div>`
})
.replace(postConvertImgRegex, (match, imgUrl, altText) => {
return `<div class="font-normal py-4 text-center"><img src="${imgUrl}" /><div class="italic pt-2 my-2">${altText}</div></div>`;
})
for (let k of Object.keys(tailwind_inject) ) {
html = html.replaceAll(`<${k}` , `<${k} class="${tailwind_inject[k]}"`)
}
return html
}
function list_posts(){
return _list_folders(`./blog/posts`).map(folder => {
return {
folder,
files: _list_files(`./blog/posts/${folder}`),
}
}).filter(p=>p.files.includes('content.md')).map( p => {
const stats = fs.statSync(`./blog/posts/${p.folder}/content.md`)
let html
const md = fs.readFileSync(`./blog/posts/${p.folder}/content.md`, 'utf8').toString()
try {
html = md_convert(md)
} catch(post_error) {
console.dir({post_error})
return false
}
let post_config = {}
if ( p.files.includes(`metadata.yml`) ) {
try { post_config = YAML.parse( fs.readFileSync(`./blog/posts/${p.folder}/metadata.yml`, 'utf8') ) }
catch(post_config_error){ console.dir({post_config_error}) }
}
const plain_text = markdownToTxt(md).trim()
return {
folder: p.folder,
created: stats.birthtime,
updated: stats.mtime,
files: p.files.filter(f=> !(['content.md','metadata.yml'].includes(f)) ),
html,
plain_text,
title: md.trim().split(`\n`)[0].replace('#','').trim(),
tags: [],
categories: [],
public: true,
authors : [BLOG_CONFIG.owner],
description: plain_text.split('\n').length > 1
? plain_text.split('\n').slice(1,).join(`\n`).trim().split('.').slice(0,5).join('.') + ' ...' // 5 sentences preview
: ``,
...post_config,
}
}).filter(p=>p && p.public).map( p => {
const slug = sanitize( slugify(p.title).toLowerCase() ).replace(/-+/g, '-')
// let new_html = p.html.replaceAll(`<img src="`,`<img class="text-center mx-auto" src="${slug}/`)
let new_html = p.html
for (let f of p.files){
new_html = new_html.replaceAll(`<img src="${f}` , `<img src="${slug}/${f}`)
}
return {
...p,
slug,
html: new_html.replaceAll(`<img src="`,`<img class="text-center mx-auto" src="`),
}
}).sort((a, b) => new Date(a.created).getTime() - new Date(b.created).getTime())
.map( (p,index) => {
return {
...p,
index,
is_in_page: Math.floor(index/BLOG_CONFIG.postsPerPage)+1,
}
})
}
const root_template = fs.readFileSync(`./predeploy/root_template.svelte`, 'utf8').toString()
const post_template = fs.readFileSync(`./predeploy/post_template.svelte`, 'utf8').toString()
const page_template = fs.readFileSync(`./predeploy/page_template.svelte`, 'utf8').toString()
const tag_template = fs.readFileSync(`./predeploy/tag_template.svelte`, 'utf8').toString()
function make_post(p){
// generate svelte component
const root_og_image_check = _list_files(`./blog`).map(e=> { return {file:e,og_img:e.startsWith('og.')} }).filter(e=>e.og_img)
const post_og_image_check = _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,og_img:e.startsWith('og.')} }).filter(e=>e.og_img)
const og_image = BLOG_CONFIG.domain && BLOG_CONFIG.domain.length && ( root_og_image_check.length || post_og_image_check.length )
? post_og_image_check.length
? `https://${BLOG_CONFIG.domain}/${p.slug}/${post_og_image_check[0].file}`
: `https://${BLOG_CONFIG.domain}/${root_og_image_check[0].file}`
: ''
return post_template.replaceAll(`{{POST_TITLE}}`,p.title)
.replaceAll(
`{{POST_TITLE_OG}}`,
_.escape(p.title)
)
.replaceAll(
`{{POST_DESCRIPTION_OG}}`,
_.escape(p.description)
)
.replaceAll(
`{{POST_IMAGE_OG}}`,
og_image
)
.replace(`{{POST_TIME}}`,(p.created).toString().split(' ').slice(1,4).join(' ') )
.replace(`{{POST_AUTHORS}}`,p.authors.join(' , '))
.replace(`{{POST_IS_IN_PAGE}}`,p.is_in_page)
.replace(`{{POST_HTML}}`,p.html)
.replace(
`{{POST_TAGS}}`,
JSON.stringify(
p.tags.map( t => sanitize((t).toLowerCase()))
)
)
}
function make_root(page,n_pages){
// generate svelte component
const blog_description = BLOG_CONFIG.description ? BLOG_CONFIG.description : ''
const og_image_check = _list_files(`./blog`).map(e=> { return {file:e,og_img:e.startsWith('og.')} }).filter(e=>e.og_img)
const og_image = BLOG_CONFIG.domain && BLOG_CONFIG.domain.length && og_image_check.length
? `https://${BLOG_CONFIG.domain}/${og_image_check[0].file}`
: ''
return root_template.replaceAll(`{{BLOG_TITLE}}`,BLOG_CONFIG.title)
.replaceAll(
`{{BLOG_TITLE_OG}}`,
_.escape(BLOG_CONFIG.title)
)
.replaceAll(
`{{BLOG_DESCRIPTION_OG}}`,
_.escape(blog_description)
)
.replaceAll(`{{BLOG_DESCRIPTION}}`,blog_description)
.replaceAll(
`{{BLOG_IMAGE_OG}}`,
og_image
)
.replace(
`{{BLOG_POSTS}}`,
JSON.stringify(
page.map( p => {
return {
title:p.title,
description:p.description,
slug:p.slug,
time:(p.created).toString().split(' ').slice(1,4).join(' '),
authors:p.authors,
tags: p.tags.map( t => sanitize((t).toLowerCase())),
thumbnail:
_list_files(`./blog/posts/${p.folder}`).map(e=>{return {file:e,thumb_img:e.startsWith('thumbnail.')} }).filter(e=>e.thumb_img).length
? `/${p.slug}/` + _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,thumb_img:e.startsWith('thumbnail.')} }).filter(e=>e.thumb_img)[0].file
: _list_files(`./blog/posts/${p.folder}`).map(e=>{return {file:e,thumb_img:e.startsWith('og.')} }).filter(e=>e.thumb_img).length
? `/${p.slug}/` + _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,thumb_img:e.startsWith('og.')} }).filter(e=>e.thumb_img)[0].file
: false,
}
})
)
)
.replaceAll(`{{LAST_PAGE}}`, n_pages)
}
function make_page(page,page_idx,n_pages){
const og_description = BLOG_CONFIG.description ? BLOG_CONFIG.description : ''
const og_image_check = _list_files(`./blog`).map(e=> { return {file:e,og_img:e.startsWith('og.')} }).filter(e=>e.og_img)
const og_image = BLOG_CONFIG.domain && BLOG_CONFIG.domain.length && og_image_check.length
? `https://${BLOG_CONFIG.domain}/${og_image_check[0].file}`
: ''
return page_template.replaceAll(`{{BLOG_TITLE}}`, `${BLOG_CONFIG.title} | Page ${page_idx+1}/${n_pages}` )
.replaceAll(
`{{BLOG_TITLE_OG}}`,
_.escape(
`${BLOG_CONFIG.title} | Page ${page_idx+1}/${n_pages}`
)
)
.replaceAll(
`{{BLOG_DESCRIPTION_OG}}`,
_.escape(og_description)
)
.replaceAll(
`{{BLOG_IMAGE_OG}}`,
og_image
)
.replace(
`{{BLOG_POSTS}}`,
JSON.stringify(
page.map( p => {
return {
title:p.title,
description:p.description,
slug:p.slug,
time:(p.created).toString().split(' ').slice(1,4).join(' '),
authors:p.authors,
tags: p.tags.map( t => sanitize((t).toLowerCase())),
thumbnail:
_list_files(`./blog/posts/${p.folder}`).map(e=>{return {file:e,thumb_img:e.startsWith('thumbnail.')} }).filter(e=>e.thumb_img).length
? `/${p.slug}/` + _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,thumb_img:e.startsWith('thumbnail.')} }).filter(e=>e.thumb_img)[0].file
: _list_files(`./blog/posts/${p.folder}`).map(e=>{return {file:e,thumb_img:e.startsWith('og.')} }).filter(e=>e.thumb_img).length
? `/${p.slug}/` + _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,thumb_img:e.startsWith('og.')} }).filter(e=>e.thumb_img)[0].file
: false,
}
})
)
)
.replaceAll(`{{LAST_PAGE}}`, n_pages)
.replaceAll(`{{CURRENT_PAGE}}`, page_idx+1)
}
function make_tags(tag,posts){
const og_description = BLOG_CONFIG.description ? BLOG_CONFIG.description : ''
const og_image_check = _list_files(`./blog`).map(e=> { return {file:e,og_img:e.startsWith('og.')} }).filter(e=>e.og_img)
const og_image = BLOG_CONFIG.domain && BLOG_CONFIG.domain.length && og_image_check.length
? `https://${BLOG_CONFIG.domain}/${og_image_check[0].file}`
: ''
return tag_template.replaceAll(`{{BLOG_TITLE}}`, `${BLOG_CONFIG.title} | Tagged in : ${tag}` )
.replaceAll(`{{TAG_NAME}}`, tag)
.replace(`{{TAG_POSTS_COUNT}}`, posts.length)
.replaceAll(
`{{BLOG_TITLE_OG}}`,
_.escape( `${BLOG_CONFIG.title} | Tagged in : ${tag} ` )
)
.replaceAll(
`{{BLOG_DESCRIPTION_OG}}`,
_.escape(og_description)
)
.replaceAll(
`{{BLOG_IMAGE_OG}}`,
og_image
)
.replace(
`{{BLOG_POSTS}}`,
JSON.stringify(
posts.map( p => {
return {
title:p.title,
description:p.description,
slug:p.slug,
time:(p.created).toString().split(' ').slice(1,4).join(' '),
authors:p.authors,
tags: p.tags.map( t => sanitize((t).toLowerCase())),
thumbnail:
_list_files(`./blog/posts/${p.folder}`).map(e=>{return {file:e,thumb_img:e.startsWith('thumbnail.')} }).filter(e=>e.thumb_img).length
? `/${p.slug}/` + _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,thumb_img:e.startsWith('thumbnail.')} }).filter(e=>e.thumb_img)[0].file
: _list_files(`./blog/posts/${p.folder}`).map(e=>{return {file:e,thumb_img:e.startsWith('og.')} }).filter(e=>e.thumb_img).length
? `/${p.slug}/` + _list_files(`./blog/posts/${p.folder}`).map(e=> { return {file:e,thumb_img:e.startsWith('og.')} }).filter(e=>e.thumb_img)[0].file
: false,
}
})
)
)
}
function generate_components(){
const posts = list_posts()
const generated_post_components = posts.map( p => make_post(p) )
const pages = _chunk(posts,BLOG_CONFIG.postsPerPage)
const n_pages = pages.length
const generated_root_component = make_root(pages[0],n_pages)
const generated_page_components = pages.map( (page,page_idx) => { return make_page(page,page_idx,n_pages) } )
let tags = {
// 'tag_name' : [posts]
}
posts.map(p=>{
for (let t of p.tags){
if (Object.keys(tags).includes(t)) tags[t].push(p)
else tags[t] = [p]
}
})
const generated_tag_components = Object.keys(tags).map( (_tag) => { return { tag:_tag, component:make_tags(_tag,tags[_tag]) } } )
try{ fs.rmSync( `./src/routes`, { recursive: true, force: true }) }catch(e){false}
fs.mkdirSync( `./src/routes`, { recursive: true, force: true })
posts.map( (p,idx) => {
// write static assets
fs.mkdirSync( `./static/${p.slug}`, { recursive: true, force: true })
p.files.map( f => {
fs.copyFileSync( `./blog/posts/${p.folder}/${f}`, `./static/${p.slug}/${f}`)
})
// write svelte components
fs.mkdirSync( `./src/routes/${p.slug}`, { recursive: true, force: true })
fs.writeFileSync( `./src/routes/${p.slug}/+layout.svelte` , generated_post_components[idx])
fs.writeFileSync( `./src/routes/${p.slug}/+page.svelte` , '')
})
fs.writeFileSync( `./src/routes/+layout.svelte` , generated_root_component)
fs.writeFileSync( `./src/routes/+page.svelte` , '')
generated_page_components.map( (page_component,idx) => {
fs.mkdirSync( `./src/routes/page/${idx+1}`, { recursive: true, force: true })
fs.writeFileSync( `./src/routes/page/${idx+1}/+layout.svelte` , page_component)
fs.writeFileSync( `./src/routes/page/${idx+1}/+page.svelte` , '')
})
generated_tag_components.map( (_t) => {
const tag_target = sanitize((_t.tag).toLowerCase())
fs.mkdirSync( `./src/routes/tag/${tag_target}`, { recursive: true, force: true })
fs.writeFileSync( `./src/routes/tag/${tag_target}/+layout.svelte` , _t.component)
fs.writeFileSync( `./src/routes/tag/${tag_target}/+page.svelte` , '')
})
_list_files(`./blog`).filter(f=>f!=`metadata.yml`).map( f => {
fs.copyFileSync( `./blog/${f}`, `./static/${f}`)
})
}
generate_components()