-
-
Save lukeed/d63a4561ce9859765d8f0e518b941642 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs'; | |
import * as astray from 'astray'; | |
import { toMarkdown } from 'mdast-util-to-markdown'; | |
import { fromMarkdown } from 'mdast-util-from-markdown'; | |
/** | |
* @param {string} file The "*.md" file path. | |
*/ | |
export async function modify(file) { | |
let content = await fs.promises.read(file, 'utf8'); | |
let AST = fromMarkdown(content); | |
let title = ''; | |
astray.walk(AST, { | |
/** | |
* Read the page's <h1> to determine page's title. | |
*/ | |
heading(node) { | |
// ignore if not <h1> header | |
if (node.depth !== 1) return; | |
astray.walk(node, { | |
text(t: MDAST.Text) { | |
// Grab the text value of the H1 | |
title += t.value; | |
}, | |
}); | |
return astray.SKIP; | |
}, | |
/** | |
* Update all anchor links (<a>) for consistent internal linking. | |
*/ | |
link(node) { | |
let value = node.url; | |
// Ignore section header links (same page) | |
if (value.startsWith('#')) return; | |
if (/^(https?:)?\/\//.test(value)) { | |
let tmp = new URL(value); | |
// Rewrite our own "https://developers.cloudflare.com" links | |
// so that they are absolute, path-based links instead. | |
if (tmp.origin === 'https://developers.cloudflare.com') { | |
value = tmp.pathname + tmp.search + tmp.hash; | |
} | |
} | |
// ... other normalization logic ... | |
// Update the link's `href` value | |
node.url = value; | |
} | |
}); | |
// Now the AST has been modified in place. | |
// AKA, the same `AST` variable is (or may be) different than before. | |
// Convert the AST back to a final string. | |
let updated = toMarkdown(AST); | |
// Write the updated markdown file | |
await fs.promises.writeFile(file, updated); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@cloudmail.ru