Skip to content

Commit

Permalink
fix: Percent-encode Markdown reserved symbols in URLs (#26)
Browse files Browse the repository at this point in the history
Encode symbols in URLS which break some MD renderers, like in Discord embeds, where URLs containing these symbols sometimes break.
  • Loading branch information
AndrejsK committed Oct 24, 2021
1 parent 43c3c2d commit 83d4fff
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
27 changes: 24 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,19 +187,40 @@ export const defaultTranslators: TranslatorConfigObject = {
const href = node.getAttribute('href');
if (!href) return {};

// Encodes symbols that can cause problems in markdown
let encodedHref = '';
for (const chr of href) {
switch (chr) {
case '(':
encodedHref += '%28';
break;
case ')':
encodedHref += '%29';
break;
case '_':
encodedHref += '%5F';
break;
case '*':
encodedHref += '%2A';
break;
default:
encodedHref += chr;
}
}

const title = node.getAttribute('title');

// Inline link, when possible
// See: https://github.com/crosstype/node-html-markdown/issues/17
if (node.textContent === href) return { content: `<${href}>` };
if (node.textContent === href) return { content: `<${encodedHref}>` };

return {
postprocess: ({ content }) => content.replace(/(?:\r?\n)+/g, ' '),
childTranslators: visitor.instance.aTagTranslators,
prefix: '[',
postfix: ']' + (!options.useLinkReferenceDefinitions
? `(${href}${title ? ` "${title}"` : ''})`
: `[${visitor.addOrGetUrlDefinition(href)}]`)
? `(${encodedHref}${title ? ` "${title}"` : ''})`
: `[${visitor.addOrGetUrlDefinition(encodedHref)}]`)
}
},

Expand Down
5 changes: 4 additions & 1 deletion test/default-tags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,17 @@ describe(`Default Tags`, () => {

test(`Link (a)`, () => {
const url = 'http://www.github.com/crosstype';
const specialUrl = 'http://www.github.com/crosstype/**/_test(123)';
const encodedSpecialUrl = 'http://www.github.com/crosstype/%2A%2A/%5Ftest%28123%29';
const res = translate(`
<a href="${url}">a<br><br>b<strong>c</strong></a>
<a>a<strong>b</strong></a> <!-- This node is treated as text due to no href -->
<a href="${url}">${url}</a>
<!-- see: https://github.com/crosstype/node-html-markdown/issues/25 -->
<a href="${url}">a<a href="2">nested</a><img src="${url}">b</a>
<b><i><a href="${specialUrl}" title="a">b</a></i></b>
`);
expect(res).toBe(`[a b**c**](${url}) a**b** <${url}> [a](${url})[nested](2)![](${url})b `);
expect(res).toBe(`[a b**c**](${url}) a**b** <${url}> [a](${url})[nested](2)![](${url})b **_[b](${encodedSpecialUrl} "a")_** `);
});

test(`Image (img)`, () => {
Expand Down

0 comments on commit 83d4fff

Please sign in to comment.