UNPKG

smarkdown

Version:

Markdown parser, simplicity and extensibility.

1,199 lines (1,190 loc) 71.1 kB
/*! * Smarkdown v1.1.0 * (c) 2018-present Yahtnif <yahtnif@gmail.com> * Released under the Anti 996 License. */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var escapeTestRegex = /[&<>"']/; var escapeReplaceRegex = /[&<>"']/g; var replacements = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; var escapeTestNoEncodeRegex = /[<>"']|&(?!#?\w+;)/; var escapeReplaceNoEncodeRegex = /[<>"']|&(?!#?\w+;)/g; var unescapeRegex = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi; function escape$1(html, encode) { if (encode) { if (escapeTestRegex.test(html)) { return html.replace(escapeReplaceRegex, function (ch) { return replacements[ch]; }); } } else if (escapeTestNoEncodeRegex.test(html)) { return html.replace(escapeReplaceNoEncodeRegex, function (ch) { return replacements[ch]; }); } return html; } function unescape(html) { return html.replace(unescapeRegex, function (_, n) { n = n.toLowerCase(); if (n === 'colon') return ':'; if (n.charAt(0) === '#') { return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); } return ''; }); } var htmlTagsRegex = /<[!\/a-z](?:.|\n)*?>/gim; var specialCharsRegex = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g; var dotSpaceRegex = /(\s|\.)/g; var Slugger = (function () { function Slugger() { this.seen = {}; } Slugger.prototype.slug = function (value, isUnique) { var slug = value .trim() .toLowerCase() .replace(htmlTagsRegex, '') .replace(specialCharsRegex, '') .replace(dotSpaceRegex, '-'); if (isUnique !== false) { if (this.seen.hasOwnProperty(slug)) { var originalSlug = slug; do { this.seen[originalSlug]++; slug = originalSlug + '-' + this.seen[originalSlug]; } while (this.seen.hasOwnProperty(slug)); } this.seen[slug] = 0; } return slug; }; return Slugger; }()); var slugger = new Slugger(); function rtrim(str, c, invert) { if (invert === void 0) { invert = false; } if (str.length === 0) { return ''; } var suffLen = 0; while (suffLen < str.length) { var currChar = str.charAt(str.length - suffLen - 1); if (currChar === c && !invert) { suffLen++; } else if (currChar !== c && invert) { suffLen++; } else { break; } } return str.substr(0, str.length - suffLen); } var originIndependentUrlRegex = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; var noLastSlashUrlRegex = /^[^:]+:\/*[^/]*$/; var protocolRegex = /^([^:]+:)[\s\S]*$/; var domainRegex = /^([^:]+:\/*[^/]*)[\s\S]*$/; var baseUrls = {}; function resolveUrl(base, href) { if (originIndependentUrlRegex.test(href)) { return href; } var baseUrlsKey = ' ' + base; if (!baseUrls[baseUrlsKey]) { if (noLastSlashUrlRegex.test(base)) { baseUrls[baseUrlsKey] = base + '/'; } else { baseUrls[baseUrlsKey] = rtrim(base, '/', true); } } base = baseUrls[baseUrlsKey]; var relativeBase = base.indexOf(':') === -1; if (href.slice(0, 2) === '//') { if (relativeBase) { return href; } return base.replace(protocolRegex, '$1') + href; } else if (href.charAt(0) === '/') { if (relativeBase) { return href; } return base.replace(domainRegex, '$1') + href; } else { return base + href; } } var nonWordAndColonRegex = /[^\w:]/g; function cleanUrl(sanitize, base, href) { if (sanitize) { var prot = void 0; try { prot = decodeURIComponent(unescape(href)) .replace(nonWordAndColonRegex, '') .toLowerCase(); } catch (e) { return null; } if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { return null; } } if (base && !originIndependentUrlRegex.test(href)) { href = resolveUrl(base, href); } try { href = encodeURI(href).replace(/%25/g, '%'); } catch (e) { return null; } return href; } var caretRegex = /(^|[^\[])\^/g; var ExtendRegexp = (function () { function ExtendRegexp(regex, flags) { if (flags === void 0) { flags = ''; } this.source = regex.source; this.flags = flags; } ExtendRegexp.prototype.setGroup = function (groupName, groupRegexp) { var newRegexp = typeof groupRegexp === 'string' ? groupRegexp : groupRegexp.source; newRegexp = newRegexp.replace(caretRegex, '$1'); this.source = this.source.replace(groupName, newRegexp); return this; }; ExtendRegexp.prototype.getRegex = function () { return new RegExp(this.source, this.flags); }; return ExtendRegexp; }()); var noopRegex = /S^/; var breakCharRegex = /^\^\(*\\*./; function getBreakChar(regExp) { return regExp.source.match(breakCharRegex)[0].slice(1); } function getRuleType(regExp) { return regExp.source; } function isBlockRule(regExp) { return regExp.source.indexOf('\\n') > -1; } var blockCommentRegex = /<!--(?!-?>)[\s\S]*?-->/; var TokenType; (function (TokenType) { TokenType[TokenType["blockquoteEnd"] = 1] = "blockquoteEnd"; TokenType[TokenType["blockquoteStart"] = 2] = "blockquoteStart"; TokenType[TokenType["code"] = 3] = "code"; TokenType[TokenType["footnote"] = 4] = "footnote"; TokenType[TokenType["heading"] = 5] = "heading"; TokenType[TokenType["hr"] = 6] = "hr"; TokenType[TokenType["html"] = 7] = "html"; TokenType[TokenType["listEnd"] = 8] = "listEnd"; TokenType[TokenType["listItemEnd"] = 9] = "listItemEnd"; TokenType[TokenType["listItemStart"] = 10] = "listItemStart"; TokenType[TokenType["listStart"] = 11] = "listStart"; TokenType[TokenType["looseItemEnd"] = 12] = "looseItemEnd"; TokenType[TokenType["looseItemStart"] = 13] = "looseItemStart"; TokenType[TokenType["paragraph"] = 14] = "paragraph"; TokenType[TokenType["raw"] = 15] = "raw"; TokenType[TokenType["space"] = 16] = "space"; TokenType[TokenType["table"] = 17] = "table"; TokenType[TokenType["text"] = 18] = "text"; })(TokenType || (TokenType = {})); var Options = (function () { function Options() { this.baseUrl = null; this.breaks = false; this.disabledRules = []; this.extra = false; this.gfm = true; this.headerId = false; this.headerPrefix = ''; this.langAttribute = false; this.langPrefix = 'language-'; this.linksInNewTab = false; this.mangle = true; this.pedantic = false; this.sanitize = false; this.silent = false; this.smartLists = false; this.smartypants = false; this.xhtml = false; this.escape = escape$1; this.unescape = unescape; this.slug = function (str, isUnique) { return slugger.slug(str, isUnique); }; this.rtrim = rtrim; this.resolveUrl = resolveUrl; this.cleanUrl = cleanUrl; this.nop = false; } return Options; }()); var baseBlockHtml = '^ {0,3}(?:' + '<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' + '|comment[^\\n]*(\\n+|$)' + '|<\\?[\\s\\S]*?\\?>\\n*' + '|<![A-Z][\\s\\S]*?>\\n*' + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*' + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' + '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' + ')'; var baseBlockRules = { _comment: blockCommentRegex, blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, bullet: /(?:[*+-]|\d{1,9}\.)/, code: /^( {4}[^\n]+\n*)+/, def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, fences: /^ {0,3}(`{3,}|~{3,})([^`~\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, heading: /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/, hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, html: new RegExp(baseBlockHtml), item: /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/, lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/, list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, newline: /^\n+/, _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/, text: /^[^\n]+/ }; var baseBlockLabel = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/; var baseBlockTitle = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; baseBlockRules.def = new ExtendRegexp(baseBlockRules.def) .setGroup('label', baseBlockLabel) .setGroup('title', baseBlockTitle) .getRegex(); baseBlockRules.item = new ExtendRegexp(baseBlockRules.item, 'gm') .setGroup(/bull/g, baseBlockRules.bullet) .getRegex(); baseBlockRules.list = new ExtendRegexp(baseBlockRules.list) .setGroup(/bull/g, baseBlockRules.bullet) .setGroup('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))') .setGroup('def', '\\n+(?=' + baseBlockRules.def.source + ')') .getRegex(); var baseBlockTag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|options' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul'; var baseBlockAttribute = / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/; baseBlockRules.html = new ExtendRegexp(baseBlockRules.html, 'i') .setGroup('comment', baseBlockRules._comment) .setGroup('tag', baseBlockTag) .setGroup('attribute', baseBlockAttribute) .getRegex(); baseBlockRules.paragraph = new ExtendRegexp(baseBlockRules._paragraph) .setGroup('hr', baseBlockRules.hr) .setGroup('heading', ' {0,3}#{1,6} ') .setGroup('|lheading', '') .setGroup('blockquote', ' {0,3}>') .setGroup('fences', ' {0,3}(?:`{3,}|~{3,})[^`\\n]*\\n') .setGroup('list', ' {0,3}(?:[*+-]|1[.)]) ') .setGroup('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)') .setGroup('tag', baseBlockTag) .getRegex(); baseBlockRules.blockquote = new ExtendRegexp(baseBlockRules.blockquote) .setGroup('paragraph', baseBlockRules.paragraph) .getRegex(); var pedanticBlockHtml = '^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))'; var pedanticBlockTag = '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b'; var pedanticBlockHtmlRegex = new ExtendRegexp(new RegExp(pedanticBlockHtml)) .setGroup('comment', baseBlockRules._comment) .setGroup(/tag/g, pedanticBlockTag) .getRegex(); var pedanticBlockRules = __assign(__assign({}, baseBlockRules), { def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/, fences: noopRegex, paragraph: new ExtendRegexp(baseBlockRules._paragraph) .setGroup('hr', baseBlockRules.hr) .setGroup('heading', ' *#{1,6} *[^\n]') .setGroup('lheading', baseBlockRules.lheading) .setGroup('blockquote', ' {0,3}>') .setGroup('|fences', '') .setGroup('|list', '') .setGroup('|html', '') .getRegex(), html: pedanticBlockHtmlRegex }); var gfmBlockNptable = new ExtendRegexp(new RegExp('^ *([^|\\n ].*\\|.*)\\n' + ' *([-:]+ *\\|[-| :]*)' + '(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)')) .setGroup('hr', baseBlockRules.hr) .setGroup('heading', ' {0,3}#{1,6} ') .setGroup('blockquote', ' {0,3}>') .setGroup('code', ' {4}[^\\n]') .setGroup('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') .setGroup('list', ' {0,3}(?:[*+-]|1[.)]) ') .setGroup('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)') .setGroup('tag', baseBlockTag) .getRegex(); var gfmBlockTable = new ExtendRegexp(new RegExp('^ *\\|(.+)\\n' + ' *\\|?( *[-:]+[-| :]*)' + '(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)')) .setGroup('hr', baseBlockRules.hr) .setGroup('heading', ' {0,3}#{1,6} ') .setGroup('lheading', '([^\\n]+)\\n {0,3}(=+|-+) *(?:\\n+|$)') .setGroup('blockquote', ' {0,3}>') .setGroup('code', ' {4}[^\\n]') .setGroup('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') .setGroup('list', ' {0,3}(?:[*+-]|1[.)]) ') .setGroup('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)') .setGroup('tag', baseBlockTag) .getRegex(); var gfmBlockRules = __assign(__assign({}, baseBlockRules), { checkbox: /^\[([ xX])\] +/, nptable: gfmBlockNptable, table: gfmBlockTable }); var extraBlockRules = __assign(__assign({}, gfmBlockRules), { paragraph: new ExtendRegexp(gfmBlockRules.paragraph) .setGroup('footnote', /^\[\^([^\]]+)\]: *([^\n]*(?:\n+|$)(?: {1,}[^\n]*(?:\n+|$))*)/) .getRegex(), footnote: /^\[\^([^\]]+)\]: ([^\n]+)/ }); var baseInlineTag = '^comment' + '|^</[a-zA-Z][\\w:-]*\\s*>' + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' + '|^<\\?[\\s\\S]*?\\?>' + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>'; var baseInlineRules = { _escapes: /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g, _label: /(?:\[[^\[\]]*\]|\\.|`[^`]*`|[^\[\]\\`])*?/, autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, br: /^( {2,}|\\)\n(?!\s*$)/, code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, em: /^_([^\s_])_(?!_)|^\*([^\s*<\[])\*(?!\*)|^_([^\s<][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_<][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s<"][\s\S]*?[^\s\*])\*(?!\*|[^\spunctuation])|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/, escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/, tag: new RegExp(baseInlineTag), text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/ }; var baseInlineAattribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; var baseInlineEmail = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; var baseInlineHref = /<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*/; var baseInlinePunctuation = '!"#$%&\'()*+,\\-./:;<=>?@\\[^_{|}~'; var baseInlineScheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; var baseInlineTitle = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; baseInlineRules.em = new ExtendRegexp(baseInlineRules.em) .setGroup(/punctuation/g, baseInlinePunctuation) .getRegex(); baseInlineRules.autolink = new ExtendRegexp(baseInlineRules.autolink) .setGroup('scheme', baseInlineScheme) .setGroup('email', baseInlineEmail) .getRegex(); baseInlineRules.tag = new ExtendRegexp(baseInlineRules.tag) .setGroup('comment', blockCommentRegex) .setGroup('attribute', baseInlineAattribute) .getRegex(); baseInlineRules.link = new ExtendRegexp(baseInlineRules.link) .setGroup('label', baseInlineRules._label) .setGroup('href', baseInlineHref) .setGroup('title', baseInlineTitle) .getRegex(); baseInlineRules.reflink = new ExtendRegexp(baseInlineRules.reflink) .setGroup('label', baseInlineRules._label) .getRegex(); var pedanticInlineLinkRegex = new ExtendRegexp(/^!?\[(label)\]\((.*?)\)/) .setGroup('label', baseInlineRules._label) .getRegex(); var pedanticInlineReflinkRegex = new ExtendRegexp(/^!?\[(label)\]\s*\[([^\]]*)\]/) .setGroup('label', baseInlineRules._label) .getRegex(); var pedanticInlineRules = __assign(__assign({}, baseInlineRules), { em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, link: pedanticInlineLinkRegex, reflink: pedanticInlineReflinkRegex, strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/ }); var gfmInlineEscape = new ExtendRegexp(baseInlineRules.escape) .setGroup('])', '~|])') .getRegex(); var gfmInlineExtendedEmail = /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/; var _url = /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/; var gfmInlineUrl = new ExtendRegexp(_url, 'i') .setGroup('email', gfmInlineExtendedEmail) .getRegex(); var gfmInlineBackpedal = /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/; var gfmInlineDel = /^~~(?=\S)([\s\S]*?\S)~~/; var gfmInlineText = /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/; var gfmInlineRules = __assign(__assign({}, baseInlineRules), { _backpedal: gfmInlineBackpedal, del: gfmInlineDel, escape: gfmInlineEscape, text: gfmInlineText, url: gfmInlineUrl }); var breaksInlineRules = __assign(__assign({}, gfmInlineRules), { br: new ExtendRegexp(gfmInlineRules.br).setGroup('{2,}', '*').getRegex(), text: new ExtendRegexp(gfmInlineRules.text) .setGroup('\\b_', '\\b_| {2,}\\n') .setGroup(/\{2,\}/g, '*') .getRegex() }); var extraInlineRules = { fnref: new ExtendRegexp(/^!?\[\^(label)\]/) .setGroup('label', gfmInlineRules._label) .getRegex() }; var BlockLexer = (function () { function BlockLexer(self, options) { this.self = self; this.links = Object.create(null); this.tokens = []; this.options = options; this.setRules(); } BlockLexer.lex = function (src, options, top) { var lexer = new this(this, options); return lexer.getTokens(src, top); }; BlockLexer.setRule = function (regExp, renderer, options) { if (options === void 0) { options = {}; } var ruleType = getRuleType(regExp); if (BlockLexer.newRules.some(function (R) { return R.type === ruleType; })) { this.unsetRule(regExp); } BlockLexer.newRules.push({ options: options, rule: regExp, type: ruleType }); this.blockRenderers.push({ renderer: renderer, type: ruleType }); }; BlockLexer.unsetRule = function (regExp) { var ruleType = getRuleType(regExp); BlockLexer.newRules = BlockLexer.newRules.filter(function (R) { return R.type !== ruleType; }); this.blockRenderers = this.blockRenderers.filter(function (R) { return R.type !== ruleType; }); }; BlockLexer.getBaseRules = function () { if (this.baseRules) return this.baseRules; return (this.baseRules = baseBlockRules); }; BlockLexer.getPedanticRules = function () { if (this.pedanticRules) return this.pedanticRules; return (this.pedanticRules = pedanticBlockRules); }; BlockLexer.getGfmRules = function () { if (this.gfmRules) return this.gfmRules; return (this.gfmRules = gfmBlockRules); }; BlockLexer.getExtraRules = function () { if (this.extraRules) return this.extraRules; return (this.extraRules = extraBlockRules); }; BlockLexer.prototype.setRules = function () { var _this = this; if (this.options.pedantic) { this.rules = this.self.getPedanticRules(); } else if (this.options.extra) { this.rules = this.self.getExtraRules(); } else if (this.options.gfm) { this.rules = this.self.getGfmRules(); } else { this.rules = this.self.getBaseRules(); } this.options.disabledRules.forEach(function (rule) { _this.rules[rule] = noopRegex; }); this.isGfm = this.rules.fences !== undefined; this.isExtra = this.rules.footnote !== undefined; }; BlockLexer.prototype.getTokens = function (src, top) { var nextPart = src; var execArr; var newRules = this.self.newRules || []; var newRulesTop = newRules .filter(function (R) { return R.options.priority; }) .sort(function (a, b) { return b.options.priority - a.options.priority; }); var newRulesBottom = newRules.filter(function (R) { return !R.options.priority; }); mainLoop: while (nextPart) { if ((execArr = this.rules.newline.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); if (execArr[0].length > 1) { this.tokens.push({ type: TokenType.space }); } } for (var _i = 0, newRulesTop_1 = newRulesTop; _i < newRulesTop_1.length; _i++) { var R = newRulesTop_1[_i]; if ((execArr = R.rule.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: R.type, execArr: execArr }); continue mainLoop; } } if ((execArr = this.rules.code.exec(nextPart))) { var lastToken = this.tokens[this.tokens.length - 1]; nextPart = nextPart.substring(execArr[0].length); if (lastToken && lastToken.type === 'paragraph') { lastToken.text += "\n" + execArr[0].trimRight(); } else { var code = execArr[0].replace(/^ {4}/gm, ''); this.tokens.push({ type: TokenType.code, codeBlockStyle: 'indented', text: !this.options.pedantic ? this.options.rtrim(code, '\n') : code }); } continue; } if (this.isGfm && (execArr = this.rules.fences.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: TokenType.code, lang: execArr[2] ? execArr[2].trim() : execArr[2], text: execArr[3] || '' }); continue; } if (this.isExtra && (execArr = this.rules.footnote.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); var item = { type: TokenType.footnote, refname: this.options.slug(execArr[1], false), text: execArr[2] }; this.tokens.push(item); continue; } if ((execArr = this.rules.heading.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: TokenType.heading, depth: execArr[1].length, text: execArr[2], ends: execArr[3] || '' }); continue; } if (this.isGfm && (execArr = this.rules.nptable.exec(nextPart))) { var item = { type: TokenType.table, header: this.splitCells(execArr[1].replace(/^ *| *\| *$/g, '')), align: execArr[2] .replace(/^ *|\| *$/g, '') .split(/ *\| */), cells: [] }; if (item.header.length === item.align.length) { nextPart = nextPart.substring(execArr[0].length); for (var i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } var cells = execArr[3] ? execArr[3].replace(/\n$/, '').split('\n') : []; for (var i = 0; i < cells.length; i++) { item.cells[i] = this.splitCells(cells[i], item.header.length); } this.tokens.push(item); continue; } } if ((execArr = this.rules.hr.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: TokenType.hr, text: execArr[0] }); continue; } if ((execArr = this.rules.blockquote.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: TokenType.blockquoteStart }); var blockquote = execArr[0].replace(/^ *> ?/gm, ''); this.getTokens(blockquote, top); this.tokens.push({ type: TokenType.blockquoteEnd }); continue; } if ((execArr = this.rules.list.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); var bull = execArr[2]; var isordered = bull.length > 1; var listStart = { type: TokenType.listStart, ordered: isordered, start: isordered ? +bull : '', loose: false }; this.tokens.push(listStart); var arr = execArr[0].match(this.rules.item); var listItems = []; var length_1 = arr.length; var next = false, space = void 0, blockBullet = void 0, loose = void 0, item = void 0, checked = void 0; for (var i = 0; i < length_1; i++) { item = arr[i]; checked = null; space = item.length; item = item.replace(/^ *([*+-]|\d+\.) */, ''); if (this.isGfm && (execArr = this.rules.checkbox.exec(item))) { checked = execArr[1] !== ' '; item = item.replace(this.rules.checkbox, ''); } if (item.indexOf('\n ') !== -1) { space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } if (i !== length_1 - 1) { blockBullet = this.self.getBaseRules().bullet.exec(arr[i + 1])[0]; if (bull.length > 1 ? blockBullet.length === 1 : blockBullet.length > 1 || (this.options.smartLists && blockBullet !== bull)) { nextPart = arr.slice(i + 1).join('\n') + nextPart; i = length_1 - 1; } } loose = next || /\n\n(?!\s*$)/.test(item); if (i !== length_1 - 1) { next = item.charAt(item.length - 1) === '\n'; if (!loose) loose = next; } if (loose) { listStart.loose = true; } var token = { loose: loose, checked: checked, type: TokenType.listItemStart }; listItems.push(token); this.tokens.push(token); this.getTokens(item, false); this.tokens.push({ type: TokenType.listItemEnd }); } if (listStart.loose) { for (var i = 0; i < listItems.length; i++) { listItems[i].loose = true; } } this.tokens.push({ type: TokenType.listEnd }); continue; } if ((execArr = this.rules.html.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); var attr = execArr[1]; var isPre = attr === 'pre' || attr === 'script' || attr === 'style'; this.tokens.push({ type: this.options.sanitize ? TokenType.paragraph : TokenType.html, pre: !this.options.sanitizer && isPre, text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(execArr[0]) : escape(execArr[0]) : execArr[0] }); continue; } if (top && (execArr = this.rules.def.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); var tag = execArr[1].toLowerCase().replace(/\s+/g, ' '); if (!this.links[tag]) { var title = execArr[3]; if (title) { title = title.substring(1, title.length - 1); } this.links[tag] = { title: title, href: execArr[2] }; } continue; } if (this.isGfm && (execArr = this.rules.table.exec(nextPart))) { var item = { type: TokenType.table, header: this.splitCells(execArr[1].replace(/^ *| *\| *$/g, '')), align: execArr[2] .replace(/^ *|\| *$/g, '') .split(/ *\| */), cells: [] }; if (item.header.length === item.align.length) { nextPart = nextPart.substring(execArr[0].length); for (var i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } var cells = execArr[3] ? execArr[3].replace(/\n$/, '').split('\n') : []; for (var i = 0; i < cells.length; i++) { item.cells[i] = this.splitCells(cells[i].replace(/^ *\| *| *\| *$/g, ''), item.header.length); } this.tokens.push(item); continue; } } for (var _a = 0, newRulesBottom_1 = newRulesBottom; _a < newRulesBottom_1.length; _a++) { var R = newRulesBottom_1[_a]; if ((execArr = R.rule.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: R.type, execArr: execArr }); continue mainLoop; } } if ((execArr = this.rules.lheading.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: TokenType.heading, depth: execArr[2].charAt(0) === '=' ? 1 : 2, text: execArr[1] }); continue; } if (top && (execArr = this.rules.paragraph.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); if (execArr[1].slice(-1) === '\n') { this.tokens.push({ type: TokenType.paragraph, text: execArr[1].slice(0, -1) }); } else { this.tokens.push({ type: this.tokens.length > 0 ? TokenType.paragraph : TokenType.text, text: execArr[1] }); } continue; } if ((execArr = this.rules.text.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.tokens.push({ type: TokenType.text, text: execArr[0] }); continue; } if (nextPart) { throw new Error("Infinite loop on byte: " + nextPart.charCodeAt(0) + ", near text '" + nextPart.slice(0, 30) + "...'"); } } return { tokens: this.tokens, links: this.links }; }; BlockLexer.prototype.splitCells = function (tableRow, count) { var row = tableRow.replace(/\|/g, function (match, offset, str) { var escaped = false, curr = offset; while (--curr >= 0 && str[curr] === '\\') escaped = !escaped; if (escaped) { return '|'; } else { return ' |'; } }); var cells = row.split(/ \|/); if (cells.length > count) { cells.splice(count); } else { while (cells.length < count) cells.push(''); } for (var i = 0; i < cells.length; i++) { cells[i] = cells[i].trim().replace(/\\\|/g, '|'); } return cells; }; BlockLexer.blockRenderers = []; BlockLexer.newRules = []; return BlockLexer; }()); var Renderer = (function () { function Renderer(options) { this._footnotes = []; this._headings = []; this.options = options || {}; } Renderer.prototype.blockquote = function (quote) { return "<blockquote>\n" + quote + "</blockquote>\n"; }; Renderer.prototype.code = function (code, language, escaped) { var lang = (language || '').match(/\S*/)[0]; if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out !== null && out !== code) { escaped = true; code = out; } } if (!lang) { return "<pre><code>" + (escaped ? code : this.options.escape(code, true)) + "</code></pre>"; } var dataLang = this.options.langAttribute ? " data-lang=\"" + this.options.escape(lang, true) + "\"" : ''; return "<pre" + dataLang + "><code class=\"" + this.options.langPrefix + this.options.escape(lang, true) + "\">" + (escaped ? code : this.options.escape(code, true)) + "</code></pre>\n"; }; Renderer.prototype.footnote = function (footnotes) { var out = "<div class=\"footnotes\" role=\"doc-endnotes\">" + this.hr() + "<ol>"; for (var _i = 0, _a = this._footnotes; _i < _a.length; _i++) { var refname = _a[_i]; out += "<li id=\"fn:" + refname + "\" role=\"doc-endnote\"><span class=\"cite-text\">" + (footnotes[refname] || '?') + "</span><a href=\"#fnref:" + refname + "\" class=\"footnote-backref\" role=\"doc-backlink\">&#8617;</a></li>"; } out += '</ol></div>'; this._footnotes = []; return out; }; Renderer.prototype.heading = function (text, level, raw, ends) { var headerId = this.options.headerId; var attr = ''; if (headerId === true || (headerId === 'off' && ends) || (headerId === 'on' && !ends)) { var id = this.options.slug(raw); var count = this._headings.filter(function (h) { return h === raw; }).length; if (count > 0) { id += "-" + count; } attr += " id=\"" + this.options.headerPrefix + id + "\""; this._headings.push(raw); } return "<h" + level + attr + ">" + text + "</h" + level + ">\n"; }; Renderer.prototype.hr = function (text) { return this.options.xhtml ? '<hr/>\n' : '<hr>\n'; }; Renderer.prototype.html = function (html) { return html; }; Renderer.prototype.list = function (body, ordered, start, isTaskList) { var type = ordered ? 'ol' : 'ul'; var startatt = ordered && start !== 1 ? ' start="' + start + '"' : ''; if (isTaskList) { startatt += ' class="task-list"'; } return "<" + type + startatt + ">\n" + body + "</" + type + ">\n"; }; Renderer.prototype.listitem = function (text, checked) { return checked === null ? "<li>" + text + "</li>\n" : "<li class=\"task-list-item\"><input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (checked ? ' checked' : '') + " disabled> " + text + "</li>\n"; }; Renderer.prototype.paragraph = function (text) { return "<p>" + text + "</p>\n"; }; Renderer.prototype.table = function (header, body) { if (body) body = '<tbody>' + body + '</tbody>'; return "\n<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n"; }; Renderer.prototype.tablerow = function (content) { return "<tr>\n" + content + "</tr>\n"; }; Renderer.prototype.tablecell = function (content, flags) { var header = flags.header, align = flags.align; var type = header ? 'th' : 'td'; var tag = align ? '<' + type + ' align="' + align + '">' : '<' + type + '>'; return tag + content + '</' + type + '>\n'; }; Renderer.prototype.br = function () { return this.options.xhtml ? '<br/>' : '<br>'; }; Renderer.prototype.codespan = function (text) { return "<code>" + text + "</code>"; }; Renderer.prototype.del = function (text) { return "<del>" + text + "</del>"; }; Renderer.prototype.em = function (text) { return "<em>" + text + "</em>"; }; Renderer.prototype.fnref = function (refname) { if (this._footnotes.indexOf(refname) === -1) { this._footnotes.push(refname); } return "<sup id=\"fnref:" + refname + "\"><a href=\"#fn:" + refname + "\" class=\"footnote-ref\" role=\"doc-noteref\">" + this._footnotes.length + "</a></sup>"; }; Renderer.prototype.image = function (href, title, text) { href = this.options.cleanUrl(this.options.sanitize, this.options.baseUrl, href); if (href === null) return text; var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; return out; }; Renderer.prototype.link = function (href, title, text) { href = this.options.cleanUrl(this.options.sanitize, this.options.baseUrl, href); if (href === null) return text; var out = '<a href="' + this.options.escape(href) + '"'; if (title) { out += ' title="' + title + '"'; } var _a = this.options, linksInNewTab = _a.linksInNewTab, trimLinkText = _a.trimLinkText; var targetBlank = linksInNewTab === true || (typeof linksInNewTab === 'function' && linksInNewTab.call(this, href)); if (typeof targetBlank === 'string') { out += targetBlank; } else if (targetBlank) { out += " target=\"_blank\""; } if (trimLinkText) { text = trimLinkText(text); } out += '>' + text + '</a>'; return out; }; Renderer.prototype.strong = function (text) { return "<strong>" + text + "</strong>"; }; Renderer.prototype.text = function (text) { return text; }; return Renderer; }()); var TextRenderer = (function () { function TextRenderer() { } TextRenderer.prototype.br = function () { return ''; }; TextRenderer.prototype.html = function (html) { return html; }; TextRenderer.prototype.codespan = function (text) { return text; }; TextRenderer.prototype.del = function (text) { return text; }; TextRenderer.prototype.em = function (text) { return text; }; TextRenderer.prototype.image = function (href, title, text) { return '' + text; }; TextRenderer.prototype.link = function (href, title, text) { return '' + text; }; TextRenderer.prototype.strong = function (text) { return text; }; TextRenderer.prototype.text = function (text) { return text; }; return TextRenderer; }()); var InlineLexer = (function () { function InlineLexer(self, links, options, renderer) { if (links === void 0) { links = {}; } this.self = self; this.links = links; this.options = options; this.sortByPriority = function (a, b) { return b.options.priority - a.options.priority; }; this.renderer = renderer || this.options.renderer || new Renderer(this.options); this.renderer.options = this.options; this.setRules(); } InlineLexer.output = function (src, links, options) { var inlineLexer = new this(this, links, options); return inlineLexer.output(src); }; InlineLexer.setRule = function (regExp, renderer, options) { if (options === void 0) { options = {}; } var ruleType = getRuleType(regExp); if (this.newRules.some(function (R) { return R.type !== ruleType; })) { this.unsetRule(regExp); } this.newRules.push({ breakChar: getBreakChar(regExp), options: options, render: renderer, rule: regExp, type: ruleType }); this.isTextBreakSync = false; }; InlineLexer.unsetRule = function (regExp) { var ruleType = getRuleType(regExp); InlineLexer.newRules = InlineLexer.newRules.filter(function (R) { return R.type !== ruleType; }); this.isTextBreakSync = false; }; InlineLexer.getBaseRules = function () { if (this.baseRules) return this.baseRules; return (this.baseRules = baseInlineRules); }; InlineLexer.getPedanticRules = function () { if (this.pedanticRules) return this.pedanticRules; return (this.pedanticRules = pedanticInlineRules); }; InlineLexer.getGfmRules = function () { if (this.gfmRules) return this.gfmRules; return (this.gfmRules = gfmInlineRules); }; InlineLexer.getBreaksRules = function () { if (this.breaksRules) return this.breaksRules; return (this.breaksRules = breaksInlineRules); }; InlineLexer.getExtraRules = function (options) { if (this.extraRules) return this.extraRules; var rules = options.breaks ? this.getBreaksRules() : this.getGfmRules(); return (this.extraRules = __assign(__assign({}, rules), extraInlineRules)); }; InlineLexer.prototype.setRules = function () { var _this = this; if (this.options.pedantic) { this.rules = this.self.getPedanticRules(); } else if (this.options.extra) { this.rules = this.self.getExtraRules(this.options); } else if (this.options.gfm) { this.rules = this.options.breaks ? this.self.getBreaksRules() : this.self.getGfmRules(); } else { this.rules = this.self.getBaseRules(); } if (!this.self.isTextBreakSync) { var textRuleStr = this.rules.text.source; if (!this.defaultTextBreak) { this.defaultTextBreak = textRuleStr.match(/\?=\[(.+?)\]/)[1]; } var textBreak = this.defaultTextBreak + InlineLexer.newRules .filter(function (R) { return _this.defaultTextBreak.indexOf(R.breakChar) === -1; }) .map(function (R) { return R.breakChar; }) .filter(function (v, i, a) { return a.indexOf(v) === i; }) .join(''); this.rules.text = new RegExp(textRuleStr.replace(this.defaultTextBreak, textBreak)); } this.options.disabledRules.forEach(function (rule) { _this.rules[rule] = noopRegex; }); this.isGfm = this.rules.url !== undefined; this.isExtra = this.rules.fnref !== undefined; }; InlineLexer.prototype.escapes = function (text) { return text ? text.replace(this.rules._escapes, '$1') : text; }; InlineLexer.prototype.findClosingBracket = function (str, b) { if (str.indexOf(b[1]) === -1) { return -1; } var level = 0; for (var i = 0; i < str.length; i++) { if (str[i] === '\\') { i++; } else if (str[i] === b[0]) { level++; } else if (str[i] === b[1]) { level--; if (level < 0) { return i; } } } return -1; }; InlineLexer.prototype.output = function (nextPart) { var execArr; var out