import snarkdown from 'https://cdn.pika.dev/snarkdown/^1.2.2'
import {
walk,
WalkOptions,
WalkEntry,
} from 'https://deno.land/std@0.51.0/fs/walk.ts'
import { readFileStr } from 'https://deno.land/std@0.51.0/fs/read_file_str.ts'
import { writeFileStr } from 'https://deno.land/std@0.51.0/fs/write_file_str.ts'
import { ensureDir } from 'https://deno.land/std@0.51.0/fs/ensure_dir.ts'
const targetDir = 'public'
interface MDFile {
name: string
path: string
content: string
}
interface HTMLFile {
originalPath: string
originalName: string
name: string
path: string
content: string
}
interface ParsedFile {
content: string
path: string
}
const walkOptions: WalkOptions = {
includeDirs: false,
exts: ['md'],
}
const headerTemplate = (files: HTMLFile[]) => (title: string) => `
${title}
`
const findMarkdownFiles = async () => {
const result = []
for await (const entry of walk('.', walkOptions)) {
result.push(entry)
}
return result
}
const withFileContent = async (entry: WalkEntry): Promise => {
const content = await readFileStr(entry.path, { encoding: 'utf8' })
return {
path: entry.path,
name: entry.name,
content,
}
}
const parseMarkdown = (mdFile: MDFile): HTMLFile => {
const html = snarkdown(mdFile.content)
return {
originalPath: mdFile.path,
originalName: mdFile.name,
path: mdFile.path.replace(/md$/, 'html'),
name: mdFile.name.replace(/\.md$/, ''),
content: html,
}
}
const addSurroundings = (headerCreator: (title: string) => string) => (
htmlFile: HTMLFile
): ParsedFile => {
const content = `
${htmlFile.name}
${headerCreator(htmlFile.name)}${htmlFile.content}
`
return {
path: htmlFile.path,
content,
}
}
const files = await findMarkdownFiles()
const markdownFiles = await Promise.all(files.map(withFileContent))
const htmlFiles = markdownFiles.map(parseMarkdown)
const createHeader = headerTemplate(htmlFiles)
const parsedFiles = htmlFiles.map(addSurroundings(createHeader))
await ensureDir(targetDir)
parsedFiles.forEach((file) =>
writeFileStr(`${targetDir}/${file.path}`, file.content)
)