instaui 0.1.3__py3-none-any.whl → 0.1.4__py3-none-any.whl

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