marked.umd.js 107 KB

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