marked-cs 0.0.1-security → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of marked-cs might be problematic. Click here for more details.

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