marked.esm.js 96 KB

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