|
| 1 | +const { createMdxAstCompiler } = require("@mdx-js/mdx"); |
| 2 | + |
| 3 | +const astCompiler = createMdxAstCompiler({ remarkPlugins: [] }); |
| 4 | + |
| 5 | +const fs = require("fs"); |
| 6 | +const glob = require("glob"); |
| 7 | +const util = require("util"); |
| 8 | +const { parse } = require("path"); |
| 9 | +const { execSync } = require("child_process"); |
| 10 | + |
| 11 | +main() |
| 12 | + |
| 13 | +async function main() { |
| 14 | + const matches = await util.promisify(glob)("**/*.{md,mdx}", { cwd: "docs" }); |
| 15 | + for (const file of matches) { |
| 16 | + const path = parse(file); |
| 17 | + const basePath = `scripts/js/src/${path.dir}/${path.name}`; |
| 18 | + fs.mkdirSync(basePath, { |
| 19 | + recursive: true, |
| 20 | + }); |
| 21 | + |
| 22 | + const content = fs.readFileSync(`docs/${file}`); |
| 23 | + |
| 24 | + const root = astCompiler.parse(content); |
| 25 | + |
| 26 | + let index = 1; |
| 27 | + function writeFile(node, i, array) { |
| 28 | + if (writeCodeToFile(node, i, array, `${basePath}/${index}.ts`)) { |
| 29 | + index++; |
| 30 | + } |
| 31 | + if (node.children) { |
| 32 | + node.children.forEach((element, i, array) => { |
| 33 | + writeFile(element, i, array); |
| 34 | + }); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + writeFile(root); |
| 39 | + } |
| 40 | + |
| 41 | + process.chdir("scripts/js"); |
| 42 | + |
| 43 | + execSync("yarn init -y"); |
| 44 | + execSync("yarn add etebase typescript"); |
| 45 | + execSync("yarn tsc --init"); |
| 46 | + |
| 47 | + try { |
| 48 | + execSync("yarn tsc --noEmit"); |
| 49 | + } catch (e) { |
| 50 | + console.log(e.stdout.toString()); |
| 51 | + console.error(e.stderr.toString()); |
| 52 | + process.exit(1); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +function writeCodeToFile(node, i, array, file) { |
| 57 | + if ( |
| 58 | + node.type === "jsx" && |
| 59 | + node.value && |
| 60 | + node.value.includes('<TabItem value="js">') |
| 61 | + ) { |
| 62 | + const codePieces = []; |
| 63 | + for (let j = i + 1; j < array.length; j++) { |
| 64 | + if ( |
| 65 | + array[j].type === "jsx" && |
| 66 | + array[j].value && |
| 67 | + array[j].value.includes("</TabItem>") |
| 68 | + ) { |
| 69 | + break; |
| 70 | + } |
| 71 | + if (array[j].type === "code" && array[j].lang === "js") { |
| 72 | + codePieces.push({ |
| 73 | + code: array[j].value, |
| 74 | + start: array[j].position.start, |
| 75 | + end: array[j].position.end, |
| 76 | + }); |
| 77 | + } |
| 78 | + } |
| 79 | + const output = ` |
| 80 | +import * as Etebase from 'etebase'; |
| 81 | +
|
| 82 | +async function main() { |
| 83 | +${codePieces.map((piece) => ` |
| 84 | +//-start ${JSON.stringify(piece.start)} |
| 85 | +${piece.code} |
| 86 | +//-end ${JSON.stringify(piece.end)} |
| 87 | +` |
| 88 | +).join('')} |
| 89 | +}`; |
| 90 | + fs.writeFileSync(file, output); |
| 91 | + return true; |
| 92 | + } |
| 93 | + return false; |
| 94 | +} |
0 commit comments