|
| 1 | +import type { Plugin } from 'vite' |
| 2 | + |
| 3 | +export function replacer(code: string, value: string, key: string, insert: 'head' | 'tail' | 'none' = 'none') { |
| 4 | + const START = `<!--${key}_STARTS-->` |
| 5 | + const END = `<!--${key}_ENDS-->` |
| 6 | + const regex = new RegExp(`${START}[\\s\\S]*?${END}`, 'im') |
| 7 | + |
| 8 | + const target = value ? `${START}\n\n${value.trim()}\n\n${END}` : `${START}${END}` |
| 9 | + |
| 10 | + if (!code.match(regex)) { |
| 11 | + if (insert === 'none') |
| 12 | + return code |
| 13 | + else if (insert === 'head') |
| 14 | + return `${target}\n\n${code}` |
| 15 | + else |
| 16 | + return `${code}\n\n${target}` |
| 17 | + } |
| 18 | + |
| 19 | + return code.replace(regex, target) |
| 20 | +} |
| 21 | + |
| 22 | +export function MarkdownTransform(): Plugin { |
| 23 | + return { |
| 24 | + name: 'js-utils-md-transform', |
| 25 | + enforce: 'pre', |
| 26 | + async transform(code, id) { |
| 27 | + if (!id.match(/\.md\b/)) |
| 28 | + return null |
| 29 | + |
| 30 | + const [pkg, _name, i] = id.split('/').slice(-3); |
| 31 | + |
| 32 | + if (pkg !== 'reference') |
| 33 | + return code; |
| 34 | + |
| 35 | + const source = await getFunctionMarkdown(_name, i) |
| 36 | + |
| 37 | + code = replacer(code, source, 'FOOTER', 'tail') |
| 38 | + |
| 39 | + code = code |
| 40 | + .replace(/(# \w+)\n/, `$1\n\n<FunctionInfo pkgName="${i.replace('.md', '')}"/>\n`); |
| 41 | + |
| 42 | + return code |
| 43 | + }, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +const GITHUB_BLOB_URL = 'https://github.com/agiletech-web-dev/js-utils-es/blob/main/src'; |
| 48 | +const GITHUB_BLOB_DOCS_URL = 'https://github.com/agiletech-web-dev/js-utils-es/blob/main/docs/reference'; |
| 49 | +// https://github.com/agiletech-web-dev/js-utils-es/blob/main/src/array/chunk.ts |
| 50 | +// https://github.com/agiletech-web-dev/js-utils-es/blob/main/docs/reference/array/chunk.md |
| 51 | + |
| 52 | +export async function getFunctionMarkdown(pkg: string, name: string) { |
| 53 | + const fileNameTs = name.replace('.md', '.ts'); |
| 54 | + const fileNameTestCase = name.replace('.md', '.spec.ts'); |
| 55 | + const URL = `${GITHUB_BLOB_URL}/${pkg}/${fileNameTs}`; |
| 56 | + const URL_DOCS = `${GITHUB_BLOB_DOCS_URL}/${pkg}/${name}`; |
| 57 | + const URL_TEST_CASE = `${GITHUB_BLOB_URL}/${pkg}/${fileNameTestCase}`; |
| 58 | + |
| 59 | + const links = ([ |
| 60 | + ['Source', URL], |
| 61 | + ['Docs', URL_DOCS], |
| 62 | + ['Test Case', URL_TEST_CASE], |
| 63 | + ]) |
| 64 | + .filter(i => i) |
| 65 | + .map(i => `[${i![0]}](${i![1]})`).join(' • ') |
| 66 | + |
| 67 | + const sourceSection = `## Source\n\n${links}\n` |
| 68 | + |
| 69 | + const footer = `\n${sourceSection}` |
| 70 | + |
| 71 | + return footer; |
| 72 | +} |
0 commit comments