{"version":3,"file":"index.js","sources":["../index.tsx","../index.cjs.tsx"],"sourcesContent":["/* @jsx h */\n/**\n * markdown-to-jsx is a fork of [simple-markdown v0.2.2](https://github.com/Khan/simple-markdown)\n * from Khan Academy. Thank you Khan devs for making such an awesome and extensible\n * parsing infra... without it, half of the optimizations here wouldn't be feasible. 🙏🏼\n */\nimport * as React from 'react'\n\nexport namespace MarkdownToJSX {\n /**\n * RequireAtLeastOne<{ ... }> <- only requires at least one key\n */\n type RequireAtLeastOne = Pick<\n T,\n Exclude\n > &\n {\n [K in Keys]-?: Required> & Partial>>\n }[Keys]\n\n export type CreateElement = typeof React.createElement\n\n export type HTMLTags = keyof JSX.IntrinsicElements\n\n export type State = {\n _inAnchor?: boolean\n _inline?: boolean\n _inTable?: boolean\n _key?: React.Key\n _list?: boolean\n _simple?: boolean\n }\n\n export type ParserResult = {\n [key: string]: any\n type?: string\n }\n\n export type NestedParser = (\n input: string,\n state?: MarkdownToJSX.State\n ) => MarkdownToJSX.ParserResult\n\n export type Parser = (\n capture: RegExpMatchArray,\n nestedParse: NestedParser,\n state?: MarkdownToJSX.State\n ) => ParserOutput\n\n export type RuleOutput = (\n ast: MarkdownToJSX.ParserResult,\n state: MarkdownToJSX.State\n ) => JSX.Element\n\n export type Rule = {\n _match: (\n source: string,\n state: MarkdownToJSX.State,\n prevCapturedString?: string\n ) => RegExpMatchArray\n _order: Priority\n _parse: MarkdownToJSX.Parser\n _react?: (\n node: ParserOutput,\n output: RuleOutput,\n state?: MarkdownToJSX.State\n ) => React.ReactChild\n }\n\n export type Rules = {\n [key: string]: Rule\n }\n\n export type Override =\n | RequireAtLeastOne<{\n component: React.ElementType\n props: Object\n }>\n | React.ElementType\n\n export type Overrides = {\n [tag in HTMLTags]?: Override\n } & {\n [customComponent: string]: Override\n }\n\n export type Options = Partial<{\n /**\n * Ultimate control over the output of all rendered JSX.\n */\n createElement: (\n tag: Parameters[0],\n props: JSX.IntrinsicAttributes,\n ...children: React.ReactChild[]\n ) => JSX.Element\n\n /**\n * Disable the compiler's best-effort transcription of provided raw HTML\n * into JSX-equivalent. This is the functionality that prevents the need to\n * use `dangerouslySetInnerHTML` in React.\n */\n disableParsingRawHTML: boolean\n\n /**\n * Forces the compiler to always output content with a block-level wrapper\n * (`

` or any block-level syntax your markdown already contains.)\n */\n forceBlock: boolean\n\n /**\n * Forces the compiler to always output content with an inline wrapper (``)\n */\n forceInline: boolean\n\n /**\n * Supply additional HTML entity: unicode replacement mappings.\n *\n * Pass only the inner part of the entity as the key,\n * e.g. `≤` -> `{ \"le\": \"\\u2264\" }`\n *\n * By default\n * the following entities are replaced with their unicode equivalents:\n *\n * ```\n * &\n * '\n * >\n * <\n *  \n * "\n * ```\n */\n namedCodesToUnicode: {\n [key: string]: string\n }\n\n /**\n * Selectively control the output of particular HTML tags as they would be\n * emitted by the compiler.\n */\n overrides: Overrides\n\n /**\n * Declare the type of the wrapper to be used when there are multiple\n * children to render. Set to `null` to get an array of children back\n * without any wrapper, or use `React.Fragment` to get a React element\n * that won't show up in the DOM.\n */\n wrapper: React.ElementType | null\n\n /**\n * Forces the compiler to wrap results, even if there is only a single\n * child or no children.\n */\n forceWrapper: boolean\n\n /**\n * Override normalization of non-URI-safe characters for use in generating\n * HTML IDs for anchor linking purposes.\n */\n slugify: (source: string) => string\n }>\n}\n\n/** TODO: Drop for React 16? */\nconst ATTRIBUTE_TO_JSX_PROP_MAP = [\n 'allowFullScreen',\n 'allowTransparency',\n 'autoComplete',\n 'autoFocus',\n 'autoPlay',\n 'cellPadding',\n 'cellSpacing',\n 'charSet',\n 'className',\n 'classId',\n 'colSpan',\n 'contentEditable',\n 'contextMenu',\n 'crossOrigin',\n 'encType',\n 'formAction',\n 'formEncType',\n 'formMethod',\n 'formNoValidate',\n 'formTarget',\n 'frameBorder',\n 'hrefLang',\n 'inputMode',\n 'keyParams',\n 'keyType',\n 'marginHeight',\n 'marginWidth',\n 'maxLength',\n 'mediaGroup',\n 'minLength',\n 'noValidate',\n 'radioGroup',\n 'readOnly',\n 'rowSpan',\n 'spellCheck',\n 'srcDoc',\n 'srcLang',\n 'srcSet',\n 'tabIndex',\n 'useMap',\n].reduce(\n (obj, x) => {\n obj[x.toLowerCase()] = x\n return obj\n },\n { for: 'htmlFor' }\n)\n\nconst namedCodesToUnicode = {\n amp: '\\u0026',\n apos: '\\u0027',\n gt: '\\u003e',\n lt: '\\u003c',\n nbsp: '\\u00a0',\n quot: '\\u201c',\n} as const\n\nconst DO_NOT_PROCESS_HTML_ELEMENTS = ['style', 'script']\n\n/**\n * the attribute extractor regex looks for a valid attribute name,\n * followed by an equal sign (whitespace around the equal sign is allowed), followed\n * by one of the following:\n *\n * 1. a single quote-bounded string, e.g. 'foo'\n * 2. a double quote-bounded string, e.g. \"bar\"\n * 3. an interpolation, e.g. {something}\n *\n * JSX can be be interpolated into itself and is passed through the compiler using\n * the same options and setup as the current run.\n *\n * } />\n * ==================\n * ↳ children: []\n *\n * Otherwise, interpolations are handled as strings or simple booleans\n * unless HTML syntax is detected.\n *\n * \n * ===== ====\n * ↓ ↳ disabled: true\n * ↳ color: \"green\"\n *\n * Numbers are not parsed at this time due to complexities around int, float,\n * and the upcoming bigint functionality that would make handling it unwieldy.\n * Parse the string in your component as desired.\n *\n * \n * ==================\n * ↳ someBigNumber: \"123456789123456789\"\n */\nconst ATTR_EXTRACTOR_R =\n /([-A-Z0-9_:]+)(?:\\s*=\\s*(?:(?:\"((?:\\\\.|[^\"])*)\")|(?:'((?:\\\\.|[^'])*)')|(?:\\{((?:\\\\.|{[^}]*?}|[^}])*)\\})))?/gi\n\n/** TODO: Write explainers for each of these */\n\nconst AUTOLINK_MAILTO_CHECK_R = /mailto:/i\nconst BLOCK_END_R = /\\n{2,}$/\nconst BLOCKQUOTE_R = /^( *>[^\\n]+(\\n[^\\n]+)*\\n*)+\\n{2,}/\nconst BLOCKQUOTE_TRIM_LEFT_MULTILINE_R = /^ *> ?/gm\nconst BREAK_LINE_R = /^ {2,}\\n/\nconst BREAK_THEMATIC_R = /^(?:( *[-*_])){3,} *(?:\\n *)+\\n/\nconst CODE_BLOCK_FENCED_R =\n /^\\s*(`{3,}|~{3,}) *(\\S+)?([^\\n]*?)?\\n([\\s\\S]+?)\\s*\\1 *(?:\\n *)*\\n?/\nconst CODE_BLOCK_R = /^(?: {4}[^\\n]+\\n*)+(?:\\n *)+\\n?/\nconst CODE_INLINE_R = /^(`+)\\s*([\\s\\S]*?[^`])\\s*\\1(?!`)/\nconst CONSECUTIVE_NEWLINE_R = /^(?:\\n *)*\\n/\nconst CR_NEWLINE_R = /\\r\\n?/g\nconst FOOTNOTE_R = /^\\[\\^([^\\]]+)](:.*)\\n/\nconst FOOTNOTE_REFERENCE_R = /^\\[\\^([^\\]]+)]/\nconst FORMFEED_R = /\\f/g\nconst GFM_TASK_R = /^\\s*?\\[(x|\\s)\\]/\nconst HEADING_R = /^ *(#{1,6}) *([^\\n]+?)(?: +#*)?(?:\\n *)*(?:\\n|$)/\nconst HEADING_SETEXT_R = /^([^\\n]+)\\n *(=|-){3,} *(?:\\n *)+\\n/\n\n/**\n * Explanation:\n *\n * 1. Look for a starting tag, preceded by any amount of spaces\n * ^ *<\n *\n * 2. Capture the tag name (capture 1)\n * ([^ >/]+)\n *\n * 3. Ignore a space after the starting tag and capture the attribute portion of the tag (capture 2)\n * ?([^>]*)\\/{0}>\n *\n * 4. Ensure a matching closing tag is present in the rest of the input string\n * (?=[\\s\\S]*<\\/\\1>)\n *\n * 5. Capture everything until the matching closing tag -- this might include additional pairs\n * of the same tag type found in step 2 (capture 3)\n * ((?:[\\s\\S]*?(?:<\\1[^>]*>[\\s\\S]*?<\\/\\1>)*[\\s\\S]*?)*?)<\\/\\1>\n *\n * 6. Capture excess newlines afterward\n * \\n*\n */\nconst HTML_BLOCK_ELEMENT_R =\n /^ *(?!<[a-z][^ >/]* ?\\/>)<([a-z][^ >/]*) ?([^>]*)\\/{0}>\\n?(\\s*(?:<\\1[^>]*?>[\\s\\S]*?<\\/\\1>|(?!<\\1)[\\s\\S])*?)<\\/\\1>\\n*/i\n\nconst HTML_CHAR_CODE_R = /&([a-zA-Z]+);/g\n\nconst HTML_COMMENT_R = /^)/\n\n/**\n * borrowed from React 15(https://github.com/facebook/react/blob/894d20744cba99383ffd847dbd5b6e0800355a5c/src/renderers/dom/shared/HTMLDOMPropertyConfig.js)\n */\nconst HTML_CUSTOM_ATTR_R = /^(data|aria|x)-[a-z_][a-z\\d_.-]*$/\n\nconst HTML_SELF_CLOSING_ELEMENT_R =\n /^ *<([a-z][a-z0-9:]*)(?:\\s+((?:<.*?>|[^>])*))?\\/?>(?!<\\/\\1>)(\\s*\\n)?/i\nconst INTERPOLATION_R = /^\\{.*\\}$/\nconst LINK_AUTOLINK_BARE_URL_R = /^(https?:\\/\\/[^\\s<]+[^<.,:;\"')\\]\\s])/\nconst LINK_AUTOLINK_MAILTO_R = /^<([^ >]+@[^ >]+)>/\nconst LINK_AUTOLINK_R = /^<([^ >]+:\\/[^ >]+)>/\nconst CAPTURE_LETTER_AFTER_HYPHEN = /-([a-z])?/gi\nconst NP_TABLE_R = /^(.*\\|?.*)\\n *(\\|? *[-:]+ *\\|[-| :]*)\\n((?:.*\\|.*\\n)*)\\n?/\nconst PARAGRAPH_R = /^[^\\n]+(?: \\n|\\n{2,})/\nconst REFERENCE_IMAGE_OR_LINK = /^\\[([^\\]]*)\\]:\\s+]+)>?\\s*(\"([^\"]*)\")?/\nconst REFERENCE_IMAGE_R = /^!\\[([^\\]]*)\\] ?\\[([^\\]]*)\\]/\nconst REFERENCE_LINK_R = /^\\[([^\\]]*)\\] ?\\[([^\\]]*)\\]/\nconst SQUARE_BRACKETS_R = /(\\[|\\])/g\nconst SHOULD_RENDER_AS_BLOCK_R = /(\\n|^[-*]\\s|^#|^ {2,}|^-{2,}|^>\\s)/\nconst TAB_R = /\\t/g\nconst TABLE_SEPARATOR_R = /^ *\\| */\nconst TABLE_TRIM_PIPES = /(^ *\\||\\| *$)/g\nconst TABLE_CELL_END_TRIM = / *$/\nconst TABLE_CENTER_ALIGN = /^ *:-+: *$/\nconst TABLE_LEFT_ALIGN = /^ *:-+ *$/\nconst TABLE_RIGHT_ALIGN = /^ *-+: *$/\n\nconst TEXT_BOLD_R =\n /^([*_])\\1((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~+.*?~+|.)*?)\\1\\1(?!\\1)/\nconst TEXT_EMPHASIZED_R =\n /^([*_])((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~+.*?~+|.)*?)\\1(?!\\1|\\w)/\nconst TEXT_MARKED_R = /^==((?:\\[.*?\\]|<.*?>(?:.*?<.*?>)?|`.*?`|.)*?)==/\nconst TEXT_STRIKETHROUGHED_R = /^~~((?:\\[.*?\\]|<.*?>(?:.*?<.*?>)?|`.*?`|.)*?)~~/\n\nconst TEXT_ESCAPED_R = /^\\\\([^0-9A-Za-z\\s])/\nconst TEXT_PLAIN_R =\n /^[\\s\\S]+?(?=[^0-9A-Z\\s\\u00c0-\\uffff&;.()'\"]|\\d+\\.|\\n\\n| {2,}\\n|\\w+:\\S|$)/i\n\nconst TRIM_STARTING_NEWLINES = /^\\n+/\n\nconst HTML_LEFT_TRIM_AMOUNT_R = /^([ \\t]*)/\n\nconst UNESCAPE_URL_R = /\\\\([^\\\\])/g\n\ntype LIST_TYPE = 1 | 2\nconst ORDERED: LIST_TYPE = 1\nconst UNORDERED: LIST_TYPE = 2\n\nconst LIST_ITEM_END_R = / *\\n+$/\nconst LIST_LOOKBEHIND_R = /(?:^|\\n)( *)$/\n\n// recognize a `*` `-`, `+`, `1.`, `2.`... list bullet\nconst ORDERED_LIST_BULLET = '(?:\\\\d+\\\\.)'\nconst UNORDERED_LIST_BULLET = '(?:[*+-])'\n\nfunction generateListItemPrefix(type: LIST_TYPE) {\n return (\n '( *)(' +\n (type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +\n ') +'\n )\n}\n\n// recognize the start of a list item:\n// leading space plus a bullet plus a space (` * `)\nconst ORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(ORDERED)\nconst UNORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(UNORDERED)\n\nfunction generateListItemPrefixRegex(type: LIST_TYPE) {\n return new RegExp(\n '^' +\n (type === ORDERED ? ORDERED_LIST_ITEM_PREFIX : UNORDERED_LIST_ITEM_PREFIX)\n )\n}\n\nconst ORDERED_LIST_ITEM_PREFIX_R = generateListItemPrefixRegex(ORDERED)\nconst UNORDERED_LIST_ITEM_PREFIX_R = generateListItemPrefixRegex(UNORDERED)\n\nfunction generateListItemRegex(type: LIST_TYPE) {\n // recognize an individual list item:\n // * hi\n // this is part of the same item\n //\n // as is this, which is a new paragraph in the same item\n //\n // * but this is not part of the same item\n return new RegExp(\n '^' +\n (type === ORDERED\n ? ORDERED_LIST_ITEM_PREFIX\n : UNORDERED_LIST_ITEM_PREFIX) +\n '[^\\\\n]*(?:\\\\n' +\n '(?!\\\\1' +\n (type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +\n ' )[^\\\\n]*)*(\\\\n|$)',\n 'gm'\n )\n}\n\nconst ORDERED_LIST_ITEM_R = generateListItemRegex(ORDERED)\nconst UNORDERED_LIST_ITEM_R = generateListItemRegex(UNORDERED)\n\n// check whether a list item has paragraphs: if it does,\n// we leave the newlines at the end\nfunction generateListRegex(type: LIST_TYPE) {\n const bullet = type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET\n\n return new RegExp(\n '^( *)(' +\n bullet +\n ') ' +\n '[\\\\s\\\\S]+?(?:\\\\n{2,}(?! )' +\n '(?!\\\\1' +\n bullet +\n ' (?!' +\n bullet +\n ' ))\\\\n*' +\n // the \\\\s*$ here is so that we can parse the inside of nested\n // lists, where our content might end before we receive two `\\n`s\n '|\\\\s*\\\\n*$)'\n )\n}\n\nconst ORDERED_LIST_R = generateListRegex(ORDERED)\nconst UNORDERED_LIST_R = generateListRegex(UNORDERED)\n\nfunction generateListRule(h: any, type: LIST_TYPE) {\n const ordered = type === ORDERED\n const LIST_R = ordered ? ORDERED_LIST_R : UNORDERED_LIST_R\n const LIST_ITEM_R = ordered ? ORDERED_LIST_ITEM_R : UNORDERED_LIST_ITEM_R\n const LIST_ITEM_PREFIX_R = ordered\n ? ORDERED_LIST_ITEM_PREFIX_R\n : UNORDERED_LIST_ITEM_PREFIX_R\n\n return {\n _match(source, state, prevCapture) {\n // We only want to break into a list if we are at the start of a\n // line. This is to avoid parsing \"hi * there\" with \"* there\"\n // becoming a part of a list.\n // You might wonder, \"but that's inline, so of course it wouldn't\n // start a list?\". You would be correct! Except that some of our\n // lists can be inline, because they might be inside another list,\n // in which case we can parse with inline scope, but need to allow\n // nested lists inside this inline scope.\n const isStartOfLine = LIST_LOOKBEHIND_R.exec(prevCapture)\n const isListBlock = state._list || (!state._inline && !state._simple)\n\n if (isStartOfLine && isListBlock) {\n source = isStartOfLine[1] + source\n\n return LIST_R.exec(source)\n } else {\n return null\n }\n },\n _order: Priority.HIGH,\n _parse(capture, parse, state) {\n const bullet = capture[2]\n const start = ordered ? +bullet : undefined\n const items = capture[0]\n // recognize the end of a paragraph block inside a list item:\n // two or more newlines at end end of the item\n .replace(BLOCK_END_R, '\\n')\n .match(LIST_ITEM_R)\n\n let lastItemWasAParagraph = false\n const itemContent = items.map(function (item, i) {\n // We need to see how far indented the item is:\n const space = LIST_ITEM_PREFIX_R.exec(item)[0].length\n\n // And then we construct a regex to \"unindent\" the subsequent\n // lines of the items by that amount:\n const spaceRegex = new RegExp('^ {1,' + space + '}', 'gm')\n\n // Before processing the item, we need a couple things\n const content = item\n // remove indents on trailing lines:\n .replace(spaceRegex, '')\n // remove the bullet:\n .replace(LIST_ITEM_PREFIX_R, '')\n\n // Handling \"loose\" lists, like:\n //\n // * this is wrapped in a paragraph\n //\n // * as is this\n //\n // * as is this\n const isLastItem = i === items.length - 1\n const containsBlocks = content.indexOf('\\n\\n') !== -1\n\n // Any element in a list is a block if it contains multiple\n // newlines. The last element in the list can also be a block\n // if the previous item in the list was a block (this is\n // because non-last items in the list can end with \\n\\n, but\n // the last item can't, so we just \"inherit\" this property\n // from our previous element).\n const thisItemIsAParagraph =\n containsBlocks || (isLastItem && lastItemWasAParagraph)\n lastItemWasAParagraph = thisItemIsAParagraph\n\n // backup our state for restoration afterwards. We're going to\n // want to set state._list to true, and state._inline depending\n // on our list's looseness.\n const oldStateInline = state._inline\n const oldStateList = state._list\n state._list = true\n\n // Parse inline if we're in a tight list, or block if we're in\n // a loose list.\n let adjustedContent\n if (thisItemIsAParagraph) {\n state._inline = false\n adjustedContent = content.replace(LIST_ITEM_END_R, '\\n\\n')\n } else {\n state._inline = true\n adjustedContent = content.replace(LIST_ITEM_END_R, '')\n }\n\n const result = parse(adjustedContent, state)\n\n // Restore our state before returning\n state._inline = oldStateInline\n state._list = oldStateList\n\n return result\n })\n\n return {\n _items: itemContent,\n _ordered: ordered,\n _start: start,\n }\n },\n _react(node, output, state) {\n const Tag = node._ordered ? 'ol' : 'ul'\n\n return (\n \n {node._items.map(function generateListItem(item, i) {\n return

  • {output(item, state)}
  • \n })}\n \n )\n },\n } as MarkdownToJSX.Rule<{\n _items: MarkdownToJSX.ParserResult[]\n _ordered: boolean\n _start?: number\n }>\n}\n\nconst LINK_R = /^\\[([^\\]]*)]\\( *((?:\\([^)]*\\)|[^() ])*) *\"?([^)\"]*)?\"?\\)/\nconst IMAGE_R = /^!\\[([^\\]]*)]\\( *((?:\\([^)]*\\)|[^() ])*) *\"?([^)\"]*)?\"?\\)/\n\nconst NON_PARAGRAPH_BLOCK_SYNTAXES = [\n BLOCKQUOTE_R,\n CODE_BLOCK_FENCED_R,\n CODE_BLOCK_R,\n HEADING_R,\n HEADING_SETEXT_R,\n HTML_COMMENT_R,\n NP_TABLE_R,\n ORDERED_LIST_ITEM_R,\n ORDERED_LIST_R,\n UNORDERED_LIST_ITEM_R,\n UNORDERED_LIST_R,\n]\n\nconst BLOCK_SYNTAXES = [\n ...NON_PARAGRAPH_BLOCK_SYNTAXES,\n PARAGRAPH_R,\n HTML_BLOCK_ELEMENT_R,\n HTML_SELF_CLOSING_ELEMENT_R,\n]\n\nfunction containsBlockSyntax(input: string) {\n return BLOCK_SYNTAXES.some(r => r.test(input))\n}\n\n/** Remove symmetrical leading and trailing quotes */\nfunction unquote(str: string) {\n const first = str[0]\n if (\n (first === '\"' || first === \"'\") &&\n str.length >= 2 &&\n str[str.length - 1] === first\n ) {\n return str.slice(1, -1)\n }\n return str\n}\n\n// based on https://stackoverflow.com/a/18123682/1141611\n// not complete, but probably good enough\nfunction slugify(str: string) {\n return str\n .replace(/[ÀÁÂÃÄÅàáâãäåæÆ]/g, 'a')\n .replace(/[çÇ]/g, 'c')\n .replace(/[ðÐ]/g, 'd')\n .replace(/[ÈÉÊËéèêë]/g, 'e')\n .replace(/[ÏïÎîÍíÌì]/g, 'i')\n .replace(/[Ññ]/g, 'n')\n .replace(/[øØœŒÕõÔôÓóÒò]/g, 'o')\n .replace(/[ÜüÛûÚúÙù]/g, 'u')\n .replace(/[ŸÿÝý]/g, 'y')\n .replace(/[^a-z0-9- ]/gi, '')\n .replace(/ /gi, '-')\n .toLowerCase()\n}\n\nfunction parseTableAlignCapture(alignCapture: string) {\n if (TABLE_RIGHT_ALIGN.test(alignCapture)) {\n return 'right'\n } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {\n return 'center'\n } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {\n return 'left'\n }\n\n return null\n}\n\nfunction parseTableRow(\n source: string,\n parse: MarkdownToJSX.NestedParser,\n state: MarkdownToJSX.State\n) {\n const prevInTable = state._inTable\n state._inTable = true\n const tableRow = parse(source.trim(), state)\n state._inTable = prevInTable\n\n let cells = [[]]\n tableRow.forEach(function (node, i) {\n if (node.type === 'tableSeparator') {\n // Filter out empty table separators at the start/end:\n if (i !== 0 && i !== tableRow.length - 1) {\n // Split the current row:\n cells.push([])\n }\n } else {\n if (\n node.type === 'text' &&\n (tableRow[i + 1] == null || tableRow[i + 1].type === 'tableSeparator')\n ) {\n node._content = node._content.replace(TABLE_CELL_END_TRIM, '')\n }\n cells[cells.length - 1].push(node)\n }\n })\n return cells\n}\n\nfunction parseTableAlign(source: string /*, parse, state*/) {\n const alignText = source.replace(TABLE_TRIM_PIPES, '').split('|')\n\n return alignText.map(parseTableAlignCapture)\n}\n\nfunction parseTableCells(\n source: string,\n parse: MarkdownToJSX.NestedParser,\n state: MarkdownToJSX.State\n) {\n const rowsText = source.trim().split('\\n')\n\n return rowsText.map(function (rowText) {\n return parseTableRow(rowText, parse, state)\n })\n}\n\nfunction parseTable(\n capture: RegExpMatchArray,\n parse: MarkdownToJSX.NestedParser,\n state: MarkdownToJSX.State\n) {\n state._inline = true\n const header = parseTableRow(capture[1], parse, state)\n const align = parseTableAlign(capture[2])\n const cells = parseTableCells(capture[3], parse, state)\n state._inline = false\n\n return {\n _align: align,\n _cells: cells,\n _header: header,\n type: 'table',\n }\n}\n\nfunction getTableStyle(node, colIndex) {\n return node._align[colIndex] == null\n ? {}\n : {\n textAlign: node._align[colIndex],\n }\n}\n\n/** TODO: remove for react 16 */\nfunction normalizeAttributeKey(key) {\n const hyphenIndex = key.indexOf('-')\n\n if (hyphenIndex !== -1 && key.match(HTML_CUSTOM_ATTR_R) === null) {\n key = key.replace(CAPTURE_LETTER_AFTER_HYPHEN, function (_, letter) {\n return letter.toUpperCase()\n })\n }\n\n return key\n}\n\nfunction attributeValueToJSXPropValue(\n key: keyof React.AllHTMLAttributes,\n value: string\n): any {\n if (key === 'style') {\n return value.split(/;\\s?/).reduce(function (styles, kvPair) {\n const key = kvPair.slice(0, kvPair.indexOf(':'))\n\n // snake-case to camelCase\n // also handles PascalCasing vendor prefixes\n const camelCasedKey = key.replace(/(-[a-z])/g, substr =>\n substr[1].toUpperCase()\n )\n\n // key.length + 1 to skip over the colon\n styles[camelCasedKey] = kvPair.slice(key.length + 1).trim()\n\n return styles\n }, {})\n } else if (key === 'href') {\n return sanitizeUrl(value)\n } else if (value.match(INTERPOLATION_R)) {\n // return as a string and let the consumer decide what to do with it\n value = value.slice(1, value.length - 1)\n }\n\n if (value === 'true') {\n return true\n } else if (value === 'false') {\n return false\n }\n\n return value\n}\n\nfunction normalizeWhitespace(source: string): string {\n return source\n .replace(CR_NEWLINE_R, '\\n')\n .replace(FORMFEED_R, '')\n .replace(TAB_R, ' ')\n}\n\n/**\n * Creates a parser for a given set of rules, with the precedence\n * specified as a list of rules.\n *\n * @rules: an object containing\n * rule type -> {match, order, parse} objects\n * (lower order is higher precedence)\n * (Note: `order` is added to defaultRules after creation so that\n * the `order` of defaultRules in the source matches the `order`\n * of defaultRules in terms of `order` fields.)\n *\n * @returns The resulting parse function, with the following parameters:\n * @source: the input source string to be parsed\n * @state: an optional object to be threaded through parse\n * calls. Allows clients to add stateful operations to\n * parsing, such as keeping track of how many levels deep\n * some nesting is. For an example use-case, see passage-ref\n * parsing in src/widgets/passage/passage-markdown.jsx\n */\nfunction parserFor(\n rules: MarkdownToJSX.Rules\n): (\n source: string,\n state: MarkdownToJSX.State\n) => ReturnType {\n // Sorts rules in order of increasing order, then\n // ascending rule name in case of ties.\n let ruleList = Object.keys(rules)\n\n /* istanbul ignore next */\n if (process.env.NODE_ENV !== 'production') {\n ruleList.forEach(function (type) {\n let order = rules[type]._order\n if (\n process.env.NODE_ENV !== 'production' &&\n (typeof order !== 'number' || !isFinite(order))\n ) {\n console.warn(\n 'markdown-to-jsx: Invalid order for rule `' + type + '`: ' + order\n )\n }\n })\n }\n\n ruleList.sort(function (typeA, typeB) {\n let orderA = rules[typeA]._order\n let orderB = rules[typeB]._order\n\n // First sort based on increasing order\n if (orderA !== orderB) {\n return orderA - orderB\n\n // Then based on increasing unicode lexicographic ordering\n } else if (typeA < typeB) {\n return -1\n }\n\n return 1\n })\n\n function nestedParse(\n source: string,\n state: MarkdownToJSX.State\n ): MarkdownToJSX.ParserResult[] {\n let result = []\n\n // We store the previous capture so that match functions can\n // use some limited amount of lookbehind. Lists use this to\n // ensure they don't match arbitrary '- ' or '* ' in inline\n // text (see the list rule for more information).\n let prevCapture = ''\n while (source) {\n let i = 0\n while (i < ruleList.length) {\n const ruleType = ruleList[i]\n const rule = rules[ruleType]\n const capture = rule._match(source, state, prevCapture)\n\n if (capture) {\n const currCaptureString = capture[0]\n source = source.substring(currCaptureString.length)\n const parsed = rule._parse(capture, nestedParse, state)\n\n // We also let rules override the default type of\n // their parsed node if they would like to, so that\n // there can be a single output function for all links,\n // even if there are several rules to parse them.\n if (parsed.type == null) {\n parsed.type = ruleType\n }\n\n result.push(parsed)\n\n prevCapture = currCaptureString\n break\n }\n\n i++\n }\n }\n\n return result\n }\n\n return function outerParse(source, state) {\n return nestedParse(normalizeWhitespace(source), state)\n }\n}\n\n// Creates a match function for an inline scoped or simple element from a regex\nfunction inlineRegex(regex: RegExp) {\n return function match(source, state: MarkdownToJSX.State) {\n if (state._inline) {\n return regex.exec(source)\n } else {\n return null\n }\n }\n}\n\n// basically any inline element except links\nfunction simpleInlineRegex(regex: RegExp) {\n return function match(source: string, state: MarkdownToJSX.State) {\n if (state._inline || state._simple) {\n return regex.exec(source)\n } else {\n return null\n }\n }\n}\n\n// Creates a match function for a block scoped element from a regex\nfunction blockRegex(regex: RegExp) {\n return function match(source: string, state: MarkdownToJSX.State) {\n if (state._inline || state._simple) {\n return null\n } else {\n return regex.exec(source)\n }\n }\n}\n\n// Creates a match function from a regex, ignoring block/inline scope\nfunction anyScopeRegex(regex: RegExp) {\n return function match(source: string /*, state*/) {\n return regex.exec(source)\n }\n}\n\nfunction matchParagraph(\n source: string,\n state: MarkdownToJSX.State,\n prevCapturedString?: string\n) {\n if (state._inline || state._simple) {\n return null\n }\n\n if (prevCapturedString && !prevCapturedString.endsWith('\\n')) {\n // don't match continuation of a line\n return null\n }\n\n let match = ''\n\n source.split('\\n').every(line => {\n // bail out on first sign of non-paragraph block\n if (NON_PARAGRAPH_BLOCK_SYNTAXES.some(regex => regex.test(line))) {\n return false\n }\n match += line + '\\n'\n return line.trim()\n })\n\n const captured = match.trimEnd()\n if (captured == '') {\n return null\n }\n\n return [match, captured]\n}\n\nfunction reactFor(outputFunc) {\n return function nestedReactOutput(\n ast: MarkdownToJSX.ParserResult | MarkdownToJSX.ParserResult[],\n state: MarkdownToJSX.State = {}\n ): React.ReactChild[] {\n if (Array.isArray(ast)) {\n const oldKey = state._key\n const result = []\n\n // map nestedOutput over the ast, except group any text\n // nodes together into a single string output.\n let lastWasString = false\n\n for (let i = 0; i < ast.length; i++) {\n state._key = i\n\n const nodeOut = nestedReactOutput(ast[i], state)\n const isString = typeof nodeOut === 'string'\n\n if (isString && lastWasString) {\n result[result.length - 1] += nodeOut\n } else if (nodeOut !== null) {\n result.push(nodeOut)\n }\n\n lastWasString = isString\n }\n\n state._key = oldKey\n\n return result\n }\n\n return outputFunc(ast, nestedReactOutput, state)\n }\n}\n\nfunction sanitizeUrl(url: string): string | null {\n try {\n const decoded = decodeURIComponent(url).replace(/[^A-Za-z0-9/:]/g, '')\n\n if (decoded.match(/^\\s*(javascript|vbscript|data(?!:image)):/i)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n 'Anchor URL contains an unsafe JavaScript/VBScript/data expression, it will not be rendered.',\n decoded\n )\n }\n\n return null\n }\n } catch (e) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n 'Anchor URL could not be decoded due to malformed syntax or characters, it will not be rendered.',\n url\n )\n }\n\n // decodeURIComponent sometimes throws a URIError\n // See `decodeURIComponent('a%AFc');`\n // http://stackoverflow.com/questions/9064536/javascript-decodeuricomponent-malformed-uri-exception\n return null\n }\n\n return url\n}\n\nfunction unescapeUrl(rawUrlString: string): string {\n return rawUrlString.replace(UNESCAPE_URL_R, '$1')\n}\n\n/**\n * Everything inline, including links.\n */\nfunction parseInline(\n parse: MarkdownToJSX.NestedParser,\n content: string,\n state: MarkdownToJSX.State\n): MarkdownToJSX.ParserResult {\n const isCurrentlyInline = state._inline || false\n const isCurrentlySimple = state._simple || false\n state._inline = true\n state._simple = true\n const result = parse(content, state)\n state._inline = isCurrentlyInline\n state._simple = isCurrentlySimple\n return result\n}\n\n/**\n * Anything inline that isn't a link.\n */\nfunction parseSimpleInline(\n parse: MarkdownToJSX.NestedParser,\n content: string,\n state: MarkdownToJSX.State\n): MarkdownToJSX.ParserResult {\n const isCurrentlyInline = state._inline || false\n const isCurrentlySimple = state._simple || false\n state._inline = false\n state._simple = true\n const result = parse(content, state)\n state._inline = isCurrentlyInline\n state._simple = isCurrentlySimple\n return result\n}\n\nfunction parseBlock(\n parse,\n content,\n state: MarkdownToJSX.State\n): MarkdownToJSX.ParserResult {\n state._inline = false\n return parse(content + '\\n\\n', state)\n}\n\nconst parseCaptureInline: MarkdownToJSX.Parser<\n ReturnType\n> = (capture, parse, state: MarkdownToJSX.State) => {\n return {\n _content: parseInline(parse, capture[1], state),\n }\n}\n\nfunction captureNothing() {\n return {}\n}\n\nfunction renderNothing() {\n return null\n}\n\nfunction ruleOutput(rules: MarkdownToJSX.Rules) {\n return function nestedRuleOutput(\n ast: MarkdownToJSX.ParserResult,\n outputFunc: MarkdownToJSX.RuleOutput,\n state: MarkdownToJSX.State\n ): React.ReactChild {\n return rules[ast.type]._react(ast, outputFunc, state)\n }\n}\n\nfunction cx(...args) {\n return args.filter(Boolean).join(' ')\n}\n\nfunction get(src: Object, path: string, fb?: any) {\n let ptr = src\n const frags = path.split('.')\n\n while (frags.length) {\n ptr = ptr[frags[0]]\n\n if (ptr === undefined) break\n else frags.shift()\n }\n\n return ptr || fb\n}\n\nfunction getTag(tag: string, overrides: MarkdownToJSX.Overrides) {\n const override = get(overrides, tag)\n\n if (!override) return tag\n\n return typeof override === 'function' ||\n (typeof override === 'object' && 'render' in override)\n ? override\n : get(overrides, `${tag}.component`, tag)\n}\n\nenum Priority {\n /**\n * anything that must scan the tree before everything else\n */\n MAX,\n /**\n * scans for block-level constructs\n */\n HIGH,\n /**\n * inline w/ more priority than other inline\n */\n MED,\n /**\n * inline elements\n */\n LOW,\n /**\n * bare text and stuff that is considered leftovers\n */\n MIN,\n}\n\nexport function compiler(\n markdown: string,\n options: MarkdownToJSX.Options = {}\n) {\n options.overrides = options.overrides || {}\n options.slugify = options.slugify || slugify\n options.namedCodesToUnicode = options.namedCodesToUnicode\n ? { ...namedCodesToUnicode, ...options.namedCodesToUnicode }\n : namedCodesToUnicode\n\n const createElementFn = options.createElement || React.createElement\n\n // JSX custom pragma\n // eslint-disable-next-line no-unused-vars\n function h(\n // locally we always will render a known string tag\n tag: MarkdownToJSX.HTMLTags,\n props: Parameters[1] & {\n className?: string\n id?: string\n },\n ...children\n ) {\n const overrideProps = get(options.overrides, `${tag}.props`, {})\n\n return createElementFn(\n getTag(tag, options.overrides),\n {\n ...props,\n ...overrideProps,\n className: cx(props?.className, overrideProps.className) || undefined,\n },\n ...children\n )\n }\n\n function compile(input: string): JSX.Element {\n let _inline = false\n\n if (options.forceInline) {\n _inline = true\n } else if (!options.forceBlock) {\n /**\n * should not contain any block-level markdown like newlines, lists, headings,\n * thematic breaks, blockquotes, tables, etc\n */\n _inline = SHOULD_RENDER_AS_BLOCK_R.test(input) === false\n }\n\n const arr = emitter(\n parser(\n _inline\n ? input\n : `${input.trimEnd().replace(TRIM_STARTING_NEWLINES, '')}\\n\\n`,\n {\n _inline,\n }\n )\n )\n\n while (\n typeof arr[arr.length - 1] === 'string' &&\n !arr[arr.length - 1].trim()\n ) {\n arr.pop()\n }\n\n if (options.wrapper === null) {\n return arr\n }\n\n const wrapper = options.wrapper || (_inline ? 'span' : 'div')\n let jsx\n\n if (arr.length > 1 || options.forceWrapper) {\n jsx = arr\n } else if (arr.length === 1) {\n jsx = arr[0]\n\n // TODO: remove this for React 16\n if (typeof jsx === 'string') {\n return {jsx}\n } else {\n return jsx\n }\n } else {\n // TODO: return null for React 16\n jsx = null\n }\n\n return React.createElement(wrapper, { key: 'outer' }, jsx)\n }\n\n function attrStringToMap(str: string): JSX.IntrinsicAttributes {\n const attributes = str.match(ATTR_EXTRACTOR_R)\n if (!attributes) {\n return null\n }\n\n return attributes.reduce(function (map, raw, index) {\n const delimiterIdx = raw.indexOf('=')\n\n if (delimiterIdx !== -1) {\n const key = normalizeAttributeKey(raw.slice(0, delimiterIdx)).trim()\n const value = unquote(raw.slice(delimiterIdx + 1).trim())\n\n const mappedKey = ATTRIBUTE_TO_JSX_PROP_MAP[key] || key\n const normalizedValue = (map[mappedKey] = attributeValueToJSXPropValue(\n key,\n value\n ))\n\n if (\n typeof normalizedValue === 'string' &&\n (HTML_BLOCK_ELEMENT_R.test(normalizedValue) ||\n HTML_SELF_CLOSING_ELEMENT_R.test(normalizedValue))\n ) {\n map[mappedKey] = React.cloneElement(compile(normalizedValue.trim()), {\n key: index,\n })\n }\n } else if (raw !== 'style') {\n map[ATTRIBUTE_TO_JSX_PROP_MAP[raw] || raw] = true\n }\n\n return map\n }, {})\n }\n\n /* istanbul ignore next */\n if (process.env.NODE_ENV !== 'production') {\n if (typeof markdown !== 'string') {\n throw new Error(`markdown-to-jsx: the first argument must be\n a string`)\n }\n\n if (\n Object.prototype.toString.call(options.overrides) !== '[object Object]'\n ) {\n throw new Error(`markdown-to-jsx: options.overrides (second argument property) must be\n undefined or an object literal with shape:\n {\n htmltagname: {\n component: string|ReactComponent(optional),\n props: object(optional)\n }\n }`)\n }\n }\n\n const footnotes: { _footnote: string; _identifier: string }[] = []\n const refs: { [key: string]: { _target: string; _title: string } } = {}\n\n /**\n * each rule's react() output function goes through our custom h() JSX pragma;\n * this allows the override functionality to be automatically applied\n */\n const rules: MarkdownToJSX.Rules = {\n blockQuote: {\n _match: blockRegex(BLOCKQUOTE_R),\n _order: Priority.HIGH,\n _parse(capture, parse, state) {\n return {\n _content: parse(\n capture[0].replace(BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, ''),\n state\n ),\n }\n },\n _react(node, output, state) {\n return (\n
    \n {output(node._content, state)}\n
    \n )\n },\n } as MarkdownToJSX.Rule<{ _content: MarkdownToJSX.ParserResult }>,\n\n breakLine: {\n _match: anyScopeRegex(BREAK_LINE_R),\n _order: Priority.HIGH,\n _parse: captureNothing,\n _react(_, __, state) {\n return
    \n },\n },\n\n breakThematic: {\n _match: blockRegex(BREAK_THEMATIC_R),\n _order: Priority.HIGH,\n _parse: captureNothing,\n _react(_, __, state) {\n return
    \n },\n },\n\n codeBlock: {\n _match: blockRegex(CODE_BLOCK_R),\n _order: Priority.MAX,\n _parse(capture /*, parse, state*/) {\n return {\n _content: capture[0].replace(/^ {4}/gm, '').replace(/\\n+$/, ''),\n _lang: undefined,\n }\n },\n\n _react(node, output, state) {\n return (\n
    \n            \n              {node._content}\n            \n          
    \n )\n },\n } as MarkdownToJSX.Rule<{\n _attrs?: ReturnType\n _content: string\n _lang?: string\n }>,\n\n codeFenced: {\n _match: blockRegex(CODE_BLOCK_FENCED_R),\n _order: Priority.MAX,\n _parse(capture /*, parse, state*/) {\n return {\n // if capture[3] it's additional metadata\n _attrs: attrStringToMap(capture[3] || ''),\n _content: capture[4],\n _lang: capture[2] || undefined,\n type: 'codeBlock',\n }\n },\n },\n\n codeInline: {\n _match: simpleInlineRegex(CODE_INLINE_R),\n _order: Priority.LOW,\n _parse(capture /*, parse, state*/) {\n return {\n _content: capture[2],\n }\n },\n _react(node, output, state) {\n return {node._content}\n },\n } as MarkdownToJSX.Rule<{ _content: string }>,\n\n /**\n * footnotes are emitted at the end of compilation in a special