reformat-mdx.mjs 932 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env node
  2. 'use strict'
  3. import { readFileSync, writeFileSync } from 'node:fs';
  4. import { join, dirname } from 'node:path';
  5. import { fileURLToPath } from 'node:url'
  6. import { sync } from 'glob';
  7. import beautify from 'js-beautify';
  8. const __dirname = dirname(fileURLToPath(import.meta.url))
  9. const docs = sync(join(__dirname, '..', 'docs', '**', '*.mdx'))
  10. docs.forEach((file, i) => {
  11. const oldContent = readFileSync(file, 'utf8')
  12. // get codeblocks from markdown
  13. const content = oldContent.replace(/(```([a-z0-9]+).*?\n)(.*?)(```)/gs, (m, m1, m2, m3, m4) => {
  14. if (m2 === 'html') {
  15. // m3 = beautify.default.html(m3, {
  16. // "indent_size": 2,
  17. // "indent_char": " ",
  18. // }).trim();
  19. // remove empty lines
  20. m3 = m3.replace(/^\s*[\r\n]/gm, '');
  21. return m1 + m3 + "\n" + m4;
  22. }
  23. return m
  24. })
  25. if (content !== oldContent) {
  26. writeFileSync(file, content, 'utf8')
  27. console.log(`Reformatted ${file}`)
  28. }
  29. })