|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const matter = require('gray-matter'); |
| 4 | + |
| 5 | +module.exports = function markdownPagesPlugin(context, options = {}) { |
| 6 | + const docsDir = path.resolve(context.siteDir, options.docsDir || 'docs'); |
| 7 | + const routeBasePath = options.routeBasePath || '/'; |
| 8 | + |
| 9 | + function walkDir(dir) { |
| 10 | + if (!fs.existsSync(dir)) return []; |
| 11 | + return fs.readdirSync(dir).flatMap((name) => { |
| 12 | + const full = path.join(dir, name); |
| 13 | + if (fs.statSync(full).isDirectory()) return walkDir(full); |
| 14 | + if (/\.(md|mdx)$/i.test(name)) return [full]; |
| 15 | + return []; |
| 16 | + }); |
| 17 | + } |
| 18 | + |
| 19 | + function resolveUrlPath(filePath, frontmatter) { |
| 20 | + if (frontmatter.slug) { |
| 21 | + const slug = frontmatter.slug.replace(/^\/+/, '').replace(/\/+$/, ''); |
| 22 | + return slug || 'index'; |
| 23 | + } |
| 24 | + const rel = path.relative(docsDir, filePath).replace(/\\/g, '/'); |
| 25 | + const withoutExt = rel.replace(/\.(md|mdx)$/i, ''); |
| 26 | + const id = frontmatter.id || path.basename(withoutExt); |
| 27 | + const dir = path.dirname(withoutExt); |
| 28 | + if (dir === '.') return id; |
| 29 | + return `${dir}/${id}`; |
| 30 | + } |
| 31 | + |
| 32 | + return { |
| 33 | + name: 'markdown-pages', |
| 34 | + |
| 35 | + async postBuild({ outDir }) { |
| 36 | + const files = walkDir(docsDir); |
| 37 | + let generated = 0; |
| 38 | + let excluded = 0; |
| 39 | + |
| 40 | + for (const filePath of files) { |
| 41 | + const raw = fs.readFileSync(filePath, 'utf8'); |
| 42 | + const { data: frontmatter } = matter(raw); |
| 43 | + |
| 44 | + const urlPath = resolveUrlPath(filePath, frontmatter); |
| 45 | + const outputPath = path.join(outDir, urlPath + '.md'); |
| 46 | + |
| 47 | + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); |
| 48 | + |
| 49 | + if (frontmatter.llm_exclude) { |
| 50 | + fs.writeFileSync(outputPath, frontmatter.llm_exclude + '\n'); |
| 51 | + excluded++; |
| 52 | + } else { |
| 53 | + fs.writeFileSync(outputPath, raw); |
| 54 | + generated++; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + console.log( |
| 59 | + `[markdown-pages] Generated ${generated} markdown files, ${excluded} excluded` |
| 60 | + ); |
| 61 | + }, |
| 62 | + }; |
| 63 | +}; |
0 commit comments