Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lukeed
Created April 29, 2022 18:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lukeed/d63a4561ce9859765d8f0e518b941642 to your computer and use it in GitHub Desktop.
Save lukeed/d63a4561ce9859765d8f0e518b941642 to your computer and use it in GitHub Desktop.
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);
}
@spike090
Copy link

@cloudmail.ru

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment