Skip to content

Instantly share code, notes, and snippets.

@JessicaMulein
Created March 2, 2023 01:22
Show Gist options
  • Save JessicaMulein/591ed3b738c7f666e250550565ac10aa to your computer and use it in GitHub Desktop.
Save JessicaMulein/591ed3b738c7f666e250550565ac10aa to your computer and use it in GitHub Desktop.
marked-linkify-it with TypeScript
// taken directly from https://github.com/UziTech/marked-linkify-it and strongly typed
import LinkifyIt from 'linkify-it';
import { marked } from 'marked';
import tlds from 'tlds';
export class markedLinkifyIt implements marked.MarkedExtension {
constructor(schemas = {}, options = {}) {
const linkify = new LinkifyIt(schemas, options);
linkify
.tlds(tlds) // Reload with full tlds list
.tlds('onion', true) // Add unofficial `.onion` domain
.set({ fuzzyIP: true }); // Enable IPs in fuzzy links (without schema)
addTlds(linkify, options);
return {
extensions: [
{
name: 'autolink',
level: 'inline',
start: (src: string) => {
const link = getNextLink(linkify, src);
if (!link) {
return;
}
return link.index;
},
tokenizer(src: string) {
const link = getNextLink(linkify, src);
if (!link) {
return;
}
let raw;
if (link.index === 0) {
raw = link.raw;
} else if (
link.index === 1 &&
src.charAt(0) === '<' &&
src.charAt(link.lastIndex) === '>'
) {
raw = `<${link.raw}>`;
}
if (!raw) {
return;
}
return {
type: 'link',
raw,
text: link.text,
href: link.url,
tokens: [
{
type: 'text',
raw: link.text,
text: link.text,
},
],
};
},
},
],
};
}
}
function getNextLink(linkify: LinkifyIt.LinkifyIt, src: string) {
const match = linkify.match(src);
if (!match || !match.length) {
return;
}
return match[0];
}
function addTlds(
linkify: LinkifyIt.LinkifyIt,
options: { tlds?: string[]; tldsKeepOld?: boolean }
) {
const tlds = options.tlds;
delete options.tlds;
const tldsKeepOld = options.tldsKeepOld;
delete options.tldsKeepOld;
if (tlds) {
linkify.tlds(tlds, tldsKeepOld);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment