-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreprocess.ts
More file actions
555 lines (428 loc) Β· 17.4 KB
/
preprocess.ts
File metadata and controls
555 lines (428 loc) Β· 17.4 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import * as fs from 'node:fs/promises'
import * as path from 'node:path'
import { existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { randomBytes } from 'node:crypto'
import { parseArgs } from 'node:util'
// ββ constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const REPO = path.resolve(__dirname)
const REPLACE_RULES_PATH = path.join(REPO, 'replace_rules.json')
// ββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class CaseInsensitiveMap<T> extends Map<string, T> {
get(key: string): T | undefined {
return super.get(key.toLowerCase())
}
set(key: string, value: T): this {
return super.set(key.toLowerCase(), value)
}
has(key: string): boolean {
return super.has(key.toLowerCase())
}
delete(key: string): boolean {
return super.delete(key.toLowerCase())
}
}
function nfc(text: string): string {
return text.normalize('NFC')
}
function randomHex(): string {
return randomBytes(3).toString('hex').toUpperCase()
}
// ββ load replace rules βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const REPLACE_RULES: Record<string, string> = JSON.parse(await fs.readFile(REPLACE_RULES_PATH, 'utf-8'))
const REPLACE_RE = new RegExp(
Object.keys(REPLACE_RULES)
.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|'),
'g'
)
const LANG_FIX_RE = /---\s*\n(.*?)\n---/s
// ββ global regexes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const WIKILINK_RE = /\[\[([^\]]+?)]]/g // raw [[β¦]] tokens
const CODE_BLOCK_RE = /```.*?```/gs // fenced code
const IMG_RE = /!\[([^\]]*?)\]\(([^)]+?)\)$/gm // images
const SLUG_RE = /^slug:\s+['\"]?([^\s'\"#]+)['\"]?/m
// ββ markdown sanitisation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function sanitiseMd(root: string): Promise<void> {
const mdFiles = await findFiles(root, ['.md', '.mdx'])
console.log(`π Sanitizing ${mdFiles.length} markdown files...`)
await Promise.all(mdFiles.map(sanitiseOne))
console.log(`β¨ Completed markdown sanitization`)
}
async function sanitiseOne(filePath: string): Promise<void> {
let text = nfc(await fs.readFile(filePath, 'utf-8'))
if (text.includes('{{hex}}') && !filePath.includes('template')) {
text = text.replace('{{hex}}', '/' + randomHex())
}
text = text.replace(REPLACE_RE, (match) => REPLACE_RULES[match])
const fm = text.match(LANG_FIX_RE)
if (fm && fm[1].includes("lang: 'en'")) {
if (!text.includes("div lang='ko") && !text.includes('div lang="ko')) {
const fileName = path.basename(filePath)
const koName = [...fileName].some((ch) => ch >= '\uAC00' && ch <= '\uD7A3')
const koChars = [...text].filter((ch) => ch >= '\uAC00' && ch <= '\uD7A3').length
const enChars = [...text].filter((ch) => (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')).length
if (koName || koChars > enChars) {
text = text.replace("lang: 'en'", "lang: 'ko'")
}
}
}
await fs.writeFile(filePath, text, 'utf-8')
}
// ββ file utilities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function findFiles(dir: string, extensions: string[]): Promise<string[]> {
const files: string[] = []
async function walk(currentDir: string) {
const entries = await fs.readdir(currentDir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name)
if (entry.isDirectory()) {
await walk(fullPath)
} else if (extensions.some((ext) => entry.name.endsWith(ext))) {
files.push(fullPath)
}
}
}
await walk(dir)
return files
}
async function copyRecursive(src: string, dest: string): Promise<void> {
const stat = await fs.stat(src)
if (stat.isDirectory()) {
await fs.mkdir(dest, { recursive: true })
const entries = await fs.readdir(src)
for (const entry of entries) {
await copyRecursive(path.join(src, entry), path.join(dest, entry))
}
} else {
await fs.copyFile(src, dest)
}
}
async function rmrf(dir: string): Promise<void> {
if (existsSync(dir)) {
await fs.rm(dir, { recursive: true, force: true })
}
}
// ββ blog generation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function processBlog(src: string, en: string, ko: string, cfg: string): Promise<void> {
console.log(`π Processing blog content...`)
await rmrf(en)
await rmrf(ko)
await fs.mkdir(en, { recursive: true })
await fs.mkdir(ko, { recursive: true })
const entries = await fs.readdir(src, { withFileTypes: true })
const fileCount = await countFiles(src)
console.log(`π Copying ${fileCount} blog files to English and Korean destinations`)
for (const entry of entries) {
const srcPath = path.join(src, entry.name)
if (entry.isFile()) {
await fs.copyFile(srcPath, path.join(en, entry.name))
await fs.copyFile(srcPath, path.join(ko, entry.name))
} else {
await copyRecursive(srcPath, path.join(en, entry.name))
await copyRecursive(srcPath, path.join(ko, entry.name))
}
}
await fs.copyFile(path.join(cfg, 'english.yml'), path.join(en, 'authors.yml'))
await fs.copyFile(path.join(cfg, 'korean.yml'), path.join(ko, 'authors.yml'))
await walkRename(en, 'en', 'ko')
await walkRename(ko, 'ko', 'en')
console.log(`π Completed blog processing`)
}
async function walkRename(base: string, toIndex: string, toDelete: string): Promise<void> {
const files = await findFiles(base, ['.md', '.mdx'])
for (const file of files) {
const dir = path.dirname(file)
const basename = path.basename(file, path.extname(file))
const ext = path.extname(file)
if (basename.startsWith(toIndex)) {
await fs.rename(file, path.join(dir, 'index' + ext))
} else if (basename.startsWith(toDelete)) {
await fs.unlink(file)
}
}
}
async function countFiles(dir: string): Promise<number> {
let count = 0
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
count += await countFiles(fullPath)
} else {
count++
}
}
return count
}
// ββ docs build βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function processDocs(src: string, dst: string): Promise<void> {
console.log(`π Processing documentation...`)
await rmrf(dst)
await copyRecursive(src, dst)
const mdFiles = await findFiles(dst, ['.md'])
console.log(`π Resolving links in ${mdFiles.length} markdown files`)
const linkMap = new CaseInsensitiveMap<string>()
for (const file of mdFiles) {
linkMap.set(nfc(path.basename(file, '.md')), file)
}
// Copy yml files
const ymlFiles = await findFiles(src, ['.yml'])
for (const yml of ymlFiles) {
const relative = path.relative(src, yml)
const target = path.join(dst, relative)
await fs.mkdir(path.dirname(target), { recursive: true })
await fs.copyFile(yml, target)
}
// Copy assets
const assetsDir = path.join(src, 'assets')
if (existsSync(assetsDir)) {
await copyRecursive(assetsDir, path.join(dst, 'assets'))
}
// Process images first
console.log(`πΈ Processing images in ${mdFiles.length} files...`)
await Promise.all(mdFiles.map((file) => processImages(file)))
// Then resolve links
console.log(`π Resolving wikilinks...`)
await Promise.all(mdFiles.map((file) => resolveFile(file, linkMap)))
console.log(`π Completed documentation processing`)
}
async function processImages(filePath: string): Promise<void> {
let txt = await fs.readFile(filePath, 'utf-8')
const before = txt
// Check if file contains wikilink images
const wikiImageMatches = txt.match(/!\[\[([^\]]+?)\]\]/g)
txt = txt.replace(/!\[\[([^\]]+?)\]\]/g, (match, p1) => {
return ``
})
await fs.writeFile(filePath, txt, 'utf-8')
}
async function resolveFile(filePath: string, linkMap: CaseInsensitiveMap<string>): Promise<void> {
const txt = await fs.readFile(filePath, 'utf-8')
const parts: string[] = []
let lastIndex = 0
// Handle code blocks
const matches = [...txt.matchAll(CODE_BLOCK_RE)]
for (const match of matches) {
const start = match.index!
const end = start + match[0].length
// Process text outside code block
const outside = txt.slice(lastIndex, start)
const processedOutside = outside.replace(WIKILINK_RE, (match, p1) => resolveWikilink(match, p1, filePath, linkMap))
parts.push(processedOutside)
parts.push(match[0])
lastIndex = end
}
// Process remainder
const remainder = txt.slice(lastIndex)
const processedRemainder = remainder.replace(WIKILINK_RE, (match, p1) =>
resolveWikilink(match, p1, filePath, linkMap)
)
parts.push(processedRemainder)
const out = parts.join('')
if (out !== txt) {
await fs.writeFile(filePath, out, 'utf-8')
}
}
function resolveWikilink(match: string, raw: string, currentFile: string, linkMap: CaseInsensitiveMap<string>): string {
// Skip tokens that are clearly not wiki titles
if (!raw || raw[0] === ' ' || raw[raw.length - 1] === ' ' || raw.trimStart().startsWith('-')) {
return match
}
const [target, display] = raw.includes('|') ? raw.split('|', 2) : [raw, raw]
const mdFile = linkMap.get(nfc(target))
if (!mdFile) {
return match // unresolved β keep original
}
let rel = path.relative(path.dirname(currentFile), mdFile)
rel = rel
.split(path.sep)
.map((seg) => encodeURIComponent(seg))
.join('/')
return `[${display}](./${rel})`
}
// ββ backlink map βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
interface BacklinkMap {
[key: string]: {
[source: string]: string
}
}
interface UidMap {
[key: string]: string
}
async function buildBacklinks(root: string, outDir: string): Promise<void> {
console.log(`π Building backlink map...`)
const backlinkMap: BacklinkMap = {}
const uidMap: UidMap = {}
let fileCount = 0
let linkCount = 0
const mdFiles = await findFiles(root, ['.md'])
for (const file of mdFiles) {
fileCount++
const fname = path.basename(file, '.md')
if (!backlinkMap[fname]) {
backlinkMap[fname] = {}
}
const txt = await fs.readFile(file, 'utf-8')
// Extract slug
const uidMatch = txt.match(SLUG_RE)
if (uidMatch) {
uidMap[fname] = uidMatch[1]
}
const relative = path.relative(root, file)
let link = "/docs/" + relative.slice(0, -path.extname(relative).length)
uidMap[fname] = link.replace(/[0-9]\./g, "").replaceAll(" ", "%20")
// Find all wikilinks
const wikilinks = [...txt.matchAll(WIKILINK_RE)]
for (const match of wikilinks) {
linkCount++
let source = match[1].split('|')[0]
source = source.split('/').pop() ?? source;
if (!backlinkMap[source]) {
backlinkMap[source] = {}
}
backlinkMap[source][fname] = getContext(txt, match[1])
}
}
await fs.mkdir(outDir, { recursive: true })
// Sort the backlink map keys and their nested objects
const sortedBacklinkMap: BacklinkMap = {}
for (const key of Object.keys(backlinkMap).sort()) {
sortedBacklinkMap[key] = {}
for (const nestedKey of Object.keys(backlinkMap[key]).sort()) {
sortedBacklinkMap[key][nestedKey] = backlinkMap[key][nestedKey]
}
}
// Sort the uid map
const sortedUidMap: UidMap = {}
for (const key of Object.keys(uidMap).sort()) {
sortedUidMap[key] = uidMap[key]
}
await fs.writeFile(path.join(outDir, 'backlinks.json'), JSON.stringify(sortedBacklinkMap, null, 2))
await fs.writeFile(path.join(outDir, 'filenames.json'), JSON.stringify(sortedUidMap, null, 2))
console.log(`π§© Created backlink map with ${fileCount} files and ${linkCount} links`)
}
function getContext(txt: string, needle: string, keep: number = 6): string {
const tag = `[[${needle}]]`
const lines = txt.split('\n')
for (const line of lines) {
if (!line.includes(tag)) continue
const [preRaw, postRaw] = line.split(tag)
const preParts = preRaw.split(/\s+/)
const postParts = postRaw.split(/\s+/)
const pre = preParts.slice(-keep).join(' ')
const post = postParts.slice(0, keep).join(' ')
return (preRaw !== pre ? '... ' + pre : pre) + tag + (postRaw !== post ? post + ' ...' : post)
}
return ''
}
// ββ image alt fix ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function fixImgAlt(root: string): Promise<void> {
let count = 0
const files = await findFiles(root, ['.md', '.mdx'])
for (const file of files) {
if (path.basename(file) === 'Welcome.md') continue
const txt = await fs.readFile(file, 'utf-8')
const out = txt.replace(IMG_RE, (match, alt, src) => {
const ext = path.extname(src).toLowerCase()
count++
if (alt.endsWith(ext) || alt.toUpperCase().startsWith('ALT:')) {
const clean = alt.replace('ALT:', '').trim()
return `\n<figure>\n\n\n\n</figure>\n`
}
return `\n<figure>\n\n\n\n<figcaption>${alt}</figcaption>\n</figure>\n`
})
if (out !== txt) {
await fs.writeFile(file, out, 'utf-8')
}
}
}
// ββ asset cleanup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function cleanupAssets(assetsDir: string, researchRoot: string): Promise<void> {
console.log(`π§Ή Checking for unused assets...`)
if (!existsSync(assetsDir)) {
return
}
const assets = await fs.readdir(assetsDir)
const assetFiles: string[] = []
for (const asset of assets) {
const stat = await fs.stat(path.join(assetsDir, asset))
if (stat.isFile()) {
assetFiles.push(asset)
}
}
console.log(`π Analyzing ${assetFiles.length} assets for usage`)
const mentioned = new Map<string, boolean>()
for (const asset of assetFiles) {
mentioned.set(asset, false)
}
const mdFiles = await findFiles(researchRoot, ['.md'])
for (const mdFile of mdFiles) {
const txt = await fs.readFile(mdFile, 'utf-8')
for (const asset of assetFiles) {
if (txt.includes(asset)) {
mentioned.set(asset, true)
}
}
}
const unused = assetFiles.filter((a) => !mentioned.get(a))
if (unused.length === 0) {
console.log('β
No unused assets found.')
return
}
console.log(`ποΈ Found ${unused.length} unused assets:`)
for (const f of unused) {
console.log(' β’', f)
}
const readline = await import('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const answer = await new Promise<string>((resolve) => {
rl.question('Delete them? (y/N): ', resolve)
})
rl.close()
if (answer.toLowerCase().startsWith('y')) {
for (const f of unused) {
await fs.unlink(path.join(assetsDir, f))
console.log(`ποΈ Deleted ${f}`)
}
}
}
// ββ entry point βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function main(): Promise<void> {
console.log('π Starting preprocessing...')
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
clean: {
type: 'boolean',
default: false,
},
},
})
const research = path.join(REPO, 'Research')
const docs = path.join(REPO, 'docs')
const blogEn = path.join(REPO, 'blog')
const blogKo = path.join(REPO, 'i18n', 'ko', 'docusaurus-plugin-content-blog')
const postsSrc = path.join(REPO, 'posts')
const cfg = path.join(REPO, 'config')
const outTs = path.join(REPO, 'src', 'data')
const assets = path.join(research, 'assets')
// await sanitiseMd(docs)
// await processBlog(postsSrc, blogEn, blogKo, cfg)
await buildBacklinks(docs, outTs)
// await processDocs(research, docs)
// await fixImgAlt(docs)
if (values.clean) {
await cleanupAssets(assets, research)
}
console.log('β
Preprocess completed.')
}
// Run if executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch(console.error)
}