| 1 | /** |
| 2 | * marked v14.1.3 - a markdown parser |
| 3 | * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) |
| 4 | * https://github.com/markedjs/marked |
| 5 | */ |
| 6 | |
| 7 | /** |
| 8 | * DO NOT EDIT THIS FILE |
| 9 | * The code in this file is generated from files in ./src/ |
| 10 | */ |
| 11 | |
| 12 | (function (global, factory) { |
| 13 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : |
| 14 | typeof define === 'function' && define.amd ? define(['exports'], factory) : |
| 15 | (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {})); |
| 16 | })(this, (function (exports) { 'use strict'; |
| 17 | |
| 18 | /** |
| 19 | * Gets the original marked default options. |
| 20 | */ |
| 21 | function _getDefaults() { |
| 22 | return { |
| 23 | async: false, |
| 24 | breaks: false, |
| 25 | extensions: null, |
| 26 | gfm: true, |
| 27 | hooks: null, |
| 28 | pedantic: false, |
| 29 | renderer: null, |
| 30 | silent: false, |
| 31 | tokenizer: null, |
| 32 | walkTokens: null, |
| 33 | }; |
| 34 | } |
| 35 | exports.defaults = _getDefaults(); |
| 36 | function changeDefaults(newDefaults) { |
| 37 | exports.defaults = newDefaults; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Helpers |
| 42 | */ |
| 43 | const escapeTest = /[&<>"']/; |
| 44 | const escapeReplace = new RegExp(escapeTest.source, 'g'); |
| 45 | const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/; |
| 46 | const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g'); |
| 47 | const escapeReplacements = { |
| 48 | '&': '&', |
| 49 | '<': '<', |
| 50 | '>': '>', |
| 51 | '"': '"', |
| 52 | "'": ''', |
| 53 | }; |
| 54 | const getEscapeReplacement = (ch) => escapeReplacements[ch]; |
| 55 | function escape$1(html, encode) { |
| 56 | if (encode) { |
| 57 | if (escapeTest.test(html)) { |
| 58 | return html.replace(escapeReplace, getEscapeReplacement); |
| 59 | } |
| 60 | } |
| 61 | else { |
| 62 | if (escapeTestNoEncode.test(html)) { |
| 63 | return html.replace(escapeReplaceNoEncode, getEscapeReplacement); |
| 64 | } |
| 65 | } |
| 66 | return html; |
| 67 | } |
| 68 | const caret = /(^|[^\[])\^/g; |
| 69 | function edit(regex, opt) { |
| 70 | let source = typeof regex === 'string' ? regex : regex.source; |
| 71 | opt = opt || ''; |
| 72 | const obj = { |
| 73 | replace: (name, val) => { |
| 74 | let valSource = typeof val === 'string' ? val : val.source; |
| 75 | valSource = valSource.replace(caret, '$1'); |
| 76 | source = source.replace(name, valSource); |
| 77 | return obj; |
| 78 | }, |
| 79 | getRegex: () => { |
| 80 | return new RegExp(source, opt); |
| 81 | }, |
| 82 | }; |
| 83 | return obj; |
| 84 | } |
| 85 | function cleanUrl(href) { |
| 86 | try { |
| 87 | href = encodeURI(href).replace(/%25/g, '%'); |
| 88 | } |
| 89 | catch { |
| 90 | return null; |
| 91 | } |
| 92 | return href; |
| 93 | } |
| 94 | const noopTest = { exec: () => null }; |
| 95 | function splitCells(tableRow, count) { |
| 96 | // ensure that every cell-delimiting pipe has a space |
| 97 | // before it to distinguish it from an escaped pipe |
| 98 | const row = tableRow.replace(/\|/g, (match, offset, str) => { |
| 99 | let escaped = false; |
| 100 | let curr = offset; |
| 101 | while (--curr >= 0 && str[curr] === '\\') |
| 102 | escaped = !escaped; |
| 103 | if (escaped) { |
| 104 | // odd number of slashes means | is escaped |
| 105 | // so we leave it alone |
| 106 | return '|'; |
| 107 | } |
| 108 | else { |
| 109 | // add space before unescaped | |
| 110 | return ' |'; |
| 111 | } |
| 112 | }), cells = row.split(/ \|/); |
| 113 | let i = 0; |
| 114 | // First/last cell in a row cannot be empty if it has no leading/trailing pipe |
| 115 | if (!cells[0].trim()) { |
| 116 | cells.shift(); |
| 117 | } |
| 118 | if (cells.length > 0 && !cells[cells.length - 1].trim()) { |
| 119 | cells.pop(); |
| 120 | } |
| 121 | if (count) { |
| 122 | if (cells.length > count) { |
| 123 | cells.splice(count); |
| 124 | } |
| 125 | else { |
| 126 | while (cells.length < count) |
| 127 | cells.push(''); |
| 128 | } |
| 129 | } |
| 130 | for (; i < cells.length; i++) { |
| 131 | // leading or trailing whitespace is ignored per the gfm spec |
| 132 | cells[i] = cells[i].trim().replace(/\\\|/g, '|'); |
| 133 | } |
| 134 | return cells; |
| 135 | } |
| 136 | /** |
| 137 | * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). |
| 138 | * /c*$/ is vulnerable to REDOS. |
| 139 | * |
| 140 | * @param str |
| 141 | * @param c |
| 142 | * @param invert Remove suffix of non-c chars instead. Default falsey. |
| 143 | */ |
| 144 | function rtrim(str, c, invert) { |
| 145 | const l = str.length; |
| 146 | if (l === 0) { |
| 147 | return ''; |
| 148 | } |
| 149 | // Length of suffix matching the invert condition. |
| 150 | let suffLen = 0; |
| 151 | // Step left until we fail to match the invert condition. |
| 152 | while (suffLen < l) { |
| 153 | const currChar = str.charAt(l - suffLen - 1); |
| 154 | if (currChar === c && !invert) { |
| 155 | suffLen++; |
| 156 | } |
| 157 | else if (currChar !== c && invert) { |
| 158 | suffLen++; |
| 159 | } |
| 160 | else { |
| 161 | break; |
| 162 | } |
| 163 | } |
| 164 | return str.slice(0, l - suffLen); |
| 165 | } |
| 166 | function findClosingBracket(str, b) { |
| 167 | if (str.indexOf(b[1]) === -1) { |
| 168 | return -1; |
| 169 | } |
| 170 | let level = 0; |
| 171 | for (let i = 0; i < str.length; i++) { |
| 172 | if (str[i] === '\\') { |
| 173 | i++; |
| 174 | } |
| 175 | else if (str[i] === b[0]) { |
| 176 | level++; |
| 177 | } |
| 178 | else if (str[i] === b[1]) { |
| 179 | level--; |
| 180 | if (level < 0) { |
| 181 | return i; |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | return -1; |
| 186 | } |
| 187 | |
| 188 | function outputLink(cap, link, raw, lexer) { |
| 189 | const href = link.href; |
| 190 | const title = link.title ? escape$1(link.title) : null; |
| 191 | const text = cap[1].replace(/\\([\[\]])/g, '$1'); |
| 192 | if (cap[0].charAt(0) !== '!') { |
| 193 | lexer.state.inLink = true; |
| 194 | const token = { |
| 195 | type: 'link', |
| 196 | raw, |
| 197 | href, |
| 198 | title, |
| 199 | text, |
| 200 | tokens: lexer.inlineTokens(text), |
| 201 | }; |
| 202 | lexer.state.inLink = false; |
| 203 | return token; |
| 204 | } |
| 205 | return { |
| 206 | type: 'image', |
| 207 | raw, |
| 208 | href, |
| 209 | title, |
| 210 | text: escape$1(text), |
| 211 | }; |
| 212 | } |
| 213 | function indentCodeCompensation(raw, text) { |
| 214 | const matchIndentToCode = raw.match(/^(\s+)(?:```)/); |
| 215 | if (matchIndentToCode === null) { |
| 216 | return text; |
| 217 | } |
| 218 | const indentToCode = matchIndentToCode[1]; |
| 219 | return text |
| 220 | .split('\n') |
| 221 | .map(node => { |
| 222 | const matchIndentInNode = node.match(/^\s+/); |
| 223 | if (matchIndentInNode === null) { |
| 224 | return node; |
| 225 | } |
| 226 | const [indentInNode] = matchIndentInNode; |
| 227 | if (indentInNode.length >= indentToCode.length) { |
| 228 | return node.slice(indentToCode.length); |
| 229 | } |
| 230 | return node; |
| 231 | }) |
| 232 | .join('\n'); |
| 233 | } |
| 234 | /** |
| 235 | * Tokenizer |
| 236 | */ |
| 237 | class _Tokenizer { |
| 238 | options; |
| 239 | rules; // set by the lexer |
| 240 | lexer; // set by the lexer |
| 241 | constructor(options) { |
| 242 | this.options = options || exports.defaults; |
| 243 | } |
| 244 | space(src) { |
| 245 | const cap = this.rules.block.newline.exec(src); |
| 246 | if (cap && cap[0].length > 0) { |
| 247 | return { |
| 248 | type: 'space', |
| 249 | raw: cap[0], |
| 250 | }; |
| 251 | } |
| 252 | } |
| 253 | code(src) { |
| 254 | const cap = this.rules.block.code.exec(src); |
| 255 | if (cap) { |
| 256 | const text = cap[0].replace(/^(?: {1,4}| {0,3}\t)/gm, ''); |
| 257 | return { |
| 258 | type: 'code', |
| 259 | raw: cap[0], |
| 260 | codeBlockStyle: 'indented', |
| 261 | text: !this.options.pedantic |
| 262 | ? rtrim(text, '\n') |
| 263 | : text, |
| 264 | }; |
| 265 | } |
| 266 | } |
| 267 | fences(src) { |
| 268 | const cap = this.rules.block.fences.exec(src); |
| 269 | if (cap) { |
| 270 | const raw = cap[0]; |
| 271 | const text = indentCodeCompensation(raw, cap[3] || ''); |
| 272 | return { |
| 273 | type: 'code', |
| 274 | raw, |
| 275 | lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2], |
| 276 | text, |
| 277 | }; |
| 278 | } |
| 279 | } |
| 280 | heading(src) { |
| 281 | const cap = this.rules.block.heading.exec(src); |
| 282 | if (cap) { |
| 283 | let text = cap[2].trim(); |
| 284 | // remove trailing #s |
| 285 | if (/#$/.test(text)) { |
| 286 | const trimmed = rtrim(text, '#'); |
| 287 | if (this.options.pedantic) { |
| 288 | text = trimmed.trim(); |
| 289 | } |
| 290 | else if (!trimmed || / $/.test(trimmed)) { |
| 291 | // CommonMark requires space before trailing #s |
| 292 | text = trimmed.trim(); |
| 293 | } |
| 294 | } |
| 295 | return { |
| 296 | type: 'heading', |
| 297 | raw: cap[0], |
| 298 | depth: cap[1].length, |
| 299 | text, |
| 300 | tokens: this.lexer.inline(text), |
| 301 | }; |
| 302 | } |
| 303 | } |
| 304 | hr(src) { |
| 305 | const cap = this.rules.block.hr.exec(src); |
| 306 | if (cap) { |
| 307 | return { |
| 308 | type: 'hr', |
| 309 | raw: rtrim(cap[0], '\n'), |
| 310 | }; |
| 311 | } |
| 312 | } |
| 313 | blockquote(src) { |
| 314 | const cap = this.rules.block.blockquote.exec(src); |
| 315 | if (cap) { |
| 316 | let lines = rtrim(cap[0], '\n').split('\n'); |
| 317 | let raw = ''; |
| 318 | let text = ''; |
| 319 | const tokens = []; |
| 320 | while (lines.length > 0) { |
| 321 | let inBlockquote = false; |
| 322 | const currentLines = []; |
| 323 | let i; |
| 324 | for (i = 0; i < lines.length; i++) { |
| 325 | // get lines up to a continuation |
| 326 | if (/^ {0,3}>/.test(lines[i])) { |
| 327 | currentLines.push(lines[i]); |
| 328 | inBlockquote = true; |
| 329 | } |
| 330 | else if (!inBlockquote) { |
| 331 | currentLines.push(lines[i]); |
| 332 | } |
| 333 | else { |
| 334 | break; |
| 335 | } |
| 336 | } |
| 337 | lines = lines.slice(i); |
| 338 | const currentRaw = currentLines.join('\n'); |
| 339 | const currentText = currentRaw |
| 340 | // precede setext continuation with 4 spaces so it isn't a setext |
| 341 | .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n $1') |
| 342 | .replace(/^ {0,3}>[ \t]?/gm, ''); |
| 343 | raw = raw ? `${raw}\n${currentRaw}` : currentRaw; |
| 344 | text = text ? `${text}\n${currentText}` : currentText; |
| 345 | // parse blockquote lines as top level tokens |
| 346 | // merge paragraphs if this is a continuation |
| 347 | const top = this.lexer.state.top; |
| 348 | this.lexer.state.top = true; |
| 349 | this.lexer.blockTokens(currentText, tokens, true); |
| 350 | this.lexer.state.top = top; |
| 351 | // if there is no continuation then we are done |
| 352 | if (lines.length === 0) { |
| 353 | break; |
| 354 | } |
| 355 | const lastToken = tokens[tokens.length - 1]; |
| 356 | if (lastToken?.type === 'code') { |
| 357 | // blockquote continuation cannot be preceded by a code block |
| 358 | break; |
| 359 | } |
| 360 | else if (lastToken?.type === 'blockquote') { |
| 361 | // include continuation in nested blockquote |
| 362 | const oldToken = lastToken; |
| 363 | const newText = oldToken.raw + '\n' + lines.join('\n'); |
| 364 | const newToken = this.blockquote(newText); |
| 365 | tokens[tokens.length - 1] = newToken; |
| 366 | raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; |
| 367 | text = text.substring(0, text.length - oldToken.text.length) + newToken.text; |
| 368 | break; |
| 369 | } |
| 370 | else if (lastToken?.type === 'list') { |
| 371 | // include continuation in nested list |
| 372 | const oldToken = lastToken; |
| 373 | const newText = oldToken.raw + '\n' + lines.join('\n'); |
| 374 | const newToken = this.list(newText); |
| 375 | tokens[tokens.length - 1] = newToken; |
| 376 | raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; |
| 377 | text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw; |
| 378 | lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n'); |
| 379 | continue; |
| 380 | } |
| 381 | } |
| 382 | return { |
| 383 | type: 'blockquote', |
| 384 | raw, |
| 385 | tokens, |
| 386 | text, |
| 387 | }; |
| 388 | } |
| 389 | } |
| 390 | list(src) { |
| 391 | let cap = this.rules.block.list.exec(src); |
| 392 | if (cap) { |
| 393 | let bull = cap[1].trim(); |
| 394 | const isordered = bull.length > 1; |
| 395 | const list = { |
| 396 | type: 'list', |
| 397 | raw: '', |
| 398 | ordered: isordered, |
| 399 | start: isordered ? +bull.slice(0, -1) : '', |
| 400 | loose: false, |
| 401 | items: [], |
| 402 | }; |
| 403 | bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; |
| 404 | if (this.options.pedantic) { |
| 405 | bull = isordered ? bull : '[*+-]'; |
| 406 | } |
| 407 | // Get next list item |
| 408 | const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`); |
| 409 | let endsWithBlankLine = false; |
| 410 | // Check if current bullet point can start a new List Item |
| 411 | while (src) { |
| 412 | let endEarly = false; |
| 413 | let raw = ''; |
| 414 | let itemContents = ''; |
| 415 | if (!(cap = itemRegex.exec(src))) { |
| 416 | break; |
| 417 | } |
| 418 | if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?) |
| 419 | break; |
| 420 | } |
| 421 | raw = cap[0]; |
| 422 | src = src.substring(raw.length); |
| 423 | let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length)); |
| 424 | let nextLine = src.split('\n', 1)[0]; |
| 425 | let blankLine = !line.trim(); |
| 426 | let indent = 0; |
| 427 | if (this.options.pedantic) { |
| 428 | indent = 2; |
| 429 | itemContents = line.trimStart(); |
| 430 | } |
| 431 | else if (blankLine) { |
| 432 | indent = cap[1].length + 1; |
| 433 | } |
| 434 | else { |
| 435 | indent = cap[2].search(/[^ ]/); // Find first non-space char |
| 436 | indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent |
| 437 | itemContents = line.slice(indent); |
| 438 | indent += cap[1].length; |
| 439 | } |
| 440 | if (blankLine && /^[ \t]*$/.test(nextLine)) { // Items begin with at most one blank line |
| 441 | raw += nextLine + '\n'; |
| 442 | src = src.substring(nextLine.length + 1); |
| 443 | endEarly = true; |
| 444 | } |
| 445 | if (!endEarly) { |
| 446 | const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`); |
| 447 | const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`); |
| 448 | const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`); |
| 449 | const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`); |
| 450 | const htmlBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}<[a-z].*>`, 'i'); |
| 451 | // Check if following lines should be included in List Item |
| 452 | while (src) { |
| 453 | const rawLine = src.split('\n', 1)[0]; |
| 454 | let nextLineWithoutTabs; |
| 455 | nextLine = rawLine; |
| 456 | // Re-align to follow commonmark nesting rules |
| 457 | if (this.options.pedantic) { |
| 458 | nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' '); |
| 459 | nextLineWithoutTabs = nextLine; |
| 460 | } |
| 461 | else { |
| 462 | nextLineWithoutTabs = nextLine.replace(/\t/g, ' '); |
| 463 | } |
| 464 | // End list item if found code fences |
| 465 | if (fencesBeginRegex.test(nextLine)) { |
| 466 | break; |
| 467 | } |
| 468 | // End list item if found start of new heading |
| 469 | if (headingBeginRegex.test(nextLine)) { |
| 470 | break; |
| 471 | } |
| 472 | // End list item if found start of html block |
| 473 | if (htmlBeginRegex.test(nextLine)) { |
| 474 | break; |
| 475 | } |
| 476 | // End list item if found start of new bullet |
| 477 | if (nextBulletRegex.test(nextLine)) { |
| 478 | break; |
| 479 | } |
| 480 | // Horizontal rule found |
| 481 | if (hrRegex.test(nextLine)) { |
| 482 | break; |
| 483 | } |
| 484 | if (nextLineWithoutTabs.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible |
| 485 | itemContents += '\n' + nextLineWithoutTabs.slice(indent); |
| 486 | } |
| 487 | else { |
| 488 | // not enough indentation |
| 489 | if (blankLine) { |
| 490 | break; |
| 491 | } |
| 492 | // paragraph continuation unless last line was a different block level element |
| 493 | if (line.replace(/\t/g, ' ').search(/[^ ]/) >= 4) { // indented code block |
| 494 | break; |
| 495 | } |
| 496 | if (fencesBeginRegex.test(line)) { |
| 497 | break; |
| 498 | } |
| 499 | if (headingBeginRegex.test(line)) { |
| 500 | break; |
| 501 | } |
| 502 | if (hrRegex.test(line)) { |
| 503 | break; |
| 504 | } |
| 505 | itemContents += '\n' + nextLine; |
| 506 | } |
| 507 | if (!blankLine && !nextLine.trim()) { // Check if current line is blank |
| 508 | blankLine = true; |
| 509 | } |
| 510 | raw += rawLine + '\n'; |
| 511 | src = src.substring(rawLine.length + 1); |
| 512 | line = nextLineWithoutTabs.slice(indent); |
| 513 | } |
| 514 | } |
| 515 | if (!list.loose) { |
| 516 | // If the previous item ended with a blank line, the list is loose |
| 517 | if (endsWithBlankLine) { |
| 518 | list.loose = true; |
| 519 | } |
| 520 | else if (/\n[ \t]*\n[ \t]*$/.test(raw)) { |
| 521 | endsWithBlankLine = true; |
| 522 | } |
| 523 | } |
| 524 | let istask = null; |
| 525 | let ischecked; |
| 526 | // Check for task list items |
| 527 | if (this.options.gfm) { |
| 528 | istask = /^\[[ xX]\] /.exec(itemContents); |
| 529 | if (istask) { |
| 530 | ischecked = istask[0] !== '[ ] '; |
| 531 | itemContents = itemContents.replace(/^\[[ xX]\] +/, ''); |
| 532 | } |
| 533 | } |
| 534 | list.items.push({ |
| 535 | type: 'list_item', |
| 536 | raw, |
| 537 | task: !!istask, |
| 538 | checked: ischecked, |
| 539 | loose: false, |
| 540 | text: itemContents, |
| 541 | tokens: [], |
| 542 | }); |
| 543 | list.raw += raw; |
| 544 | } |
| 545 | // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic |
| 546 | list.items[list.items.length - 1].raw = list.items[list.items.length - 1].raw.trimEnd(); |
| 547 | list.items[list.items.length - 1].text = list.items[list.items.length - 1].text.trimEnd(); |
| 548 | list.raw = list.raw.trimEnd(); |
| 549 | // Item child tokens handled here at end because we needed to have the final item to trim it first |
| 550 | for (let i = 0; i < list.items.length; i++) { |
| 551 | this.lexer.state.top = false; |
| 552 | list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); |
| 553 | if (!list.loose) { |
| 554 | // Check if list should be loose |
| 555 | const spacers = list.items[i].tokens.filter(t => t.type === 'space'); |
| 556 | const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw)); |
| 557 | list.loose = hasMultipleLineBreaks; |
| 558 | } |
| 559 | } |
| 560 | // Set all items to loose if list is loose |
| 561 | if (list.loose) { |
| 562 | for (let i = 0; i < list.items.length; i++) { |
| 563 | list.items[i].loose = true; |
| 564 | } |
| 565 | } |
| 566 | return list; |
| 567 | } |
| 568 | } |
| 569 | html(src) { |
| 570 | const cap = this.rules.block.html.exec(src); |
| 571 | if (cap) { |
| 572 | const token = { |
| 573 | type: 'html', |
| 574 | block: true, |
| 575 | raw: cap[0], |
| 576 | pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', |
| 577 | text: cap[0], |
| 578 | }; |
| 579 | return token; |
| 580 | } |
| 581 | } |
| 582 | def(src) { |
| 583 | const cap = this.rules.block.def.exec(src); |
| 584 | if (cap) { |
| 585 | const tag = cap[1].toLowerCase().replace(/\s+/g, ' '); |
| 586 | const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : ''; |
| 587 | const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3]; |
| 588 | return { |
| 589 | type: 'def', |
| 590 | tag, |
| 591 | raw: cap[0], |
| 592 | href, |
| 593 | title, |
| 594 | }; |
| 595 | } |
| 596 | } |
| 597 | table(src) { |
| 598 | const cap = this.rules.block.table.exec(src); |
| 599 | if (!cap) { |
| 600 | return; |
| 601 | } |
| 602 | if (!/[:|]/.test(cap[2])) { |
| 603 | // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading |
| 604 | return; |
| 605 | } |
| 606 | const headers = splitCells(cap[1]); |
| 607 | const aligns = cap[2].replace(/^\||\| *$/g, '').split('|'); |
| 608 | const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []; |
| 609 | const item = { |
| 610 | type: 'table', |
| 611 | raw: cap[0], |
| 612 | header: [], |
| 613 | align: [], |
| 614 | rows: [], |
| 615 | }; |
| 616 | if (headers.length !== aligns.length) { |
| 617 | // header and align columns must be equal, rows can be different. |
| 618 | return; |
| 619 | } |
| 620 | for (const align of aligns) { |
| 621 | if (/^ *-+: *$/.test(align)) { |
| 622 | item.align.push('right'); |
| 623 | } |
| 624 | else if (/^ *:-+: *$/.test(align)) { |
| 625 | item.align.push('center'); |
| 626 | } |
| 627 | else if (/^ *:-+ *$/.test(align)) { |
| 628 | item.align.push('left'); |
| 629 | } |
| 630 | else { |
| 631 | item.align.push(null); |
| 632 | } |
| 633 | } |
| 634 | for (let i = 0; i < headers.length; i++) { |
| 635 | item.header.push({ |
| 636 | text: headers[i], |
| 637 | tokens: this.lexer.inline(headers[i]), |
| 638 | header: true, |
| 639 | align: item.align[i], |
| 640 | }); |
| 641 | } |
| 642 | for (const row of rows) { |
| 643 | item.rows.push(splitCells(row, item.header.length).map((cell, i) => { |
| 644 | return { |
| 645 | text: cell, |
| 646 | tokens: this.lexer.inline(cell), |
| 647 | header: false, |
| 648 | align: item.align[i], |
| 649 | }; |
| 650 | })); |
| 651 | } |
| 652 | return item; |
| 653 | } |
| 654 | lheading(src) { |
| 655 | const cap = this.rules.block.lheading.exec(src); |
| 656 | if (cap) { |
| 657 | return { |
| 658 | type: 'heading', |
| 659 | raw: cap[0], |
| 660 | depth: cap[2].charAt(0) === '=' ? 1 : 2, |
| 661 | text: cap[1], |
| 662 | tokens: this.lexer.inline(cap[1]), |
| 663 | }; |
| 664 | } |
| 665 | } |
| 666 | paragraph(src) { |
| 667 | const cap = this.rules.block.paragraph.exec(src); |
| 668 | if (cap) { |
| 669 | const text = cap[1].charAt(cap[1].length - 1) === '\n' |
| 670 | ? cap[1].slice(0, -1) |
| 671 | : cap[1]; |
| 672 | return { |
| 673 | type: 'paragraph', |
| 674 | raw: cap[0], |
| 675 | text, |
| 676 | tokens: this.lexer.inline(text), |
| 677 | }; |
| 678 | } |
| 679 | } |
| 680 | text(src) { |
| 681 | const cap = this.rules.block.text.exec(src); |
| 682 | if (cap) { |
| 683 | return { |
| 684 | type: 'text', |
| 685 | raw: cap[0], |
| 686 | text: cap[0], |
| 687 | tokens: this.lexer.inline(cap[0]), |
| 688 | }; |
| 689 | } |
| 690 | } |
| 691 | escape(src) { |
| 692 | const cap = this.rules.inline.escape.exec(src); |
| 693 | if (cap) { |
| 694 | return { |
| 695 | type: 'escape', |
| 696 | raw: cap[0], |
| 697 | text: escape$1(cap[1]), |
| 698 | }; |
| 699 | } |
| 700 | } |
| 701 | tag(src) { |
| 702 | const cap = this.rules.inline.tag.exec(src); |
| 703 | if (cap) { |
| 704 | if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) { |
| 705 | this.lexer.state.inLink = true; |
| 706 | } |
| 707 | else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) { |
| 708 | this.lexer.state.inLink = false; |
| 709 | } |
| 710 | if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { |
| 711 | this.lexer.state.inRawBlock = true; |
| 712 | } |
| 713 | else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { |
| 714 | this.lexer.state.inRawBlock = false; |
| 715 | } |
| 716 | return { |
| 717 | type: 'html', |
| 718 | raw: cap[0], |
| 719 | inLink: this.lexer.state.inLink, |
| 720 | inRawBlock: this.lexer.state.inRawBlock, |
| 721 | block: false, |
| 722 | text: cap[0], |
| 723 | }; |
| 724 | } |
| 725 | } |
| 726 | link(src) { |
| 727 | const cap = this.rules.inline.link.exec(src); |
| 728 | if (cap) { |
| 729 | const trimmedUrl = cap[2].trim(); |
| 730 | if (!this.options.pedantic && /^</.test(trimmedUrl)) { |
| 731 | // commonmark requires matching angle brackets |
| 732 | if (!(/>$/.test(trimmedUrl))) { |
| 733 | return; |
| 734 | } |
| 735 | // ending angle bracket cannot be escaped |
| 736 | const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); |
| 737 | if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { |
| 738 | return; |
| 739 | } |
| 740 | } |
| 741 | else { |
| 742 | // find closing parenthesis |
| 743 | const lastParenIndex = findClosingBracket(cap[2], '()'); |
| 744 | if (lastParenIndex > -1) { |
| 745 | const start = cap[0].indexOf('!') === 0 ? 5 : 4; |
| 746 | const linkLen = start + cap[1].length + lastParenIndex; |
| 747 | cap[2] = cap[2].substring(0, lastParenIndex); |
| 748 | cap[0] = cap[0].substring(0, linkLen).trim(); |
| 749 | cap[3] = ''; |
| 750 | } |
| 751 | } |
| 752 | let href = cap[2]; |
| 753 | let title = ''; |
| 754 | if (this.options.pedantic) { |
| 755 | // split pedantic href and title |
| 756 | const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); |
| 757 | if (link) { |
| 758 | href = link[1]; |
| 759 | title = link[3]; |
| 760 | } |
| 761 | } |
| 762 | else { |
| 763 | title = cap[3] ? cap[3].slice(1, -1) : ''; |
| 764 | } |
| 765 | href = href.trim(); |
| 766 | if (/^</.test(href)) { |
| 767 | if (this.options.pedantic && !(/>$/.test(trimmedUrl))) { |
| 768 | // pedantic allows starting angle bracket without ending angle bracket |
| 769 | href = href.slice(1); |
| 770 | } |
| 771 | else { |
| 772 | href = href.slice(1, -1); |
| 773 | } |
| 774 | } |
| 775 | return outputLink(cap, { |
| 776 | href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href, |
| 777 | title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title, |
| 778 | }, cap[0], this.lexer); |
| 779 | } |
| 780 | } |
| 781 | reflink(src, links) { |
| 782 | let cap; |
| 783 | if ((cap = this.rules.inline.reflink.exec(src)) |
| 784 | || (cap = this.rules.inline.nolink.exec(src))) { |
| 785 | const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' '); |
| 786 | const link = links[linkString.toLowerCase()]; |
| 787 | if (!link) { |
| 788 | const text = cap[0].charAt(0); |
| 789 | return { |
| 790 | type: 'text', |
| 791 | raw: text, |
| 792 | text, |
| 793 | }; |
| 794 | } |
| 795 | return outputLink(cap, link, cap[0], this.lexer); |
| 796 | } |
| 797 | } |
| 798 | emStrong(src, maskedSrc, prevChar = '') { |
| 799 | let match = this.rules.inline.emStrongLDelim.exec(src); |
| 800 | if (!match) |
| 801 | return; |
| 802 | // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well |
| 803 | if (match[3] && prevChar.match(/[\p{L}\p{N}]/u)) |
| 804 | return; |
| 805 | const nextChar = match[1] || match[2] || ''; |
| 806 | if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { |
| 807 | // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below) |
| 808 | const lLength = [...match[0]].length - 1; |
| 809 | let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; |
| 810 | const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; |
| 811 | endReg.lastIndex = 0; |
| 812 | // Clip maskedSrc to same section of string as src (move to lexer?) |
| 813 | maskedSrc = maskedSrc.slice(-1 * src.length + lLength); |
| 814 | while ((match = endReg.exec(maskedSrc)) != null) { |
| 815 | rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; |
| 816 | if (!rDelim) |
| 817 | continue; // skip single * in __abc*abc__ |
| 818 | rLength = [...rDelim].length; |
| 819 | if (match[3] || match[4]) { // found another Left Delim |
| 820 | delimTotal += rLength; |
| 821 | continue; |
| 822 | } |
| 823 | else if (match[5] || match[6]) { // either Left or Right Delim |
| 824 | if (lLength % 3 && !((lLength + rLength) % 3)) { |
| 825 | midDelimTotal += rLength; |
| 826 | continue; // CommonMark Emphasis Rules 9-10 |
| 827 | } |
| 828 | } |
| 829 | delimTotal -= rLength; |
| 830 | if (delimTotal > 0) |
| 831 | continue; // Haven't found enough closing delimiters |
| 832 | // Remove extra characters. *a*** -> *a* |
| 833 | rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); |
| 834 | // char length can be >1 for unicode characters; |
| 835 | const lastCharLength = [...match[0]][0].length; |
| 836 | const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); |
| 837 | // Create `em` if smallest delimiter has odd char count. *a*** |
| 838 | if (Math.min(lLength, rLength) % 2) { |
| 839 | const text = raw.slice(1, -1); |
| 840 | return { |
| 841 | type: 'em', |
| 842 | raw, |
| 843 | text, |
| 844 | tokens: this.lexer.inlineTokens(text), |
| 845 | }; |
| 846 | } |
| 847 | // Create 'strong' if smallest delimiter has even char count. **a*** |
| 848 | const text = raw.slice(2, -2); |
| 849 | return { |
| 850 | type: 'strong', |
| 851 | raw, |
| 852 | text, |
| 853 | tokens: this.lexer.inlineTokens(text), |
| 854 | }; |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | codespan(src) { |
| 859 | const cap = this.rules.inline.code.exec(src); |
| 860 | if (cap) { |
| 861 | let text = cap[2].replace(/\n/g, ' '); |
| 862 | const hasNonSpaceChars = /[^ ]/.test(text); |
| 863 | const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); |
| 864 | if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { |
| 865 | text = text.substring(1, text.length - 1); |
| 866 | } |
| 867 | text = escape$1(text, true); |
| 868 | return { |
| 869 | type: 'codespan', |
| 870 | raw: cap[0], |
| 871 | text, |
| 872 | }; |
| 873 | } |
| 874 | } |
| 875 | br(src) { |
| 876 | const cap = this.rules.inline.br.exec(src); |
| 877 | if (cap) { |
| 878 | return { |
| 879 | type: 'br', |
| 880 | raw: cap[0], |
| 881 | }; |
| 882 | } |
| 883 | } |
| 884 | del(src) { |
| 885 | const cap = this.rules.inline.del.exec(src); |
| 886 | if (cap) { |
| 887 | return { |
| 888 | type: 'del', |
| 889 | raw: cap[0], |
| 890 | text: cap[2], |
| 891 | tokens: this.lexer.inlineTokens(cap[2]), |
| 892 | }; |
| 893 | } |
| 894 | } |
| 895 | autolink(src) { |
| 896 | const cap = this.rules.inline.autolink.exec(src); |
| 897 | if (cap) { |
| 898 | let text, href; |
| 899 | if (cap[2] === '@') { |
| 900 | text = escape$1(cap[1]); |
| 901 | href = 'mailto:' + text; |
| 902 | } |
| 903 | else { |
| 904 | text = escape$1(cap[1]); |
| 905 | href = text; |
| 906 | } |
| 907 | return { |
| 908 | type: 'link', |
| 909 | raw: cap[0], |
| 910 | text, |
| 911 | href, |
| 912 | tokens: [ |
| 913 | { |
| 914 | type: 'text', |
| 915 | raw: text, |
| 916 | text, |
| 917 | }, |
| 918 | ], |
| 919 | }; |
| 920 | } |
| 921 | } |
| 922 | url(src) { |
| 923 | let cap; |
| 924 | if (cap = this.rules.inline.url.exec(src)) { |
| 925 | let text, href; |
| 926 | if (cap[2] === '@') { |
| 927 | text = escape$1(cap[0]); |
| 928 | href = 'mailto:' + text; |
| 929 | } |
| 930 | else { |
| 931 | // do extended autolink path validation |
| 932 | let prevCapZero; |
| 933 | do { |
| 934 | prevCapZero = cap[0]; |
| 935 | cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ''; |
| 936 | } while (prevCapZero !== cap[0]); |
| 937 | text = escape$1(cap[0]); |
| 938 | if (cap[1] === 'www.') { |
| 939 | href = 'http://' + cap[0]; |
| 940 | } |
| 941 | else { |
| 942 | href = cap[0]; |
| 943 | } |
| 944 | } |
| 945 | return { |
| 946 | type: 'link', |
| 947 | raw: cap[0], |
| 948 | text, |
| 949 | href, |
| 950 | tokens: [ |
| 951 | { |
| 952 | type: 'text', |
| 953 | raw: text, |
| 954 | text, |
| 955 | }, |
| 956 | ], |
| 957 | }; |
| 958 | } |
| 959 | } |
| 960 | inlineText(src) { |
| 961 | const cap = this.rules.inline.text.exec(src); |
| 962 | if (cap) { |
| 963 | let text; |
| 964 | if (this.lexer.state.inRawBlock) { |
| 965 | text = cap[0]; |
| 966 | } |
| 967 | else { |
| 968 | text = escape$1(cap[0]); |
| 969 | } |
| 970 | return { |
| 971 | type: 'text', |
| 972 | raw: cap[0], |
| 973 | text, |
| 974 | }; |
| 975 | } |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | /** |
| 980 | * Block-Level Grammar |
| 981 | */ |
| 982 | const newline = /^(?:[ \t]*(?:\n|$))+/; |
| 983 | const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; |
| 984 | const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; |
| 985 | const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; |
| 986 | const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; |
| 987 | const bullet = /(?:[*+-]|\d{1,9}[.)])/; |
| 988 | const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/) |
| 989 | .replace(/bull/g, bullet) // lists can interrupt |
| 990 | .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt |
| 991 | .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt |
| 992 | .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt |
| 993 | .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt |
| 994 | .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt |
| 995 | .getRegex(); |
| 996 | const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; |
| 997 | const blockText = /^[^\n]+/; |
| 998 | const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; |
| 999 | const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/) |
| 1000 | .replace('label', _blockLabel) |
| 1001 | .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/) |
| 1002 | .getRegex(); |
| 1003 | const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/) |
| 1004 | .replace(/bull/g, bullet) |
| 1005 | .getRegex(); |
| 1006 | const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' |
| 1007 | + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' |
| 1008 | + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' |
| 1009 | + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' |
| 1010 | + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' |
| 1011 | + '|tr|track|ul'; |
| 1012 | const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/; |
| 1013 | const html = edit('^ {0,3}(?:' // optional indentation |
| 1014 | + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1) |
| 1015 | + '|comment[^\\n]*(\\n+|$)' // (2) |
| 1016 | + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) |
| 1017 | + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4) |
| 1018 | + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5) |
| 1019 | + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6) |
| 1020 | + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag |
| 1021 | + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag |
| 1022 | + ')', 'i') |
| 1023 | .replace('comment', _comment) |
| 1024 | .replace('tag', _tag) |
| 1025 | .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) |
| 1026 | .getRegex(); |
| 1027 | const paragraph = edit(_paragraph) |
| 1028 | .replace('hr', hr) |
| 1029 | .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') |
| 1030 | .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs |
| 1031 | .replace('|table', '') |
| 1032 | .replace('blockquote', ' {0,3}>') |
| 1033 | .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') |
| 1034 | .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt |
| 1035 | .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)') |
| 1036 | .replace('tag', _tag) // pars can be interrupted by type (6) html blocks |
| 1037 | .getRegex(); |
| 1038 | const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/) |
| 1039 | .replace('paragraph', paragraph) |
| 1040 | .getRegex(); |
| 1041 | /** |
| 1042 | * Normal Block Grammar |
| 1043 | */ |
| 1044 | const blockNormal = { |
| 1045 | blockquote, |
| 1046 | code: blockCode, |
| 1047 | def, |
| 1048 | fences, |
| 1049 | heading, |
| 1050 | hr, |
| 1051 | html, |
| 1052 | lheading, |
| 1053 | list, |
| 1054 | newline, |
| 1055 | paragraph, |
| 1056 | table: noopTest, |
| 1057 | text: blockText, |
| 1058 | }; |
| 1059 | /** |
| 1060 | * GFM Block Grammar |
| 1061 | */ |
| 1062 | const gfmTable = edit('^ *([^\\n ].*)\\n' // Header |
| 1063 | + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align |
| 1064 | + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells |
| 1065 | .replace('hr', hr) |
| 1066 | .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') |
| 1067 | .replace('blockquote', ' {0,3}>') |
| 1068 | .replace('code', '(?: {4}| {0,3}\t)[^\\n]') |
| 1069 | .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') |
| 1070 | .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt |
| 1071 | .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)') |
| 1072 | .replace('tag', _tag) // tables can be interrupted by type (6) html blocks |
| 1073 | .getRegex(); |
| 1074 | const blockGfm = { |
| 1075 | ...blockNormal, |
| 1076 | table: gfmTable, |
| 1077 | paragraph: edit(_paragraph) |
| 1078 | .replace('hr', hr) |
| 1079 | .replace('heading', ' {0,3}#{1,6}(?:\\s|$)') |
| 1080 | .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs |
| 1081 | .replace('table', gfmTable) // interrupt paragraphs with table |
| 1082 | .replace('blockquote', ' {0,3}>') |
| 1083 | .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') |
| 1084 | .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt |
| 1085 | .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)') |
| 1086 | .replace('tag', _tag) // pars can be interrupted by type (6) html blocks |
| 1087 | .getRegex(), |
| 1088 | }; |
| 1089 | /** |
| 1090 | * Pedantic grammar (original John Gruber's loose markdown specification) |
| 1091 | */ |
| 1092 | const blockPedantic = { |
| 1093 | ...blockNormal, |
| 1094 | html: edit('^ *(?:comment *(?:\\n|\\s*$)' |
| 1095 | + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag |
| 1096 | + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') |
| 1097 | .replace('comment', _comment) |
| 1098 | .replace(/tag/g, '(?!(?:' |
| 1099 | + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' |
| 1100 | + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' |
| 1101 | + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') |
| 1102 | .getRegex(), |
| 1103 | def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, |
| 1104 | heading: /^(#{1,6})(.*)(?:\n+|$)/, |
| 1105 | fences: noopTest, // fences not supported |
| 1106 | lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, |
| 1107 | paragraph: edit(_paragraph) |
| 1108 | .replace('hr', hr) |
| 1109 | .replace('heading', ' *#{1,6} *[^\n]') |
| 1110 | .replace('lheading', lheading) |
| 1111 | .replace('|table', '') |
| 1112 | .replace('blockquote', ' {0,3}>') |
| 1113 | .replace('|fences', '') |
| 1114 | .replace('|list', '') |
| 1115 | .replace('|html', '') |
| 1116 | .replace('|tag', '') |
| 1117 | .getRegex(), |
| 1118 | }; |
| 1119 | /** |
| 1120 | * Inline-Level Grammar |
| 1121 | */ |
| 1122 | const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; |
| 1123 | const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; |
| 1124 | const br = /^( {2,}|\\)\n(?!\s*$)/; |
| 1125 | const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/; |
| 1126 | // list of unicode punctuation marks, plus any missing characters from CommonMark spec |
| 1127 | const _punctuation = '\\p{P}\\p{S}'; |
| 1128 | const punctuation = edit(/^((?![*_])[\spunctuation])/, 'u') |
| 1129 | .replace(/punctuation/g, _punctuation).getRegex(); |
| 1130 | // sequences em should skip over [title](link), `code`, <html> |
| 1131 | const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g; |
| 1132 | const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u') |
| 1133 | .replace(/punct/g, _punctuation) |
| 1134 | .getRegex(); |
| 1135 | const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong |
| 1136 | + '|[^*]+(?=[^*])' // Consume to delim |
| 1137 | + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter |
| 1138 | + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter |
| 1139 | + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter |
| 1140 | + '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter |
| 1141 | + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter |
| 1142 | + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter |
| 1143 | .replace(/punct/g, _punctuation) |
| 1144 | .getRegex(); |
| 1145 | // (6) Not allowed for _ |
| 1146 | const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong |
| 1147 | + '|[^_]+(?=[^_])' // Consume to delim |
| 1148 | + '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter |
| 1149 | + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter |
| 1150 | + '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter |
| 1151 | + '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter |
| 1152 | + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter |
| 1153 | .replace(/punct/g, _punctuation) |
| 1154 | .getRegex(); |
| 1155 | const anyPunctuation = edit(/\\([punct])/, 'gu') |
| 1156 | .replace(/punct/g, _punctuation) |
| 1157 | .getRegex(); |
| 1158 | const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/) |
| 1159 | .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/) |
| 1160 | .replace('email', /[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])?)+(?![-_])/) |
| 1161 | .getRegex(); |
| 1162 | const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex(); |
| 1163 | const tag = edit('^comment' |
| 1164 | + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag |
| 1165 | + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag |
| 1166 | + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?> |
| 1167 | + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html> |
| 1168 | + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>') // CDATA section |
| 1169 | .replace('comment', _inlineComment) |
| 1170 | .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/) |
| 1171 | .getRegex(); |
| 1172 | const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; |
| 1173 | const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/) |
| 1174 | .replace('label', _inlineLabel) |
| 1175 | .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/) |
| 1176 | .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/) |
| 1177 | .getRegex(); |
| 1178 | const reflink = edit(/^!?\[(label)\]\[(ref)\]/) |
| 1179 | .replace('label', _inlineLabel) |
| 1180 | .replace('ref', _blockLabel) |
| 1181 | .getRegex(); |
| 1182 | const nolink = edit(/^!?\[(ref)\](?:\[\])?/) |
| 1183 | .replace('ref', _blockLabel) |
| 1184 | .getRegex(); |
| 1185 | const reflinkSearch = edit('reflink|nolink(?!\\()', 'g') |
| 1186 | .replace('reflink', reflink) |
| 1187 | .replace('nolink', nolink) |
| 1188 | .getRegex(); |
| 1189 | /** |
| 1190 | * Normal Inline Grammar |
| 1191 | */ |
| 1192 | const inlineNormal = { |
| 1193 | _backpedal: noopTest, // only used for GFM url |
| 1194 | anyPunctuation, |
| 1195 | autolink, |
| 1196 | blockSkip, |
| 1197 | br, |
| 1198 | code: inlineCode, |
| 1199 | del: noopTest, |
| 1200 | emStrongLDelim, |
| 1201 | emStrongRDelimAst, |
| 1202 | emStrongRDelimUnd, |
| 1203 | escape, |
| 1204 | link, |
| 1205 | nolink, |
| 1206 | punctuation, |
| 1207 | reflink, |
| 1208 | reflinkSearch, |
| 1209 | tag, |
| 1210 | text: inlineText, |
| 1211 | url: noopTest, |
| 1212 | }; |
| 1213 | /** |
| 1214 | * Pedantic Inline Grammar |
| 1215 | */ |
| 1216 | const inlinePedantic = { |
| 1217 | ...inlineNormal, |
| 1218 | link: edit(/^!?\[(label)\]\((.*?)\)/) |
| 1219 | .replace('label', _inlineLabel) |
| 1220 | .getRegex(), |
| 1221 | reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) |
| 1222 | .replace('label', _inlineLabel) |
| 1223 | .getRegex(), |
| 1224 | }; |
| 1225 | /** |
| 1226 | * GFM Inline Grammar |
| 1227 | */ |
| 1228 | const inlineGfm = { |
| 1229 | ...inlineNormal, |
| 1230 | escape: edit(escape).replace('])', '~|])').getRegex(), |
| 1231 | url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i') |
| 1232 | .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/) |
| 1233 | .getRegex(), |
| 1234 | _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, |
| 1235 | del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, |
| 1236 | text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/, |
| 1237 | }; |
| 1238 | /** |
| 1239 | * GFM + Line Breaks Inline Grammar |
| 1240 | */ |
| 1241 | const inlineBreaks = { |
| 1242 | ...inlineGfm, |
| 1243 | br: edit(br).replace('{2,}', '*').getRegex(), |
| 1244 | text: edit(inlineGfm.text) |
| 1245 | .replace('\\b_', '\\b_| {2,}\\n') |
| 1246 | .replace(/\{2,\}/g, '*') |
| 1247 | .getRegex(), |
| 1248 | }; |
| 1249 | /** |
| 1250 | * exports |
| 1251 | */ |
| 1252 | const block = { |
| 1253 | normal: blockNormal, |
| 1254 | gfm: blockGfm, |
| 1255 | pedantic: blockPedantic, |
| 1256 | }; |
| 1257 | const inline = { |
| 1258 | normal: inlineNormal, |
| 1259 | gfm: inlineGfm, |
| 1260 | breaks: inlineBreaks, |
| 1261 | pedantic: inlinePedantic, |
| 1262 | }; |
| 1263 | |
| 1264 | /** |
| 1265 | * Block Lexer |
| 1266 | */ |
| 1267 | class _Lexer { |
| 1268 | tokens; |
| 1269 | options; |
| 1270 | state; |
| 1271 | tokenizer; |
| 1272 | inlineQueue; |
| 1273 | constructor(options) { |
| 1274 | // TokenList cannot be created in one go |
| 1275 | this.tokens = []; |
| 1276 | this.tokens.links = Object.create(null); |
| 1277 | this.options = options || exports.defaults; |
| 1278 | this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); |
| 1279 | this.tokenizer = this.options.tokenizer; |
| 1280 | this.tokenizer.options = this.options; |
| 1281 | this.tokenizer.lexer = this; |
| 1282 | this.inlineQueue = []; |
| 1283 | this.state = { |
| 1284 | inLink: false, |
| 1285 | inRawBlock: false, |
| 1286 | top: true, |
| 1287 | }; |
| 1288 | const rules = { |
| 1289 | block: block.normal, |
| 1290 | inline: inline.normal, |
| 1291 | }; |
| 1292 | if (this.options.pedantic) { |
| 1293 | rules.block = block.pedantic; |
| 1294 | rules.inline = inline.pedantic; |
| 1295 | } |
| 1296 | else if (this.options.gfm) { |
| 1297 | rules.block = block.gfm; |
| 1298 | if (this.options.breaks) { |
| 1299 | rules.inline = inline.breaks; |
| 1300 | } |
| 1301 | else { |
| 1302 | rules.inline = inline.gfm; |
| 1303 | } |
| 1304 | } |
| 1305 | this.tokenizer.rules = rules; |
| 1306 | } |
| 1307 | /** |
| 1308 | * Expose Rules |
| 1309 | */ |
| 1310 | static get rules() { |
| 1311 | return { |
| 1312 | block, |
| 1313 | inline, |
| 1314 | }; |
| 1315 | } |
| 1316 | /** |
| 1317 | * Static Lex Method |
| 1318 | */ |
| 1319 | static lex(src, options) { |
| 1320 | const lexer = new _Lexer(options); |
| 1321 | return lexer.lex(src); |
| 1322 | } |
| 1323 | /** |
| 1324 | * Static Lex Inline Method |
| 1325 | */ |
| 1326 | static lexInline(src, options) { |
| 1327 | const lexer = new _Lexer(options); |
| 1328 | return lexer.inlineTokens(src); |
| 1329 | } |
| 1330 | /** |
| 1331 | * Preprocessing |
| 1332 | */ |
| 1333 | lex(src) { |
| 1334 | src = src |
| 1335 | .replace(/\r\n|\r/g, '\n'); |
| 1336 | this.blockTokens(src, this.tokens); |
| 1337 | for (let i = 0; i < this.inlineQueue.length; i++) { |
| 1338 | const next = this.inlineQueue[i]; |
| 1339 | this.inlineTokens(next.src, next.tokens); |
| 1340 | } |
| 1341 | this.inlineQueue = []; |
| 1342 | return this.tokens; |
| 1343 | } |
| 1344 | blockTokens(src, tokens = [], lastParagraphClipped = false) { |
| 1345 | if (this.options.pedantic) { |
| 1346 | src = src.replace(/\t/g, ' ').replace(/^ +$/gm, ''); |
| 1347 | } |
| 1348 | let token; |
| 1349 | let lastToken; |
| 1350 | let cutSrc; |
| 1351 | while (src) { |
| 1352 | if (this.options.extensions |
| 1353 | && this.options.extensions.block |
| 1354 | && this.options.extensions.block.some((extTokenizer) => { |
| 1355 | if (token = extTokenizer.call({ lexer: this }, src, tokens)) { |
| 1356 | src = src.substring(token.raw.length); |
| 1357 | tokens.push(token); |
| 1358 | return true; |
| 1359 | } |
| 1360 | return false; |
| 1361 | })) { |
| 1362 | continue; |
| 1363 | } |
| 1364 | // newline |
| 1365 | if (token = this.tokenizer.space(src)) { |
| 1366 | src = src.substring(token.raw.length); |
| 1367 | if (token.raw.length === 1 && tokens.length > 0) { |
| 1368 | // if there's a single \n as a spacer, it's terminating the last line, |
| 1369 | // so move it there so that we don't get unnecessary paragraph tags |
| 1370 | tokens[tokens.length - 1].raw += '\n'; |
| 1371 | } |
| 1372 | else { |
| 1373 | tokens.push(token); |
| 1374 | } |
| 1375 | continue; |
| 1376 | } |
| 1377 | // code |
| 1378 | if (token = this.tokenizer.code(src)) { |
| 1379 | src = src.substring(token.raw.length); |
| 1380 | lastToken = tokens[tokens.length - 1]; |
| 1381 | // An indented code block cannot interrupt a paragraph. |
| 1382 | if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { |
| 1383 | lastToken.raw += '\n' + token.raw; |
| 1384 | lastToken.text += '\n' + token.text; |
| 1385 | this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; |
| 1386 | } |
| 1387 | else { |
| 1388 | tokens.push(token); |
| 1389 | } |
| 1390 | continue; |
| 1391 | } |
| 1392 | // fences |
| 1393 | if (token = this.tokenizer.fences(src)) { |
| 1394 | src = src.substring(token.raw.length); |
| 1395 | tokens.push(token); |
| 1396 | continue; |
| 1397 | } |
| 1398 | // heading |
| 1399 | if (token = this.tokenizer.heading(src)) { |
| 1400 | src = src.substring(token.raw.length); |
| 1401 | tokens.push(token); |
| 1402 | continue; |
| 1403 | } |
| 1404 | // hr |
| 1405 | if (token = this.tokenizer.hr(src)) { |
| 1406 | src = src.substring(token.raw.length); |
| 1407 | tokens.push(token); |
| 1408 | continue; |
| 1409 | } |
| 1410 | // blockquote |
| 1411 | if (token = this.tokenizer.blockquote(src)) { |
| 1412 | src = src.substring(token.raw.length); |
| 1413 | tokens.push(token); |
| 1414 | continue; |
| 1415 | } |
| 1416 | // list |
| 1417 | if (token = this.tokenizer.list(src)) { |
| 1418 | src = src.substring(token.raw.length); |
| 1419 | tokens.push(token); |
| 1420 | continue; |
| 1421 | } |
| 1422 | // html |
| 1423 | if (token = this.tokenizer.html(src)) { |
| 1424 | src = src.substring(token.raw.length); |
| 1425 | tokens.push(token); |
| 1426 | continue; |
| 1427 | } |
| 1428 | // def |
| 1429 | if (token = this.tokenizer.def(src)) { |
| 1430 | src = src.substring(token.raw.length); |
| 1431 | lastToken = tokens[tokens.length - 1]; |
| 1432 | if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { |
| 1433 | lastToken.raw += '\n' + token.raw; |
| 1434 | lastToken.text += '\n' + token.raw; |
| 1435 | this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; |
| 1436 | } |
| 1437 | else if (!this.tokens.links[token.tag]) { |
| 1438 | this.tokens.links[token.tag] = { |
| 1439 | href: token.href, |
| 1440 | title: token.title, |
| 1441 | }; |
| 1442 | } |
| 1443 | continue; |
| 1444 | } |
| 1445 | // table (gfm) |
| 1446 | if (token = this.tokenizer.table(src)) { |
| 1447 | src = src.substring(token.raw.length); |
| 1448 | tokens.push(token); |
| 1449 | continue; |
| 1450 | } |
| 1451 | // lheading |
| 1452 | if (token = this.tokenizer.lheading(src)) { |
| 1453 | src = src.substring(token.raw.length); |
| 1454 | tokens.push(token); |
| 1455 | continue; |
| 1456 | } |
| 1457 | // top-level paragraph |
| 1458 | // prevent paragraph consuming extensions by clipping 'src' to extension start |
| 1459 | cutSrc = src; |
| 1460 | if (this.options.extensions && this.options.extensions.startBlock) { |
| 1461 | let startIndex = Infinity; |
| 1462 | const tempSrc = src.slice(1); |
| 1463 | let tempStart; |
| 1464 | this.options.extensions.startBlock.forEach((getStartIndex) => { |
| 1465 | tempStart = getStartIndex.call({ lexer: this }, tempSrc); |
| 1466 | if (typeof tempStart === 'number' && tempStart >= 0) { |
| 1467 | startIndex = Math.min(startIndex, tempStart); |
| 1468 | } |
| 1469 | }); |
| 1470 | if (startIndex < Infinity && startIndex >= 0) { |
| 1471 | cutSrc = src.substring(0, startIndex + 1); |
| 1472 | } |
| 1473 | } |
| 1474 | if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { |
| 1475 | lastToken = tokens[tokens.length - 1]; |
| 1476 | if (lastParagraphClipped && lastToken?.type === 'paragraph') { |
| 1477 | lastToken.raw += '\n' + token.raw; |
| 1478 | lastToken.text += '\n' + token.text; |
| 1479 | this.inlineQueue.pop(); |
| 1480 | this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; |
| 1481 | } |
| 1482 | else { |
| 1483 | tokens.push(token); |
| 1484 | } |
| 1485 | lastParagraphClipped = (cutSrc.length !== src.length); |
| 1486 | src = src.substring(token.raw.length); |
| 1487 | continue; |
| 1488 | } |
| 1489 | // text |
| 1490 | if (token = this.tokenizer.text(src)) { |
| 1491 | src = src.substring(token.raw.length); |
| 1492 | lastToken = tokens[tokens.length - 1]; |
| 1493 | if (lastToken && lastToken.type === 'text') { |
| 1494 | lastToken.raw += '\n' + token.raw; |
| 1495 | lastToken.text += '\n' + token.text; |
| 1496 | this.inlineQueue.pop(); |
| 1497 | this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; |
| 1498 | } |
| 1499 | else { |
| 1500 | tokens.push(token); |
| 1501 | } |
| 1502 | continue; |
| 1503 | } |
| 1504 | if (src) { |
| 1505 | const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); |
| 1506 | if (this.options.silent) { |
| 1507 | console.error(errMsg); |
| 1508 | break; |
| 1509 | } |
| 1510 | else { |
| 1511 | throw new Error(errMsg); |
| 1512 | } |
| 1513 | } |
| 1514 | } |
| 1515 | this.state.top = true; |
| 1516 | return tokens; |
| 1517 | } |
| 1518 | inline(src, tokens = []) { |
| 1519 | this.inlineQueue.push({ src, tokens }); |
| 1520 | return tokens; |
| 1521 | } |
| 1522 | /** |
| 1523 | * Lexing/Compiling |
| 1524 | */ |
| 1525 | inlineTokens(src, tokens = []) { |
| 1526 | let token, lastToken, cutSrc; |
| 1527 | // String with links masked to avoid interference with em and strong |
| 1528 | let maskedSrc = src; |
| 1529 | let match; |
| 1530 | let keepPrevChar, prevChar; |
| 1531 | // Mask out reflinks |
| 1532 | if (this.tokens.links) { |
| 1533 | const links = Object.keys(this.tokens.links); |
| 1534 | if (links.length > 0) { |
| 1535 | while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { |
| 1536 | if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { |
| 1537 | maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); |
| 1538 | } |
| 1539 | } |
| 1540 | } |
| 1541 | } |
| 1542 | // Mask out other blocks |
| 1543 | while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { |
| 1544 | maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); |
| 1545 | } |
| 1546 | // Mask out escaped characters |
| 1547 | while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { |
| 1548 | maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); |
| 1549 | } |
| 1550 | while (src) { |
| 1551 | if (!keepPrevChar) { |
| 1552 | prevChar = ''; |
| 1553 | } |
| 1554 | keepPrevChar = false; |
| 1555 | // extensions |
| 1556 | if (this.options.extensions |
| 1557 | && this.options.extensions.inline |
| 1558 | && this.options.extensions.inline.some((extTokenizer) => { |
| 1559 | if (token = extTokenizer.call({ lexer: this }, src, tokens)) { |
| 1560 | src = src.substring(token.raw.length); |
| 1561 | tokens.push(token); |
| 1562 | return true; |
| 1563 | } |
| 1564 | return false; |
| 1565 | })) { |
| 1566 | continue; |
| 1567 | } |
| 1568 | // escape |
| 1569 | if (token = this.tokenizer.escape(src)) { |
| 1570 | src = src.substring(token.raw.length); |
| 1571 | tokens.push(token); |
| 1572 | continue; |
| 1573 | } |
| 1574 | // tag |
| 1575 | if (token = this.tokenizer.tag(src)) { |
| 1576 | src = src.substring(token.raw.length); |
| 1577 | lastToken = tokens[tokens.length - 1]; |
| 1578 | if (lastToken && token.type === 'text' && lastToken.type === 'text') { |
| 1579 | lastToken.raw += token.raw; |
| 1580 | lastToken.text += token.text; |
| 1581 | } |
| 1582 | else { |
| 1583 | tokens.push(token); |
| 1584 | } |
| 1585 | continue; |
| 1586 | } |
| 1587 | // link |
| 1588 | if (token = this.tokenizer.link(src)) { |
| 1589 | src = src.substring(token.raw.length); |
| 1590 | tokens.push(token); |
| 1591 | continue; |
| 1592 | } |
| 1593 | // reflink, nolink |
| 1594 | if (token = this.tokenizer.reflink(src, this.tokens.links)) { |
| 1595 | src = src.substring(token.raw.length); |
| 1596 | lastToken = tokens[tokens.length - 1]; |
| 1597 | if (lastToken && token.type === 'text' && lastToken.type === 'text') { |
| 1598 | lastToken.raw += token.raw; |
| 1599 | lastToken.text += token.text; |
| 1600 | } |
| 1601 | else { |
| 1602 | tokens.push(token); |
| 1603 | } |
| 1604 | continue; |
| 1605 | } |
| 1606 | // em & strong |
| 1607 | if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { |
| 1608 | src = src.substring(token.raw.length); |
| 1609 | tokens.push(token); |
| 1610 | continue; |
| 1611 | } |
| 1612 | // code |
| 1613 | if (token = this.tokenizer.codespan(src)) { |
| 1614 | src = src.substring(token.raw.length); |
| 1615 | tokens.push(token); |
| 1616 | continue; |
| 1617 | } |
| 1618 | // br |
| 1619 | if (token = this.tokenizer.br(src)) { |
| 1620 | src = src.substring(token.raw.length); |
| 1621 | tokens.push(token); |
| 1622 | continue; |
| 1623 | } |
| 1624 | // del (gfm) |
| 1625 | if (token = this.tokenizer.del(src)) { |
| 1626 | src = src.substring(token.raw.length); |
| 1627 | tokens.push(token); |
| 1628 | continue; |
| 1629 | } |
| 1630 | // autolink |
| 1631 | if (token = this.tokenizer.autolink(src)) { |
| 1632 | src = src.substring(token.raw.length); |
| 1633 | tokens.push(token); |
| 1634 | continue; |
| 1635 | } |
| 1636 | // url (gfm) |
| 1637 | if (!this.state.inLink && (token = this.tokenizer.url(src))) { |
| 1638 | src = src.substring(token.raw.length); |
| 1639 | tokens.push(token); |
| 1640 | continue; |
| 1641 | } |
| 1642 | // text |
| 1643 | // prevent inlineText consuming extensions by clipping 'src' to extension start |
| 1644 | cutSrc = src; |
| 1645 | if (this.options.extensions && this.options.extensions.startInline) { |
| 1646 | let startIndex = Infinity; |
| 1647 | const tempSrc = src.slice(1); |
| 1648 | let tempStart; |
| 1649 | this.options.extensions.startInline.forEach((getStartIndex) => { |
| 1650 | tempStart = getStartIndex.call({ lexer: this }, tempSrc); |
| 1651 | if (typeof tempStart === 'number' && tempStart >= 0) { |
| 1652 | startIndex = Math.min(startIndex, tempStart); |
| 1653 | } |
| 1654 | }); |
| 1655 | if (startIndex < Infinity && startIndex >= 0) { |
| 1656 | cutSrc = src.substring(0, startIndex + 1); |
| 1657 | } |
| 1658 | } |
| 1659 | if (token = this.tokenizer.inlineText(cutSrc)) { |
| 1660 | src = src.substring(token.raw.length); |
| 1661 | if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started |
| 1662 | prevChar = token.raw.slice(-1); |
| 1663 | } |
| 1664 | keepPrevChar = true; |
| 1665 | lastToken = tokens[tokens.length - 1]; |
| 1666 | if (lastToken && lastToken.type === 'text') { |
| 1667 | lastToken.raw += token.raw; |
| 1668 | lastToken.text += token.text; |
| 1669 | } |
| 1670 | else { |
| 1671 | tokens.push(token); |
| 1672 | } |
| 1673 | continue; |
| 1674 | } |
| 1675 | if (src) { |
| 1676 | const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); |
| 1677 | if (this.options.silent) { |
| 1678 | console.error(errMsg); |
| 1679 | break; |
| 1680 | } |
| 1681 | else { |
| 1682 | throw new Error(errMsg); |
| 1683 | } |
| 1684 | } |
| 1685 | } |
| 1686 | return tokens; |
| 1687 | } |
| 1688 | } |
| 1689 | |
| 1690 | /** |
| 1691 | * Renderer |
| 1692 | */ |
| 1693 | class _Renderer { |
| 1694 | options; |
| 1695 | parser; // set by the parser |
| 1696 | constructor(options) { |
| 1697 | this.options = options || exports.defaults; |
| 1698 | } |
| 1699 | space(token) { |
| 1700 | return ''; |
| 1701 | } |
| 1702 | code({ text, lang, escaped }) { |
| 1703 | const langString = (lang || '').match(/^\S*/)?.[0]; |
| 1704 | const code = text.replace(/\n$/, '') + '\n'; |
| 1705 | if (!langString) { |
| 1706 | return '<pre><code>' |
| 1707 | + (escaped ? code : escape$1(code, true)) |
| 1708 | + '</code></pre>\n'; |
| 1709 | } |
| 1710 | return '<pre><code class="language-' |
| 1711 | + escape$1(langString) |
| 1712 | + '">' |
| 1713 | + (escaped ? code : escape$1(code, true)) |
| 1714 | + '</code></pre>\n'; |
| 1715 | } |
| 1716 | blockquote({ tokens }) { |
| 1717 | const body = this.parser.parse(tokens); |
| 1718 | return `<blockquote>\n${body}</blockquote>\n`; |
| 1719 | } |
| 1720 | html({ text }) { |
| 1721 | return text; |
| 1722 | } |
| 1723 | heading({ tokens, depth }) { |
| 1724 | return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`; |
| 1725 | } |
| 1726 | hr(token) { |
| 1727 | return '<hr>\n'; |
| 1728 | } |
| 1729 | list(token) { |
| 1730 | const ordered = token.ordered; |
| 1731 | const start = token.start; |
| 1732 | let body = ''; |
| 1733 | for (let j = 0; j < token.items.length; j++) { |
| 1734 | const item = token.items[j]; |
| 1735 | body += this.listitem(item); |
| 1736 | } |
| 1737 | const type = ordered ? 'ol' : 'ul'; |
| 1738 | const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : ''; |
| 1739 | return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n'; |
| 1740 | } |
| 1741 | listitem(item) { |
| 1742 | let itemBody = ''; |
| 1743 | if (item.task) { |
| 1744 | const checkbox = this.checkbox({ checked: !!item.checked }); |
| 1745 | if (item.loose) { |
| 1746 | if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { |
| 1747 | item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; |
| 1748 | if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { |
| 1749 | item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; |
| 1750 | } |
| 1751 | } |
| 1752 | else { |
| 1753 | item.tokens.unshift({ |
| 1754 | type: 'text', |
| 1755 | raw: checkbox + ' ', |
| 1756 | text: checkbox + ' ', |
| 1757 | }); |
| 1758 | } |
| 1759 | } |
| 1760 | else { |
| 1761 | itemBody += checkbox + ' '; |
| 1762 | } |
| 1763 | } |
| 1764 | itemBody += this.parser.parse(item.tokens, !!item.loose); |
| 1765 | return `<li>${itemBody}</li>\n`; |
| 1766 | } |
| 1767 | checkbox({ checked }) { |
| 1768 | return '<input ' |
| 1769 | + (checked ? 'checked="" ' : '') |
| 1770 | + 'disabled="" type="checkbox">'; |
| 1771 | } |
| 1772 | paragraph({ tokens }) { |
| 1773 | return `<p>${this.parser.parseInline(tokens)}</p>\n`; |
| 1774 | } |
| 1775 | table(token) { |
| 1776 | let header = ''; |
| 1777 | // header |
| 1778 | let cell = ''; |
| 1779 | for (let j = 0; j < token.header.length; j++) { |
| 1780 | cell += this.tablecell(token.header[j]); |
| 1781 | } |
| 1782 | header += this.tablerow({ text: cell }); |
| 1783 | let body = ''; |
| 1784 | for (let j = 0; j < token.rows.length; j++) { |
| 1785 | const row = token.rows[j]; |
| 1786 | cell = ''; |
| 1787 | for (let k = 0; k < row.length; k++) { |
| 1788 | cell += this.tablecell(row[k]); |
| 1789 | } |
| 1790 | body += this.tablerow({ text: cell }); |
| 1791 | } |
| 1792 | if (body) |
| 1793 | body = `<tbody>${body}</tbody>`; |
| 1794 | return '<table>\n' |
| 1795 | + '<thead>\n' |
| 1796 | + header |
| 1797 | + '</thead>\n' |
| 1798 | + body |
| 1799 | + '</table>\n'; |
| 1800 | } |
| 1801 | tablerow({ text }) { |
| 1802 | return `<tr>\n${text}</tr>\n`; |
| 1803 | } |
| 1804 | tablecell(token) { |
| 1805 | const content = this.parser.parseInline(token.tokens); |
| 1806 | const type = token.header ? 'th' : 'td'; |
| 1807 | const tag = token.align |
| 1808 | ? `<${type} align="${token.align}">` |
| 1809 | : `<${type}>`; |
| 1810 | return tag + content + `</${type}>\n`; |
| 1811 | } |
| 1812 | /** |
| 1813 | * span level renderer |
| 1814 | */ |
| 1815 | strong({ tokens }) { |
| 1816 | return `<strong>${this.parser.parseInline(tokens)}</strong>`; |
| 1817 | } |
| 1818 | em({ tokens }) { |
| 1819 | return `<em>${this.parser.parseInline(tokens)}</em>`; |
| 1820 | } |
| 1821 | codespan({ text }) { |
| 1822 | return `<code>${text}</code>`; |
| 1823 | } |
| 1824 | br(token) { |
| 1825 | return '<br>'; |
| 1826 | } |
| 1827 | del({ tokens }) { |
| 1828 | return `<del>${this.parser.parseInline(tokens)}</del>`; |
| 1829 | } |
| 1830 | link({ href, title, tokens }) { |
| 1831 | const text = this.parser.parseInline(tokens); |
| 1832 | const cleanHref = cleanUrl(href); |
| 1833 | if (cleanHref === null) { |
| 1834 | return text; |
| 1835 | } |
| 1836 | href = cleanHref; |
| 1837 | let out = '<a href="' + href + '"'; |
| 1838 | if (title) { |
| 1839 | out += ' title="' + title + '"'; |
| 1840 | } |
| 1841 | out += '>' + text + '</a>'; |
| 1842 | return out; |
| 1843 | } |
| 1844 | image({ href, title, text }) { |
| 1845 | const cleanHref = cleanUrl(href); |
| 1846 | if (cleanHref === null) { |
| 1847 | return text; |
| 1848 | } |
| 1849 | href = cleanHref; |
| 1850 | let out = `<img src="${href}" alt="${text}"`; |
| 1851 | if (title) { |
| 1852 | out += ` title="${title}"`; |
| 1853 | } |
| 1854 | out += '>'; |
| 1855 | return out; |
| 1856 | } |
| 1857 | text(token) { |
| 1858 | return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text; |
| 1859 | } |
| 1860 | } |
| 1861 | |
| 1862 | /** |
| 1863 | * TextRenderer |
| 1864 | * returns only the textual part of the token |
| 1865 | */ |
| 1866 | class _TextRenderer { |
| 1867 | // no need for block level renderers |
| 1868 | strong({ text }) { |
| 1869 | return text; |
| 1870 | } |
| 1871 | em({ text }) { |
| 1872 | return text; |
| 1873 | } |
| 1874 | codespan({ text }) { |
| 1875 | return text; |
| 1876 | } |
| 1877 | del({ text }) { |
| 1878 | return text; |
| 1879 | } |
| 1880 | html({ text }) { |
| 1881 | return text; |
| 1882 | } |
| 1883 | text({ text }) { |
| 1884 | return text; |
| 1885 | } |
| 1886 | link({ text }) { |
| 1887 | return '' + text; |
| 1888 | } |
| 1889 | image({ text }) { |
| 1890 | return '' + text; |
| 1891 | } |
| 1892 | br() { |
| 1893 | return ''; |
| 1894 | } |
| 1895 | } |
| 1896 | |
| 1897 | /** |
| 1898 | * Parsing & Compiling |
| 1899 | */ |
| 1900 | class _Parser { |
| 1901 | options; |
| 1902 | renderer; |
| 1903 | textRenderer; |
| 1904 | constructor(options) { |
| 1905 | this.options = options || exports.defaults; |
| 1906 | this.options.renderer = this.options.renderer || new _Renderer(); |
| 1907 | this.renderer = this.options.renderer; |
| 1908 | this.renderer.options = this.options; |
| 1909 | this.renderer.parser = this; |
| 1910 | this.textRenderer = new _TextRenderer(); |
| 1911 | } |
| 1912 | /** |
| 1913 | * Static Parse Method |
| 1914 | */ |
| 1915 | static parse(tokens, options) { |
| 1916 | const parser = new _Parser(options); |
| 1917 | return parser.parse(tokens); |
| 1918 | } |
| 1919 | /** |
| 1920 | * Static Parse Inline Method |
| 1921 | */ |
| 1922 | static parseInline(tokens, options) { |
| 1923 | const parser = new _Parser(options); |
| 1924 | return parser.parseInline(tokens); |
| 1925 | } |
| 1926 | /** |
| 1927 | * Parse Loop |
| 1928 | */ |
| 1929 | parse(tokens, top = true) { |
| 1930 | let out = ''; |
| 1931 | for (let i = 0; i < tokens.length; i++) { |
| 1932 | const anyToken = tokens[i]; |
| 1933 | // Run any renderer extensions |
| 1934 | if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) { |
| 1935 | const genericToken = anyToken; |
| 1936 | const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken); |
| 1937 | if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) { |
| 1938 | out += ret || ''; |
| 1939 | continue; |
| 1940 | } |
| 1941 | } |
| 1942 | const token = anyToken; |
| 1943 | switch (token.type) { |
| 1944 | case 'space': { |
| 1945 | out += this.renderer.space(token); |
| 1946 | continue; |
| 1947 | } |
| 1948 | case 'hr': { |
| 1949 | out += this.renderer.hr(token); |
| 1950 | continue; |
| 1951 | } |
| 1952 | case 'heading': { |
| 1953 | out += this.renderer.heading(token); |
| 1954 | continue; |
| 1955 | } |
| 1956 | case 'code': { |
| 1957 | out += this.renderer.code(token); |
| 1958 | continue; |
| 1959 | } |
| 1960 | case 'table': { |
| 1961 | out += this.renderer.table(token); |
| 1962 | continue; |
| 1963 | } |
| 1964 | case 'blockquote': { |
| 1965 | out += this.renderer.blockquote(token); |
| 1966 | continue; |
| 1967 | } |
| 1968 | case 'list': { |
| 1969 | out += this.renderer.list(token); |
| 1970 | continue; |
| 1971 | } |
| 1972 | case 'html': { |
| 1973 | out += this.renderer.html(token); |
| 1974 | continue; |
| 1975 | } |
| 1976 | case 'paragraph': { |
| 1977 | out += this.renderer.paragraph(token); |
| 1978 | continue; |
| 1979 | } |
| 1980 | case 'text': { |
| 1981 | let textToken = token; |
| 1982 | let body = this.renderer.text(textToken); |
| 1983 | while (i + 1 < tokens.length && tokens[i + 1].type === 'text') { |
| 1984 | textToken = tokens[++i]; |
| 1985 | body += '\n' + this.renderer.text(textToken); |
| 1986 | } |
| 1987 | if (top) { |
| 1988 | out += this.renderer.paragraph({ |
| 1989 | type: 'paragraph', |
| 1990 | raw: body, |
| 1991 | text: body, |
| 1992 | tokens: [{ type: 'text', raw: body, text: body }], |
| 1993 | }); |
| 1994 | } |
| 1995 | else { |
| 1996 | out += body; |
| 1997 | } |
| 1998 | continue; |
| 1999 | } |
| 2000 | default: { |
| 2001 | const errMsg = 'Token with "' + token.type + '" type was not found.'; |
| 2002 | if (this.options.silent) { |
| 2003 | console.error(errMsg); |
| 2004 | return ''; |
| 2005 | } |
| 2006 | else { |
| 2007 | throw new Error(errMsg); |
| 2008 | } |
| 2009 | } |
| 2010 | } |
| 2011 | } |
| 2012 | return out; |
| 2013 | } |
| 2014 | /** |
| 2015 | * Parse Inline Tokens |
| 2016 | */ |
| 2017 | parseInline(tokens, renderer) { |
| 2018 | renderer = renderer || this.renderer; |
| 2019 | let out = ''; |
| 2020 | for (let i = 0; i < tokens.length; i++) { |
| 2021 | const anyToken = tokens[i]; |
| 2022 | // Run any renderer extensions |
| 2023 | if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) { |
| 2024 | const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken); |
| 2025 | if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) { |
| 2026 | out += ret || ''; |
| 2027 | continue; |
| 2028 | } |
| 2029 | } |
| 2030 | const token = anyToken; |
| 2031 | switch (token.type) { |
| 2032 | case 'escape': { |
| 2033 | out += renderer.text(token); |
| 2034 | break; |
| 2035 | } |
| 2036 | case 'html': { |
| 2037 | out += renderer.html(token); |
| 2038 | break; |
| 2039 | } |
| 2040 | case 'link': { |
| 2041 | out += renderer.link(token); |
| 2042 | break; |
| 2043 | } |
| 2044 | case 'image': { |
| 2045 | out += renderer.image(token); |
| 2046 | break; |
| 2047 | } |
| 2048 | case 'strong': { |
| 2049 | out += renderer.strong(token); |
| 2050 | break; |
| 2051 | } |
| 2052 | case 'em': { |
| 2053 | out += renderer.em(token); |
| 2054 | break; |
| 2055 | } |
| 2056 | case 'codespan': { |
| 2057 | out += renderer.codespan(token); |
| 2058 | break; |
| 2059 | } |
| 2060 | case 'br': { |
| 2061 | out += renderer.br(token); |
| 2062 | break; |
| 2063 | } |
| 2064 | case 'del': { |
| 2065 | out += renderer.del(token); |
| 2066 | break; |
| 2067 | } |
| 2068 | case 'text': { |
| 2069 | out += renderer.text(token); |
| 2070 | break; |
| 2071 | } |
| 2072 | default: { |
| 2073 | const errMsg = 'Token with "' + token.type + '" type was not found.'; |
| 2074 | if (this.options.silent) { |
| 2075 | console.error(errMsg); |
| 2076 | return ''; |
| 2077 | } |
| 2078 | else { |
| 2079 | throw new Error(errMsg); |
| 2080 | } |
| 2081 | } |
| 2082 | } |
| 2083 | } |
| 2084 | return out; |
| 2085 | } |
| 2086 | } |
| 2087 | |
| 2088 | class _Hooks { |
| 2089 | options; |
| 2090 | block; |
| 2091 | constructor(options) { |
| 2092 | this.options = options || exports.defaults; |
| 2093 | } |
| 2094 | static passThroughHooks = new Set([ |
| 2095 | 'preprocess', |
| 2096 | 'postprocess', |
| 2097 | 'processAllTokens', |
| 2098 | ]); |
| 2099 | /** |
| 2100 | * Process markdown before marked |
| 2101 | */ |
| 2102 | preprocess(markdown) { |
| 2103 | return markdown; |
| 2104 | } |
| 2105 | /** |
| 2106 | * Process HTML after marked is finished |
| 2107 | */ |
| 2108 | postprocess(html) { |
| 2109 | return html; |
| 2110 | } |
| 2111 | /** |
| 2112 | * Process all tokens before walk tokens |
| 2113 | */ |
| 2114 | processAllTokens(tokens) { |
| 2115 | return tokens; |
| 2116 | } |
| 2117 | /** |
| 2118 | * Provide function to tokenize markdown |
| 2119 | */ |
| 2120 | provideLexer() { |
| 2121 | return this.block ? _Lexer.lex : _Lexer.lexInline; |
| 2122 | } |
| 2123 | /** |
| 2124 | * Provide function to parse tokens |
| 2125 | */ |
| 2126 | provideParser() { |
| 2127 | return this.block ? _Parser.parse : _Parser.parseInline; |
| 2128 | } |
| 2129 | } |
| 2130 | |
| 2131 | class Marked { |
| 2132 | defaults = _getDefaults(); |
| 2133 | options = this.setOptions; |
| 2134 | parse = this.parseMarkdown(true); |
| 2135 | parseInline = this.parseMarkdown(false); |
| 2136 | Parser = _Parser; |
| 2137 | Renderer = _Renderer; |
| 2138 | TextRenderer = _TextRenderer; |
| 2139 | Lexer = _Lexer; |
| 2140 | Tokenizer = _Tokenizer; |
| 2141 | Hooks = _Hooks; |
| 2142 | constructor(...args) { |
| 2143 | this.use(...args); |
| 2144 | } |
| 2145 | /** |
| 2146 | * Run callback for every token |
| 2147 | */ |
| 2148 | walkTokens(tokens, callback) { |
| 2149 | let values = []; |
| 2150 | for (const token of tokens) { |
| 2151 | values = values.concat(callback.call(this, token)); |
| 2152 | switch (token.type) { |
| 2153 | case 'table': { |
| 2154 | const tableToken = token; |
| 2155 | for (const cell of tableToken.header) { |
| 2156 | values = values.concat(this.walkTokens(cell.tokens, callback)); |
| 2157 | } |
| 2158 | for (const row of tableToken.rows) { |
| 2159 | for (const cell of row) { |
| 2160 | values = values.concat(this.walkTokens(cell.tokens, callback)); |
| 2161 | } |
| 2162 | } |
| 2163 | break; |
| 2164 | } |
| 2165 | case 'list': { |
| 2166 | const listToken = token; |
| 2167 | values = values.concat(this.walkTokens(listToken.items, callback)); |
| 2168 | break; |
| 2169 | } |
| 2170 | default: { |
| 2171 | const genericToken = token; |
| 2172 | if (this.defaults.extensions?.childTokens?.[genericToken.type]) { |
| 2173 | this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => { |
| 2174 | const tokens = genericToken[childTokens].flat(Infinity); |
| 2175 | values = values.concat(this.walkTokens(tokens, callback)); |
| 2176 | }); |
| 2177 | } |
| 2178 | else if (genericToken.tokens) { |
| 2179 | values = values.concat(this.walkTokens(genericToken.tokens, callback)); |
| 2180 | } |
| 2181 | } |
| 2182 | } |
| 2183 | } |
| 2184 | return values; |
| 2185 | } |
| 2186 | use(...args) { |
| 2187 | const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; |
| 2188 | args.forEach((pack) => { |
| 2189 | // copy options to new object |
| 2190 | const opts = { ...pack }; |
| 2191 | // set async to true if it was set to true before |
| 2192 | opts.async = this.defaults.async || opts.async || false; |
| 2193 | // ==-- Parse "addon" extensions --== // |
| 2194 | if (pack.extensions) { |
| 2195 | pack.extensions.forEach((ext) => { |
| 2196 | if (!ext.name) { |
| 2197 | throw new Error('extension name required'); |
| 2198 | } |
| 2199 | if ('renderer' in ext) { // Renderer extensions |
| 2200 | const prevRenderer = extensions.renderers[ext.name]; |
| 2201 | if (prevRenderer) { |
| 2202 | // Replace extension with func to run new extension but fall back if false |
| 2203 | extensions.renderers[ext.name] = function (...args) { |
| 2204 | let ret = ext.renderer.apply(this, args); |
| 2205 | if (ret === false) { |
| 2206 | ret = prevRenderer.apply(this, args); |
| 2207 | } |
| 2208 | return ret; |
| 2209 | }; |
| 2210 | } |
| 2211 | else { |
| 2212 | extensions.renderers[ext.name] = ext.renderer; |
| 2213 | } |
| 2214 | } |
| 2215 | if ('tokenizer' in ext) { // Tokenizer Extensions |
| 2216 | if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) { |
| 2217 | throw new Error("extension level must be 'block' or 'inline'"); |
| 2218 | } |
| 2219 | const extLevel = extensions[ext.level]; |
| 2220 | if (extLevel) { |
| 2221 | extLevel.unshift(ext.tokenizer); |
| 2222 | } |
| 2223 | else { |
| 2224 | extensions[ext.level] = [ext.tokenizer]; |
| 2225 | } |
| 2226 | if (ext.start) { // Function to check for start of token |
| 2227 | if (ext.level === 'block') { |
| 2228 | if (extensions.startBlock) { |
| 2229 | extensions.startBlock.push(ext.start); |
| 2230 | } |
| 2231 | else { |
| 2232 | extensions.startBlock = [ext.start]; |
| 2233 | } |
| 2234 | } |
| 2235 | else if (ext.level === 'inline') { |
| 2236 | if (extensions.startInline) { |
| 2237 | extensions.startInline.push(ext.start); |
| 2238 | } |
| 2239 | else { |
| 2240 | extensions.startInline = [ext.start]; |
| 2241 | } |
| 2242 | } |
| 2243 | } |
| 2244 | } |
| 2245 | if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens |
| 2246 | extensions.childTokens[ext.name] = ext.childTokens; |
| 2247 | } |
| 2248 | }); |
| 2249 | opts.extensions = extensions; |
| 2250 | } |
| 2251 | // ==-- Parse "overwrite" extensions --== // |
| 2252 | if (pack.renderer) { |
| 2253 | const renderer = this.defaults.renderer || new _Renderer(this.defaults); |
| 2254 | for (const prop in pack.renderer) { |
| 2255 | if (!(prop in renderer)) { |
| 2256 | throw new Error(`renderer '${prop}' does not exist`); |
| 2257 | } |
| 2258 | if (['options', 'parser'].includes(prop)) { |
| 2259 | // ignore options property |
| 2260 | continue; |
| 2261 | } |
| 2262 | const rendererProp = prop; |
| 2263 | const rendererFunc = pack.renderer[rendererProp]; |
| 2264 | const prevRenderer = renderer[rendererProp]; |
| 2265 | // Replace renderer with func to run extension, but fall back if false |
| 2266 | renderer[rendererProp] = (...args) => { |
| 2267 | let ret = rendererFunc.apply(renderer, args); |
| 2268 | if (ret === false) { |
| 2269 | ret = prevRenderer.apply(renderer, args); |
| 2270 | } |
| 2271 | return ret || ''; |
| 2272 | }; |
| 2273 | } |
| 2274 | opts.renderer = renderer; |
| 2275 | } |
| 2276 | if (pack.tokenizer) { |
| 2277 | const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); |
| 2278 | for (const prop in pack.tokenizer) { |
| 2279 | if (!(prop in tokenizer)) { |
| 2280 | throw new Error(`tokenizer '${prop}' does not exist`); |
| 2281 | } |
| 2282 | if (['options', 'rules', 'lexer'].includes(prop)) { |
| 2283 | // ignore options, rules, and lexer properties |
| 2284 | continue; |
| 2285 | } |
| 2286 | const tokenizerProp = prop; |
| 2287 | const tokenizerFunc = pack.tokenizer[tokenizerProp]; |
| 2288 | const prevTokenizer = tokenizer[tokenizerProp]; |
| 2289 | // Replace tokenizer with func to run extension, but fall back if false |
| 2290 | // @ts-expect-error cannot type tokenizer function dynamically |
| 2291 | tokenizer[tokenizerProp] = (...args) => { |
| 2292 | let ret = tokenizerFunc.apply(tokenizer, args); |
| 2293 | if (ret === false) { |
| 2294 | ret = prevTokenizer.apply(tokenizer, args); |
| 2295 | } |
| 2296 | return ret; |
| 2297 | }; |
| 2298 | } |
| 2299 | opts.tokenizer = tokenizer; |
| 2300 | } |
| 2301 | // ==-- Parse Hooks extensions --== // |
| 2302 | if (pack.hooks) { |
| 2303 | const hooks = this.defaults.hooks || new _Hooks(); |
| 2304 | for (const prop in pack.hooks) { |
| 2305 | if (!(prop in hooks)) { |
| 2306 | throw new Error(`hook '${prop}' does not exist`); |
| 2307 | } |
| 2308 | if (['options', 'block'].includes(prop)) { |
| 2309 | // ignore options and block properties |
| 2310 | continue; |
| 2311 | } |
| 2312 | const hooksProp = prop; |
| 2313 | const hooksFunc = pack.hooks[hooksProp]; |
| 2314 | const prevHook = hooks[hooksProp]; |
| 2315 | if (_Hooks.passThroughHooks.has(prop)) { |
| 2316 | // @ts-expect-error cannot type hook function dynamically |
| 2317 | hooks[hooksProp] = (arg) => { |
| 2318 | if (this.defaults.async) { |
| 2319 | return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { |
| 2320 | return prevHook.call(hooks, ret); |
| 2321 | }); |
| 2322 | } |
| 2323 | const ret = hooksFunc.call(hooks, arg); |
| 2324 | return prevHook.call(hooks, ret); |
| 2325 | }; |
| 2326 | } |
| 2327 | else { |
| 2328 | // @ts-expect-error cannot type hook function dynamically |
| 2329 | hooks[hooksProp] = (...args) => { |
| 2330 | let ret = hooksFunc.apply(hooks, args); |
| 2331 | if (ret === false) { |
| 2332 | ret = prevHook.apply(hooks, args); |
| 2333 | } |
| 2334 | return ret; |
| 2335 | }; |
| 2336 | } |
| 2337 | } |
| 2338 | opts.hooks = hooks; |
| 2339 | } |
| 2340 | // ==-- Parse WalkTokens extensions --== // |
| 2341 | if (pack.walkTokens) { |
| 2342 | const walkTokens = this.defaults.walkTokens; |
| 2343 | const packWalktokens = pack.walkTokens; |
| 2344 | opts.walkTokens = function (token) { |
| 2345 | let values = []; |
| 2346 | values.push(packWalktokens.call(this, token)); |
| 2347 | if (walkTokens) { |
| 2348 | values = values.concat(walkTokens.call(this, token)); |
| 2349 | } |
| 2350 | return values; |
| 2351 | }; |
| 2352 | } |
| 2353 | this.defaults = { ...this.defaults, ...opts }; |
| 2354 | }); |
| 2355 | return this; |
| 2356 | } |
| 2357 | setOptions(opt) { |
| 2358 | this.defaults = { ...this.defaults, ...opt }; |
| 2359 | return this; |
| 2360 | } |
| 2361 | lexer(src, options) { |
| 2362 | return _Lexer.lex(src, options ?? this.defaults); |
| 2363 | } |
| 2364 | parser(tokens, options) { |
| 2365 | return _Parser.parse(tokens, options ?? this.defaults); |
| 2366 | } |
| 2367 | parseMarkdown(blockType) { |
| 2368 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 2369 | const parse = (src, options) => { |
| 2370 | const origOpt = { ...options }; |
| 2371 | const opt = { ...this.defaults, ...origOpt }; |
| 2372 | const throwError = this.onError(!!opt.silent, !!opt.async); |
| 2373 | // throw error if an extension set async to true but parse was called with async: false |
| 2374 | if (this.defaults.async === true && origOpt.async === false) { |
| 2375 | return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.')); |
| 2376 | } |
| 2377 | // throw error in case of non string input |
| 2378 | if (typeof src === 'undefined' || src === null) { |
| 2379 | return throwError(new Error('marked(): input parameter is undefined or null')); |
| 2380 | } |
| 2381 | if (typeof src !== 'string') { |
| 2382 | return throwError(new Error('marked(): input parameter is of type ' |
| 2383 | + Object.prototype.toString.call(src) + ', string expected')); |
| 2384 | } |
| 2385 | if (opt.hooks) { |
| 2386 | opt.hooks.options = opt; |
| 2387 | opt.hooks.block = blockType; |
| 2388 | } |
| 2389 | const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline); |
| 2390 | const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline); |
| 2391 | if (opt.async) { |
| 2392 | return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src) |
| 2393 | .then(src => lexer(src, opt)) |
| 2394 | .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens) |
| 2395 | .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens) |
| 2396 | .then(tokens => parser(tokens, opt)) |
| 2397 | .then(html => opt.hooks ? opt.hooks.postprocess(html) : html) |
| 2398 | .catch(throwError); |
| 2399 | } |
| 2400 | try { |
| 2401 | if (opt.hooks) { |
| 2402 | src = opt.hooks.preprocess(src); |
| 2403 | } |
| 2404 | let tokens = lexer(src, opt); |
| 2405 | if (opt.hooks) { |
| 2406 | tokens = opt.hooks.processAllTokens(tokens); |
| 2407 | } |
| 2408 | if (opt.walkTokens) { |
| 2409 | this.walkTokens(tokens, opt.walkTokens); |
| 2410 | } |
| 2411 | let html = parser(tokens, opt); |
| 2412 | if (opt.hooks) { |
| 2413 | html = opt.hooks.postprocess(html); |
| 2414 | } |
| 2415 | return html; |
| 2416 | } |
| 2417 | catch (e) { |
| 2418 | return throwError(e); |
| 2419 | } |
| 2420 | }; |
| 2421 | return parse; |
| 2422 | } |
| 2423 | onError(silent, async) { |
| 2424 | return (e) => { |
| 2425 | e.message += '\nPlease report this to https://github.com/markedjs/marked.'; |
| 2426 | if (silent) { |
| 2427 | const msg = '<p>An error occurred:</p><pre>' |
| 2428 | + escape$1(e.message + '', true) |
| 2429 | + '</pre>'; |
| 2430 | if (async) { |
| 2431 | return Promise.resolve(msg); |
| 2432 | } |
| 2433 | return msg; |
| 2434 | } |
| 2435 | if (async) { |
| 2436 | return Promise.reject(e); |
| 2437 | } |
| 2438 | throw e; |
| 2439 | }; |
| 2440 | } |
| 2441 | } |
| 2442 | |
| 2443 | const markedInstance = new Marked(); |
| 2444 | function marked(src, opt) { |
| 2445 | return markedInstance.parse(src, opt); |
| 2446 | } |
| 2447 | /** |
| 2448 | * Sets the default options. |
| 2449 | * |
| 2450 | * @param options Hash of options |
| 2451 | */ |
| 2452 | marked.options = |
| 2453 | marked.setOptions = function (options) { |
| 2454 | markedInstance.setOptions(options); |
| 2455 | marked.defaults = markedInstance.defaults; |
| 2456 | changeDefaults(marked.defaults); |
| 2457 | return marked; |
| 2458 | }; |
| 2459 | /** |
| 2460 | * Gets the original marked default options. |
| 2461 | */ |
| 2462 | marked.getDefaults = _getDefaults; |
| 2463 | marked.defaults = exports.defaults; |
| 2464 | /** |
| 2465 | * Use Extension |
| 2466 | */ |
| 2467 | marked.use = function (...args) { |
| 2468 | markedInstance.use(...args); |
| 2469 | marked.defaults = markedInstance.defaults; |
| 2470 | changeDefaults(marked.defaults); |
| 2471 | return marked; |
| 2472 | }; |
| 2473 | /** |
| 2474 | * Run callback for every token |
| 2475 | */ |
| 2476 | marked.walkTokens = function (tokens, callback) { |
| 2477 | return markedInstance.walkTokens(tokens, callback); |
| 2478 | }; |
| 2479 | /** |
| 2480 | * Compiles markdown to HTML without enclosing `p` tag. |
| 2481 | * |
| 2482 | * @param src String of markdown source to be compiled |
| 2483 | * @param options Hash of options |
| 2484 | * @return String of compiled HTML |
| 2485 | */ |
| 2486 | marked.parseInline = markedInstance.parseInline; |
| 2487 | /** |
| 2488 | * Expose |
| 2489 | */ |
| 2490 | marked.Parser = _Parser; |
| 2491 | marked.parser = _Parser.parse; |
| 2492 | marked.Renderer = _Renderer; |
| 2493 | marked.TextRenderer = _TextRenderer; |
| 2494 | marked.Lexer = _Lexer; |
| 2495 | marked.lexer = _Lexer.lex; |
| 2496 | marked.Tokenizer = _Tokenizer; |
| 2497 | marked.Hooks = _Hooks; |
| 2498 | marked.parse = marked; |
| 2499 | const options = marked.options; |
| 2500 | const setOptions = marked.setOptions; |
| 2501 | const use = marked.use; |
| 2502 | const walkTokens = marked.walkTokens; |
| 2503 | const parseInline = marked.parseInline; |
| 2504 | const parse = marked; |
| 2505 | const parser = _Parser.parse; |
| 2506 | const lexer = _Lexer.lex; |
| 2507 | |
| 2508 | exports.Hooks = _Hooks; |
| 2509 | exports.Lexer = _Lexer; |
| 2510 | exports.Marked = Marked; |
| 2511 | exports.Parser = _Parser; |
| 2512 | exports.Renderer = _Renderer; |
| 2513 | exports.TextRenderer = _TextRenderer; |
| 2514 | exports.Tokenizer = _Tokenizer; |
| 2515 | exports.getDefaults = _getDefaults; |
| 2516 | exports.lexer = lexer; |
| 2517 | exports.marked = marked; |
| 2518 | exports.options = options; |
| 2519 | exports.parse = parse; |
| 2520 | exports.parseInline = parseInline; |
| 2521 | exports.parser = parser; |
| 2522 | exports.setOptions = setOptions; |
| 2523 | exports.use = use; |
| 2524 | exports.walkTokens = walkTokens; |
| 2525 | |
| 2526 | })); |
| 2527 | //# sourceMappingURL=marked.umd.js.map |