Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(readme): rewrite relative urls with github cdn paths #52

Merged
merged 1 commit into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions routes/repos/[owner]/[repo]/readme.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
const GH_RAW_URL = "https://raw.githubusercontent.com";

export default cachedEventHandler(
async (event) => {
const repo = `${event.context.params.owner}/${event.context.params.repo}`;
const defaultBranch = await ghRepo(repo).then(
(r) => r.default_branch || "main",
);
const markdown = await $fetch<string>(
`https://raw.githubusercontent.com/${repo}/${defaultBranch}/README.md`,
);
const cdnBaseURL = `${GH_RAW_URL}/${repo}/${defaultBranch}`;
const markdown = await $fetch<string>(`${cdnBaseURL}/README.md`);
const html = await ghMarkdown(markdown, repo, "readme");
return {
html,
markdown,
markdown: resolveMarkdownRelativeLinks(markdown, cdnBaseURL),
html: resolveMarkdownRelativeLinks(html, cdnBaseURL),
};
},
{
Expand Down
23 changes: 23 additions & 0 deletions utils/markdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const MARKDOWN_LINK_RE =
/(?<link>\[.*?]\((?<url>.*?)\)|<img.*?src="(?<url2>.*?)".*?>)/g;

/**
* HTML & Mardown Function to replace relative image paths with absolute paths
*/
export function resolveMarkdownRelativeLinks(
content: string,
cdnBaseURL: string,
) {
console.log("fixing", content);
cpreston321 marked this conversation as resolved.
Show resolved Hide resolved
return content.replace(
MARKDOWN_LINK_RE,
(match, _, url: string | undefined, url2: string) => {
const path = url || url2;
// If path is already a URL, return the match
if (path.startsWith("http") || path.startsWith("https")) {
return match;
}
return match.replace(path, `${cdnBaseURL}/${path.replace(/^\.\//, "")}`);
},
);
}