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