@khanacademy/simple-markdown 0.0.0-PR1039-20240229230747

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.
package/dist/index.js ADDED
@@ -0,0 +1,1421 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var perseusCore = require('@khanacademy/perseus-core');
6
+
7
+ // This file is processed by a Rollup plugin (replace) to inject the production
8
+ const libName = "@khanacademy/simple-markdown";
9
+ const libVersion = "0.11.3";
10
+ perseusCore.addLibraryVersionToPerseusDebug(libName, libVersion);
11
+
12
+ /* eslint-disable prefer-spread, no-regex-spaces, @typescript-eslint/no-unused-vars, guard-for-in, no-console, no-var */
13
+
14
+ // Type Definitions:
15
+
16
+ // We want to clarify our defaultRules types a little bit more so clients can
17
+ // reuse defaultRules built-ins. So we make some stronger guarantess when
18
+ // we can:
19
+ // End TypeScript Definitions
20
+
21
+ var CR_NEWLINE_R = /\r\n?/g;
22
+ var TAB_R = /\t/g;
23
+ var FORMFEED_R = /\f/g;
24
+
25
+ /**
26
+ * Turn various whitespace into easy-to-process whitespace
27
+ */
28
+ var preprocess = function (source) {
29
+ return source.replace(CR_NEWLINE_R, "\n").replace(FORMFEED_R, "").replace(TAB_R, " ");
30
+ };
31
+ var populateInitialState = function (givenState, defaultState) {
32
+ var state = givenState || {};
33
+ if (defaultState != null) {
34
+ for (var prop in defaultState) {
35
+ if (Object.prototype.hasOwnProperty.call(defaultState, prop)) {
36
+ state[prop] = defaultState[prop];
37
+ }
38
+ }
39
+ }
40
+ return state;
41
+ };
42
+
43
+ /**
44
+ * Creates a parser for a given set of rules, with the precedence
45
+ * specified as a list of rules.
46
+ *
47
+ * @param {SimpleMarkdown.ParserRules} rules
48
+ * an object containing
49
+ * rule type -> {match, order, parse} objects
50
+ * (lower order is higher precedence)
51
+ * @param {SimpleMarkdown.OptionalState} [defaultState]
52
+ *
53
+ * @returns {SimpleMarkdown.Parser}
54
+ * The resulting parse function, with the following parameters:
55
+ * @source: the input source string to be parsed
56
+ * @state: an optional object to be threaded through parse
57
+ * calls. Allows clients to add stateful operations to
58
+ * parsing, such as keeping track of how many levels deep
59
+ * some nesting is. For an example use-case, see passage-ref
60
+ * parsing in src/widgets/passage/passage-markdown.jsx
61
+ */
62
+ var parserFor = function (rules, defaultState) {
63
+ // Sorts rules in order of increasing order, then
64
+ // ascending rule name in case of ties.
65
+ var ruleList = Object.keys(rules).filter(function (type) {
66
+ var rule = rules[type];
67
+ if (rule == null || rule.match == null) {
68
+ return false;
69
+ }
70
+ var order = rule.order;
71
+ if ((typeof order !== "number" || !isFinite(order)) && typeof console !== "undefined") {
72
+ console.warn("simple-markdown: Invalid order for rule `" + type + "`: " + String(order));
73
+ }
74
+ return true;
75
+ });
76
+ ruleList.sort(function (typeA, typeB) {
77
+ var ruleA = rules[typeA];
78
+ var ruleB = rules[typeB];
79
+ var orderA = ruleA.order;
80
+ var orderB = ruleB.order;
81
+
82
+ // First sort based on increasing order
83
+ if (orderA !== orderB) {
84
+ return orderA - orderB;
85
+ }
86
+ var secondaryOrderA = ruleA.quality ? 0 : 1;
87
+ var secondaryOrderB = ruleB.quality ? 0 : 1;
88
+ if (secondaryOrderA !== secondaryOrderB) {
89
+ return secondaryOrderA - secondaryOrderB;
90
+
91
+ // Then based on increasing unicode lexicographic ordering
92
+ } else if (typeA < typeB) {
93
+ return -1;
94
+ } else if (typeA > typeB) {
95
+ return 1;
96
+ } else {
97
+ // Rules should never have the same name,
98
+ // but this is provided for completeness.
99
+ return 0;
100
+ }
101
+ });
102
+ var latestState;
103
+ var nestedParse = function (source, state) {
104
+ var result = [];
105
+ state = state || latestState;
106
+ latestState = state;
107
+ while (source) {
108
+ // store the best match, it's rule, and quality:
109
+ var ruleType = null;
110
+ var rule = null;
111
+ var capture = null;
112
+ var quality = NaN;
113
+
114
+ // loop control variables:
115
+ var i = 0;
116
+ var currRuleType = ruleList[0];
117
+ var currRule = rules[currRuleType];
118
+ do {
119
+ var currOrder = currRule.order;
120
+ var prevCaptureStr = state.prevCapture == null ? "" : state.prevCapture[0];
121
+ var currCapture = currRule.match(source, state, prevCaptureStr);
122
+ if (currCapture) {
123
+ var currQuality = currRule.quality ? currRule.quality(currCapture, state, prevCaptureStr) : 0;
124
+ // This should always be true the first time because
125
+ // the initial quality is NaN (that's why there's the
126
+ // condition negation).
127
+ if (!(currQuality <= quality)) {
128
+ // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
129
+ ruleType = currRuleType;
130
+ // @ts-expect-error - TS2322 - Type 'ParserRule' is not assignable to type 'null'.
131
+ rule = currRule;
132
+ // @ts-expect-error - TS2322 - Type 'Capture' is not assignable to type 'null'.
133
+ capture = currCapture;
134
+ quality = currQuality;
135
+ }
136
+ }
137
+
138
+ // Move on to the next item.
139
+ // Note that this makes `currRule` be the next item
140
+ i++;
141
+ currRuleType = ruleList[i];
142
+ currRule = rules[currRuleType];
143
+ } while (
144
+ // keep looping while we're still within the ruleList
145
+ currRule && (
146
+ // if we don't have a match yet, continue
147
+ !capture ||
148
+ // or if we have a match, but the next rule is
149
+ // at the same order, and has a quality measurement
150
+ // functions, then this rule must have a quality
151
+ // measurement function (since they are sorted before
152
+ // those without), and we need to check if there is
153
+ // a better quality match
154
+ currRule.order === currOrder && currRule.quality));
155
+
156
+ // TODO(aria): Write tests for these
157
+ if (rule == null || capture == null) {
158
+ throw new Error("Could not find a matching rule for the below " + "content. The rule with highest `order` should " + "always match content provided to it. Check " + "the definition of `match` for '" + ruleList[ruleList.length - 1] + "'. It seems to not match the following source:\n" + source);
159
+ }
160
+ // @ts-expect-error - TS2339 - Property 'index' does not exist on type 'never'.
161
+ if (capture.index) {
162
+ // If present and non-zero, i.e. a non-^ regexp result:
163
+ throw new Error("`match` must return a capture starting at index 0 " + "(the current parse index). Did you forget a ^ at the " + "start of the RegExp?");
164
+ }
165
+
166
+ // @ts-expect-error - TS2339 - Property 'parse' does not exist on type 'never'.
167
+ var parsed = rule.parse(capture, nestedParse, state);
168
+ // We maintain the same object here so that rules can
169
+ // store references to the objects they return and
170
+ // modify them later. (oops sorry! but this adds a lot
171
+ // of power--see reflinks.)
172
+ if (Array.isArray(parsed)) {
173
+ Array.prototype.push.apply(result, parsed);
174
+ } else {
175
+ if (parsed == null || typeof parsed !== "object") {
176
+ throw new Error(`parse() function returned invalid parse result: '${parsed}'`);
177
+ }
178
+
179
+ // We also let rules override the default type of
180
+ // their parsed node if they would like to, so that
181
+ // there can be a single output function for all links,
182
+ // even if there are several rules to parse them.
183
+ if (parsed.type == null) {
184
+ parsed.type = ruleType;
185
+ }
186
+ result.push(parsed);
187
+ }
188
+ state.prevCapture = capture;
189
+ source = source.substring(state.prevCapture[0].length);
190
+ }
191
+ return result;
192
+ };
193
+ var outerParse = function (source, state) {
194
+ latestState = populateInitialState(state, defaultState);
195
+ if (!latestState.inline && !latestState.disableAutoBlockNewlines) {
196
+ source = source + "\n\n";
197
+ }
198
+ // We store the previous capture so that match functions can
199
+ // use some limited amount of lookbehind. Lists use this to
200
+ // ensure they don't match arbitrary '- ' or '* ' in inline
201
+ // text (see the list rule for more information). This stores
202
+ // the full regex capture object, if there is one.
203
+ latestState.prevCapture = null;
204
+ return nestedParse(preprocess(source), latestState);
205
+ };
206
+ return outerParse;
207
+ };
208
+
209
+ // Creates a match function for an inline scoped element from a regex
210
+ var inlineRegex = function (regex) {
211
+ var match = function (source, state, prevCapture) {
212
+ if (state.inline) {
213
+ return regex.exec(source);
214
+ } else {
215
+ return null;
216
+ }
217
+ };
218
+ // @ts-expect-error - TS2339 - Property 'regex' does not exist on type '(source: string, state: State, prevCapture: string) => Capture | null | undefined'.
219
+ match.regex = regex;
220
+ return match;
221
+ };
222
+
223
+ // Creates a match function for a block scoped element from a regex
224
+ var blockRegex = function (regex) {
225
+ var match = function (source, state) {
226
+ if (state.inline) {
227
+ return null;
228
+ } else {
229
+ return regex.exec(source);
230
+ }
231
+ };
232
+ match.regex = regex;
233
+ return match;
234
+ };
235
+
236
+ // Creates a match function from a regex, ignoring block/inline scope
237
+ var anyScopeRegex = function (regex) {
238
+ var match = function (source, state) {
239
+ return regex.exec(source);
240
+ };
241
+ match.regex = regex;
242
+ return match;
243
+ };
244
+ var TYPE_SYMBOL = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7;
245
+ var reactElement = function (type, key, props) {
246
+ var element = {
247
+ $$typeof: TYPE_SYMBOL,
248
+ type: type,
249
+ key: key == null ? undefined : key,
250
+ ref: null,
251
+ props: props,
252
+ _owner: null
253
+ };
254
+ return element;
255
+ };
256
+
257
+ /** Returns a closed HTML tag.
258
+ * @param {string} tagName - Name of HTML tag (eg. "em" or "a")
259
+ * @param {string} content - Inner content of tag
260
+ * @param {{ [attr: string]: SimpleMarkdown.Attr }} [attributes] - Optional extra attributes of tag as an object of key-value pairs
261
+ * eg. { "href": "http://google.com" }. Falsey attributes are filtered out.
262
+ * @param {boolean} [isClosed] - boolean that controls whether tag is closed or not (eg. img tags).
263
+ * defaults to true
264
+ */
265
+ var htmlTag = function (tagName, content, attributes, isClosed) {
266
+ attributes = attributes || {};
267
+ isClosed = typeof isClosed !== "undefined" ? isClosed : true;
268
+ var attributeString = "";
269
+ for (var attr in attributes) {
270
+ var attribute = attributes[attr];
271
+ // Removes falsey attributes
272
+ if (Object.prototype.hasOwnProperty.call(attributes, attr) && attribute) {
273
+ attributeString += " " + sanitizeText(attr) + '="' + sanitizeText(attribute) + '"';
274
+ }
275
+ }
276
+ var unclosedTag = "<" + tagName + attributeString + ">";
277
+ if (isClosed) {
278
+ return unclosedTag + content + "</" + tagName + ">";
279
+ } else {
280
+ return unclosedTag;
281
+ }
282
+ };
283
+ var EMPTY_PROPS = {};
284
+
285
+ /**
286
+ * @param {string | null | undefined} url - url to sanitize
287
+ * @returns {string | null} - url if safe, or null if a safe url could not be made
288
+ */
289
+ var sanitizeUrl = function (url) {
290
+ if (url == null) {
291
+ return null;
292
+ }
293
+ try {
294
+ var prot = new URL(url, "https://localhost").protocol;
295
+ if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) {
296
+ return null;
297
+ }
298
+ } catch (e) {
299
+ // invalid URLs should throw a TypeError
300
+ // see for instance: `new URL("");`
301
+ return null;
302
+ }
303
+ return url;
304
+ };
305
+ var SANITIZE_TEXT_R = /[<>&"']/g;
306
+ var SANITIZE_TEXT_CODES = {
307
+ "<": "&lt;",
308
+ ">": "&gt;",
309
+ "&": "&amp;",
310
+ '"': "&quot;",
311
+ "'": "&#x27;",
312
+ "/": "&#x2F;",
313
+ "`": "&#96;"
314
+ };
315
+ var sanitizeText = function (text) {
316
+ return String(text).replace(SANITIZE_TEXT_R, function (chr) {
317
+ return SANITIZE_TEXT_CODES[chr];
318
+ });
319
+ };
320
+ var UNESCAPE_URL_R = /\\([^0-9A-Za-z\s])/g;
321
+ var unescapeUrl = function (rawUrlString) {
322
+ return rawUrlString.replace(UNESCAPE_URL_R, "$1");
323
+ };
324
+
325
+ /**
326
+ * Parse some content with the parser `parse`, with state.inline
327
+ * set to true. Useful for block elements; not generally necessary
328
+ * to be used by inline elements (where state.inline is already true.
329
+ */
330
+ var parseInline = function (parse, content, state) {
331
+ var isCurrentlyInline = state.inline || false;
332
+ state.inline = true;
333
+ var result = parse(content, state);
334
+ state.inline = isCurrentlyInline;
335
+ return result;
336
+ };
337
+ var parseBlock = function (parse, content, state) {
338
+ var isCurrentlyInline = state.inline || false;
339
+ state.inline = false;
340
+ var result = parse(content + "\n\n", state);
341
+ state.inline = isCurrentlyInline;
342
+ return result;
343
+ };
344
+ var parseCaptureInline = function (capture, parse, state) {
345
+ return {
346
+ content: parseInline(parse, capture[1], state)
347
+ };
348
+ };
349
+ var ignoreCapture = function () {
350
+ return {};
351
+ };
352
+
353
+ // recognize a `*` `-`, `+`, `1.`, `2.`... list bullet
354
+ var LIST_BULLET = "(?:[*+-]|\\d+\\.)";
355
+ // recognize the start of a list item:
356
+ // leading space plus a bullet plus a space (` * `)
357
+ var LIST_ITEM_PREFIX = "( *)(" + LIST_BULLET + ") +";
358
+ var LIST_ITEM_PREFIX_R = new RegExp("^" + LIST_ITEM_PREFIX);
359
+ // recognize an individual list item:
360
+ // * hi
361
+ // this is part of the same item
362
+ //
363
+ // as is this, which is a new paragraph in the same item
364
+ //
365
+ // * but this is not part of the same item
366
+ var LIST_ITEM_R = new RegExp(LIST_ITEM_PREFIX + "[^\\n]*(?:\\n" + "(?!\\1" + LIST_BULLET + " )[^\\n]*)*(\n|$)", "gm");
367
+ var BLOCK_END_R = /\n{2,}$/;
368
+ var INLINE_CODE_ESCAPE_BACKTICKS_R = /^ (?= *`)|(` *) $/g;
369
+ // recognize the end of a paragraph block inside a list item:
370
+ // two or more newlines at end end of the item
371
+ var LIST_BLOCK_END_R = BLOCK_END_R;
372
+ var LIST_ITEM_END_R = / *\n+$/;
373
+ // check whether a list item has paragraphs: if it does,
374
+ // we leave the newlines at the end
375
+ var LIST_R = new RegExp("^( *)(" + LIST_BULLET + ") " + "[\\s\\S]+?(?:\n{2,}(?! )" + "(?!\\1" + LIST_BULLET + " )\\n*" +
376
+ // the \\s*$ here is so that we can parse the inside of nested
377
+ // lists, where our content might end before we receive two `\n`s
378
+ "|\\s*\n*$)");
379
+ var LIST_LOOKBEHIND_R = /(?:^|\n)( *)$/;
380
+ var TABLES = function () {
381
+ var TABLE_ROW_SEPARATOR_TRIM = /^ *\| *| *\| *$/g;
382
+ var TABLE_CELL_END_TRIM = / *$/;
383
+ var TABLE_RIGHT_ALIGN = /^ *-+: *$/;
384
+ var TABLE_CENTER_ALIGN = /^ *:-+: *$/;
385
+ var TABLE_LEFT_ALIGN = /^ *:-+ *$/;
386
+
387
+ // TODO: This needs a real type
388
+
389
+ var parseTableAlignCapture = function (alignCapture) {
390
+ if (TABLE_RIGHT_ALIGN.test(alignCapture)) {
391
+ return "right";
392
+ } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {
393
+ return "center";
394
+ } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {
395
+ return "left";
396
+ } else {
397
+ return null;
398
+ }
399
+ };
400
+ var parseTableAlign = function (source, parse, state, trimEndSeparators) {
401
+ if (trimEndSeparators) {
402
+ source = source.replace(TABLE_ROW_SEPARATOR_TRIM, "");
403
+ }
404
+ var alignText = source.trim().split("|");
405
+ return alignText.map(parseTableAlignCapture);
406
+ };
407
+ var parseTableRow = function (source, parse, state, trimEndSeparators) {
408
+ var prevInTable = state.inTable;
409
+ state.inTable = true;
410
+ var tableRow = parse(source.trim(), state);
411
+ state.inTable = prevInTable;
412
+ var cells = [[]];
413
+ tableRow.forEach(function (node, i) {
414
+ if (node.type === "tableSeparator") {
415
+ // Filter out empty table separators at the start/end:
416
+ if (!trimEndSeparators || i !== 0 && i !== tableRow.length - 1) {
417
+ // Split the current row:
418
+ cells.push([]);
419
+ }
420
+ } else {
421
+ if (node.type === "text" && (tableRow[i + 1] == null || tableRow[i + 1].type === "tableSeparator")) {
422
+ node.content = node.content.replace(TABLE_CELL_END_TRIM, "");
423
+ }
424
+ // @ts-expect-error - TS2345 - Argument of type 'SingleASTNode' is not assignable to parameter of type 'never'.
425
+ cells[cells.length - 1].push(node);
426
+ }
427
+ });
428
+ return cells;
429
+ };
430
+
431
+ /**
432
+ * @param {string} source
433
+ * @param {SimpleMarkdown.Parser} parse
434
+ * @param {SimpleMarkdown.State} state
435
+ * @param {boolean} trimEndSeparators
436
+ * @returns {SimpleMarkdown.ASTNode[][]}
437
+ */
438
+ var parseTableCells = function (source, parse, state, trimEndSeparators) {
439
+ var rowsText = source.trim().split("\n");
440
+ return rowsText.map(function (rowText) {
441
+ return parseTableRow(rowText, parse, state, trimEndSeparators);
442
+ });
443
+ };
444
+
445
+ /**
446
+ * @param {boolean} trimEndSeparators
447
+ * @returns {SimpleMarkdown.SingleNodeParseFunction}
448
+ */
449
+ var parseTable = function (trimEndSeparators) {
450
+ return function (capture, parse, state) {
451
+ state.inline = true;
452
+ var header = parseTableRow(capture[1], parse, state, trimEndSeparators);
453
+ var align = parseTableAlign(capture[2], parse, state, trimEndSeparators);
454
+ var cells = parseTableCells(capture[3], parse, state, trimEndSeparators);
455
+ state.inline = false;
456
+ return {
457
+ type: "table",
458
+ header: header,
459
+ align: align,
460
+ cells: cells
461
+ };
462
+ };
463
+ };
464
+ return {
465
+ parseTable: parseTable(true),
466
+ parseNpTable: parseTable(false),
467
+ TABLE_REGEX: /^ *(\|.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/,
468
+ NPTABLE_REGEX: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/
469
+ };
470
+ }();
471
+ var LINK_INSIDE = "(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*";
472
+ var LINK_HREF_AND_TITLE = "\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*";
473
+ var AUTOLINK_MAILTO_CHECK_R = /mailto:/i;
474
+ var parseRef = function (capture, state, refNode) {
475
+ var ref = (capture[2] || capture[1]).replace(/\s+/g, " ").toLowerCase();
476
+
477
+ // We store information about previously seen defs on
478
+ // state._defs (_ to deconflict with client-defined
479
+ // state). If the def for this reflink/refimage has
480
+ // already been seen, we can use its target/source
481
+ // and title here:
482
+ if (state._defs && state._defs[ref]) {
483
+ var def = state._defs[ref];
484
+ // `refNode` can be a link or an image. Both use
485
+ // target and title properties.
486
+ refNode.target = def.target;
487
+ refNode.title = def.title;
488
+ }
489
+
490
+ // In case we haven't seen our def yet (or if someone
491
+ // overwrites that def later on), we add this node
492
+ // to the list of ref nodes for that def. Then, when
493
+ // we find the def, we can modify this link/image AST
494
+ // node :).
495
+ // I'm sorry.
496
+ state._refs = state._refs || {};
497
+ state._refs[ref] = state._refs[ref] || [];
498
+ state._refs[ref].push(refNode);
499
+ return refNode;
500
+ };
501
+ var currOrder = 0;
502
+ var defaultRules = {
503
+ Array: {
504
+ react: function (arr, output, state) {
505
+ var oldKey = state.key;
506
+ var result = [];
507
+
508
+ // map output over the ast, except group any text
509
+ // nodes together into a single string output.
510
+ for (var i = 0, key = 0; i < arr.length; i++, key++) {
511
+ // `key` is our numerical `state.key`, which we increment for
512
+ // every output node, but don't change for joined text nodes.
513
+ // (i, however, must change for joined text nodes)
514
+ state.key = "" + i;
515
+ var node = arr[i];
516
+ if (node.type === "text") {
517
+ node = {
518
+ type: "text",
519
+ content: node.content
520
+ };
521
+ for (; i + 1 < arr.length && arr[i + 1].type === "text"; i++) {
522
+ node.content += arr[i + 1].content;
523
+ }
524
+ }
525
+ result.push(output(node, state));
526
+ }
527
+ state.key = oldKey;
528
+ return result;
529
+ },
530
+ html: function (arr, output, state) {
531
+ var result = "";
532
+
533
+ // map output over the ast, except group any text
534
+ // nodes together into a single string output.
535
+ for (var i = 0; i < arr.length; i++) {
536
+ var node = arr[i];
537
+ if (node.type === "text") {
538
+ node = {
539
+ type: "text",
540
+ content: node.content
541
+ };
542
+ for (; i + 1 < arr.length && arr[i + 1].type === "text"; i++) {
543
+ node.content += arr[i + 1].content;
544
+ }
545
+ }
546
+ result += output(node, state);
547
+ }
548
+ return result;
549
+ }
550
+ },
551
+ heading: {
552
+ order: currOrder++,
553
+ match: blockRegex(/^ *(#{1,6})([^\n]+?)#* *(?:\n *)+\n/),
554
+ parse: function (capture, parse, state) {
555
+ return {
556
+ level: capture[1].length,
557
+ content: parseInline(parse, capture[2].trim(), state)
558
+ };
559
+ },
560
+ react: function (node, output, state) {
561
+ return reactElement("h" + node.level, state.key, {
562
+ children: output(node.content, state)
563
+ });
564
+ },
565
+ html: function (node, output, state) {
566
+ return htmlTag("h" + node.level, output(node.content, state));
567
+ }
568
+ },
569
+ nptable: {
570
+ order: currOrder++,
571
+ match: blockRegex(TABLES.NPTABLE_REGEX),
572
+ parse: TABLES.parseNpTable,
573
+ react: null,
574
+ html: null
575
+ },
576
+ lheading: {
577
+ order: currOrder++,
578
+ match: blockRegex(/^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/),
579
+ parse: function (capture, parse, state) {
580
+ return {
581
+ type: "heading",
582
+ level: capture[2] === "=" ? 1 : 2,
583
+ content: parseInline(parse, capture[1], state)
584
+ };
585
+ },
586
+ react: null,
587
+ html: null
588
+ },
589
+ hr: {
590
+ order: currOrder++,
591
+ match: blockRegex(/^( *[-*_]){3,} *(?:\n *)+\n/),
592
+ parse: ignoreCapture,
593
+ react: function (node, output, state) {
594
+ return reactElement("hr", state.key, EMPTY_PROPS);
595
+ },
596
+ html: function (node, output, state) {
597
+ return "<hr>";
598
+ }
599
+ },
600
+ codeBlock: {
601
+ order: currOrder++,
602
+ match: blockRegex(/^(?: [^\n]+\n*)+(?:\n *)+\n/),
603
+ parse: function (capture, parse, state) {
604
+ var content = capture[0].replace(/^ /gm, "").replace(/\n+$/, "");
605
+ return {
606
+ lang: undefined,
607
+ content: content
608
+ };
609
+ },
610
+ react: function (node, output, state) {
611
+ var className = node.lang ? "markdown-code-" + node.lang : undefined;
612
+ return reactElement("pre", state.key, {
613
+ children: reactElement("code", null, {
614
+ className: className,
615
+ children: node.content
616
+ })
617
+ });
618
+ },
619
+ html: function (node, output, state) {
620
+ var className = node.lang ? "markdown-code-" + node.lang : undefined;
621
+ var codeBlock = htmlTag("code", sanitizeText(node.content), {
622
+ class: className
623
+ });
624
+ return htmlTag("pre", codeBlock);
625
+ }
626
+ },
627
+ fence: {
628
+ order: currOrder++,
629
+ match: blockRegex(/^ *(`{3,}|~{3,}) *(?:(\S+) *)?\n([\s\S]+?)\n?\1 *(?:\n *)+\n/),
630
+ parse: function (capture, parse, state) {
631
+ return {
632
+ type: "codeBlock",
633
+ lang: capture[2] || undefined,
634
+ content: capture[3]
635
+ };
636
+ },
637
+ react: null,
638
+ html: null
639
+ },
640
+ blockQuote: {
641
+ order: currOrder++,
642
+ match: blockRegex(/^( *>[^\n]+(\n[^\n]+)*\n*)+\n{2,}/),
643
+ parse: function (capture, parse, state) {
644
+ var content = capture[0].replace(/^ *> ?/gm, "");
645
+ return {
646
+ content: parse(content, state)
647
+ };
648
+ },
649
+ react: function (node, output, state) {
650
+ return reactElement("blockquote", state.key, {
651
+ children: output(node.content, state)
652
+ });
653
+ },
654
+ html: function (node, output, state) {
655
+ return htmlTag("blockquote", output(node.content, state));
656
+ }
657
+ },
658
+ list: {
659
+ order: currOrder++,
660
+ match: function (source, state) {
661
+ // We only want to break into a list if we are at the start of a
662
+ // line. This is to avoid parsing "hi * there" with "* there"
663
+ // becoming a part of a list.
664
+ // You might wonder, "but that's inline, so of course it wouldn't
665
+ // start a list?". You would be correct! Except that some of our
666
+ // lists can be inline, because they might be inside another list,
667
+ // in which case we can parse with inline scope, but need to allow
668
+ // nested lists inside this inline scope.
669
+ var prevCaptureStr = state.prevCapture == null ? "" : state.prevCapture[0];
670
+ var isStartOfLineCapture = LIST_LOOKBEHIND_R.exec(prevCaptureStr);
671
+ var isListBlock = state._list || !state.inline;
672
+ if (isStartOfLineCapture && isListBlock) {
673
+ source = isStartOfLineCapture[1] + source;
674
+ return LIST_R.exec(source);
675
+ } else {
676
+ return null;
677
+ }
678
+ },
679
+ parse: function (capture, parse, state) {
680
+ var bullet = capture[2];
681
+ var ordered = bullet.length > 1;
682
+ var start = ordered ? +bullet : undefined;
683
+ // @ts-expect-error - TS2322 - Type 'RegExpMatchArray | null' is not assignable to type 'string[]'.
684
+ var items = capture[0].replace(LIST_BLOCK_END_R, "\n").match(LIST_ITEM_R);
685
+
686
+ // We know this will match here, because of how the regexes are
687
+ // defined
688
+
689
+ var lastItemWasAParagraph = false;
690
+ var itemContent = items.map(function (item, i) {
691
+ // We need to see how far indented this item is:
692
+ var prefixCapture = LIST_ITEM_PREFIX_R.exec(item);
693
+ var space = prefixCapture ? prefixCapture[0].length : 0;
694
+ // And then we construct a regex to "unindent" the subsequent
695
+ // lines of the items by that amount:
696
+ var spaceRegex = new RegExp("^ {1," + space + "}", "gm");
697
+
698
+ // Before processing the item, we need a couple things
699
+ var content = item
700
+ // remove indents on trailing lines:
701
+ .replace(spaceRegex, "")
702
+ // remove the bullet:
703
+ .replace(LIST_ITEM_PREFIX_R, "");
704
+
705
+ // I'm not sur4 why this is necessary again?
706
+
707
+ // Handling "loose" lists, like:
708
+ //
709
+ // * this is wrapped in a paragraph
710
+ //
711
+ // * as is this
712
+ //
713
+ // * as is this
714
+ var isLastItem = i === items.length - 1;
715
+ var containsBlocks = content.indexOf("\n\n") !== -1;
716
+
717
+ // Any element in a list is a block if it contains multiple
718
+ // newlines. The last element in the list can also be a block
719
+ // if the previous item in the list was a block (this is
720
+ // because non-last items in the list can end with \n\n, but
721
+ // the last item can't, so we just "inherit" this property
722
+ // from our previous element).
723
+ var thisItemIsAParagraph = containsBlocks || isLastItem && lastItemWasAParagraph;
724
+ lastItemWasAParagraph = thisItemIsAParagraph;
725
+
726
+ // backup our state for restoration afterwards. We're going to
727
+ // want to set state._list to true, and state.inline depending
728
+ // on our list's looseness.
729
+ var oldStateInline = state.inline;
730
+ var oldStateList = state._list;
731
+ state._list = true;
732
+
733
+ // Parse inline if we're in a tight list, or block if we're in
734
+ // a loose list.
735
+ var adjustedContent;
736
+ if (thisItemIsAParagraph) {
737
+ state.inline = false;
738
+ adjustedContent = content.replace(LIST_ITEM_END_R, "\n\n");
739
+ } else {
740
+ state.inline = true;
741
+ adjustedContent = content.replace(LIST_ITEM_END_R, "");
742
+ }
743
+ var result = parse(adjustedContent, state);
744
+
745
+ // Restore our state before returning
746
+ state.inline = oldStateInline;
747
+ state._list = oldStateList;
748
+ return result;
749
+ });
750
+ return {
751
+ ordered: ordered,
752
+ start: start,
753
+ items: itemContent
754
+ };
755
+ },
756
+ react: function (node, output, state) {
757
+ var ListWrapper = node.ordered ? "ol" : "ul";
758
+ return reactElement(ListWrapper, state.key, {
759
+ start: node.start,
760
+ children: node.items.map(function (item, i) {
761
+ return reactElement("li", "" + i, {
762
+ children: output(item, state)
763
+ });
764
+ })
765
+ });
766
+ },
767
+ html: function (node, output, state) {
768
+ var listItems = node.items.map(function (item) {
769
+ return htmlTag("li", output(item, state));
770
+ }).join("");
771
+ var listTag = node.ordered ? "ol" : "ul";
772
+ var attributes = {
773
+ start: node.start
774
+ };
775
+ return htmlTag(listTag, listItems, attributes);
776
+ }
777
+ },
778
+ def: {
779
+ order: currOrder++,
780
+ // TODO(aria): This will match without a blank line before the next
781
+ // block element, which is inconsistent with most of the rest of
782
+ // simple-markdown.
783
+ match: blockRegex(/^ *\[([^\]]+)\]: *<?([^\s>]*)>?(?: +["(]([^\n]+)[")])? *\n(?: *\n)*/),
784
+ parse: function (capture, parse, state) {
785
+ var def = capture[1].replace(/\s+/g, " ").toLowerCase();
786
+ var target = capture[2];
787
+ var title = capture[3];
788
+
789
+ // Look for previous links/images using this def
790
+ // If any links/images using this def have already been declared,
791
+ // they will have added themselves to the state._refs[def] list
792
+ // (_ to deconflict with client-defined state). We look through
793
+ // that list of reflinks for this def, and modify those AST nodes
794
+ // with our newly found information now.
795
+ // Sorry :(.
796
+ if (state._refs && state._refs[def]) {
797
+ // `refNode` can be a link or an image
798
+ state._refs[def].forEach(function (refNode) {
799
+ refNode.target = target;
800
+ refNode.title = title;
801
+ });
802
+ }
803
+
804
+ // Add this def to our map of defs for any future links/images
805
+ // In case we haven't found any or all of the refs referring to
806
+ // this def yet, we add our def to the table of known defs, so
807
+ // that future reflinks can modify themselves appropriately with
808
+ // this information.
809
+ state._defs = state._defs || {};
810
+ state._defs[def] = {
811
+ target: target,
812
+ title: title
813
+ };
814
+
815
+ // return the relevant parsed information
816
+ // for debugging only.
817
+ return {
818
+ def: def,
819
+ target: target,
820
+ title: title
821
+ };
822
+ },
823
+ react: function () {
824
+ return null;
825
+ },
826
+ html: function () {
827
+ return "";
828
+ }
829
+ },
830
+ table: {
831
+ order: currOrder++,
832
+ match: blockRegex(TABLES.TABLE_REGEX),
833
+ parse: TABLES.parseTable,
834
+ react: function (node, output, state) {
835
+ var getStyle = function (colIndex) {
836
+ return node.align[colIndex] == null ? {} : {
837
+ textAlign: node.align[colIndex]
838
+ };
839
+ };
840
+ var headers = node.header.map(function (content, i) {
841
+ return reactElement("th", "" + i, {
842
+ style: getStyle(i),
843
+ scope: "col",
844
+ children: output(content, state)
845
+ });
846
+ });
847
+ var rows = node.cells.map(function (row, r) {
848
+ return reactElement("tr", "" + r, {
849
+ children: row.map(function (content, c) {
850
+ return reactElement("td", "" + c, {
851
+ style: getStyle(c),
852
+ children: output(content, state)
853
+ });
854
+ })
855
+ });
856
+ });
857
+ return reactElement("table", state.key, {
858
+ children: [reactElement("thead", "thead", {
859
+ children: reactElement("tr", null, {
860
+ children: headers
861
+ })
862
+ }), reactElement("tbody", "tbody", {
863
+ children: rows
864
+ })]
865
+ });
866
+ },
867
+ html: function (node, output, state) {
868
+ var getStyle = function (colIndex) {
869
+ return node.align[colIndex] == null ? "" : "text-align:" + node.align[colIndex] + ";";
870
+ };
871
+ var headers = node.header.map(function (content, i) {
872
+ return htmlTag("th", output(content, state), {
873
+ style: getStyle(i),
874
+ scope: "col"
875
+ });
876
+ }).join("");
877
+ var rows = node.cells.map(function (row) {
878
+ var cols = row.map(function (content, c) {
879
+ return htmlTag("td", output(content, state), {
880
+ style: getStyle(c)
881
+ });
882
+ }).join("");
883
+ return htmlTag("tr", cols);
884
+ }).join("");
885
+ var thead = htmlTag("thead", htmlTag("tr", headers));
886
+ var tbody = htmlTag("tbody", rows);
887
+ return htmlTag("table", thead + tbody);
888
+ }
889
+ },
890
+ newline: {
891
+ order: currOrder++,
892
+ match: blockRegex(/^(?:\n *)*\n/),
893
+ parse: ignoreCapture,
894
+ react: function (node, output, state) {
895
+ return "\n";
896
+ },
897
+ html: function (node, output, state) {
898
+ return "\n";
899
+ }
900
+ },
901
+ paragraph: {
902
+ order: currOrder++,
903
+ match: blockRegex(/^((?:[^\n]|\n(?! *\n))+)(?:\n *)+\n/),
904
+ parse: parseCaptureInline,
905
+ react: function (node, output, state) {
906
+ return reactElement("div", state.key, {
907
+ className: "paragraph",
908
+ children: output(node.content, state)
909
+ });
910
+ },
911
+ html: function (node, output, state) {
912
+ var attributes = {
913
+ class: "paragraph"
914
+ };
915
+ return htmlTag("div", output(node.content, state), attributes);
916
+ }
917
+ },
918
+ escape: {
919
+ order: currOrder++,
920
+ // We don't allow escaping numbers, letters, or spaces here so that
921
+ // backslashes used in plain text still get rendered. But allowing
922
+ // escaping anything else provides a very flexible escape mechanism,
923
+ // regardless of how this grammar is extended.
924
+ match: inlineRegex(/^\\([^0-9A-Za-z\s])/),
925
+ parse: function (capture, parse, state) {
926
+ return {
927
+ type: "text",
928
+ content: capture[1]
929
+ };
930
+ },
931
+ react: null,
932
+ html: null
933
+ },
934
+ tableSeparator: {
935
+ order: currOrder++,
936
+ match: function (source, state) {
937
+ if (!state.inTable) {
938
+ return null;
939
+ }
940
+ return /^ *\| */.exec(source);
941
+ },
942
+ parse: function () {
943
+ return {
944
+ type: "tableSeparator"
945
+ };
946
+ },
947
+ // These shouldn't be reached, but in case they are, be reasonable:
948
+ react: function () {
949
+ return " | ";
950
+ },
951
+ html: function () {
952
+ return " &vert; ";
953
+ }
954
+ },
955
+ autolink: {
956
+ order: currOrder++,
957
+ match: inlineRegex(/^<([^: >]+:\/[^ >]+)>/),
958
+ parse: function (capture, parse, state) {
959
+ return {
960
+ type: "link",
961
+ content: [{
962
+ type: "text",
963
+ content: capture[1]
964
+ }],
965
+ target: capture[1]
966
+ };
967
+ },
968
+ react: null,
969
+ html: null
970
+ },
971
+ mailto: {
972
+ order: currOrder++,
973
+ match: inlineRegex(/^<([^ >]+@[^ >]+)>/),
974
+ parse: function (capture, parse, state) {
975
+ var address = capture[1];
976
+ var target = capture[1];
977
+
978
+ // Check for a `mailto:` already existing in the link:
979
+ if (!AUTOLINK_MAILTO_CHECK_R.test(target)) {
980
+ target = "mailto:" + target;
981
+ }
982
+ return {
983
+ type: "link",
984
+ content: [{
985
+ type: "text",
986
+ content: address
987
+ }],
988
+ target: target
989
+ };
990
+ },
991
+ react: null,
992
+ html: null
993
+ },
994
+ url: {
995
+ order: currOrder++,
996
+ match: inlineRegex(/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/),
997
+ parse: function (capture, parse, state) {
998
+ return {
999
+ type: "link",
1000
+ content: [{
1001
+ type: "text",
1002
+ content: capture[1]
1003
+ }],
1004
+ target: capture[1],
1005
+ title: undefined
1006
+ };
1007
+ },
1008
+ react: null,
1009
+ html: null
1010
+ },
1011
+ link: {
1012
+ order: currOrder++,
1013
+ match: inlineRegex(new RegExp("^\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)")),
1014
+ parse: function (capture, parse, state) {
1015
+ var link = {
1016
+ content: parse(capture[1], state),
1017
+ target: unescapeUrl(capture[2]),
1018
+ title: capture[3]
1019
+ };
1020
+ return link;
1021
+ },
1022
+ react: function (node, output, state) {
1023
+ return reactElement("a", state.key, {
1024
+ href: sanitizeUrl(node.target),
1025
+ title: node.title,
1026
+ children: output(node.content, state)
1027
+ });
1028
+ },
1029
+ html: function (node, output, state) {
1030
+ var attributes = {
1031
+ href: sanitizeUrl(node.target),
1032
+ title: node.title
1033
+ };
1034
+ return htmlTag("a", output(node.content, state), attributes);
1035
+ }
1036
+ },
1037
+ image: {
1038
+ order: currOrder++,
1039
+ match: inlineRegex(new RegExp("^!\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)")),
1040
+ parse: function (capture, parse, state) {
1041
+ var image = {
1042
+ alt: capture[1],
1043
+ target: unescapeUrl(capture[2]),
1044
+ title: capture[3]
1045
+ };
1046
+ return image;
1047
+ },
1048
+ react: function (node, output, state) {
1049
+ return reactElement("img", state.key, {
1050
+ src: sanitizeUrl(node.target),
1051
+ alt: node.alt,
1052
+ title: node.title
1053
+ });
1054
+ },
1055
+ html: function (node, output, state) {
1056
+ var attributes = {
1057
+ src: sanitizeUrl(node.target),
1058
+ alt: node.alt,
1059
+ title: node.title
1060
+ };
1061
+ return htmlTag("img", "", attributes, false);
1062
+ }
1063
+ },
1064
+ reflink: {
1065
+ order: currOrder++,
1066
+ match: inlineRegex(new RegExp(
1067
+ // The first [part] of the link
1068
+ "^\\[(" + LINK_INSIDE + ")\\]" +
1069
+ // The [ref] target of the link
1070
+ "\\s*\\[([^\\]]*)\\]")),
1071
+ parse: function (capture, parse, state) {
1072
+ return parseRef(capture, state, {
1073
+ type: "link",
1074
+ content: parse(capture[1], state)
1075
+ });
1076
+ },
1077
+ react: null,
1078
+ html: null
1079
+ },
1080
+ refimage: {
1081
+ order: currOrder++,
1082
+ match: inlineRegex(new RegExp(
1083
+ // The first [part] of the link
1084
+ "^!\\[(" + LINK_INSIDE + ")\\]" +
1085
+ // The [ref] target of the link
1086
+ "\\s*\\[([^\\]]*)\\]")),
1087
+ parse: function (capture, parse, state) {
1088
+ return parseRef(capture, state, {
1089
+ type: "image",
1090
+ alt: capture[1]
1091
+ });
1092
+ },
1093
+ react: null,
1094
+ html: null
1095
+ },
1096
+ em: {
1097
+ order: currOrder /* same as strong/u */,
1098
+ match: inlineRegex(new RegExp(
1099
+ // only match _s surrounding words.
1100
+ "^\\b_" + "((?:__|\\\\[\\s\\S]|[^\\\\_])+?)_" + "\\b" +
1101
+ // Or match *s:
1102
+ "|" +
1103
+ // Only match *s that are followed by a non-space:
1104
+ "^\\*(?=\\S)(" +
1105
+ // Match at least one of:
1106
+ "(?:" +
1107
+ // - `**`: so that bolds inside italics don't close the
1108
+ // italics
1109
+ "\\*\\*|" +
1110
+ // - escape sequence: so escaped *s don't close us
1111
+ "\\\\[\\s\\S]|" +
1112
+ // - whitespace: followed by a non-* (we don't
1113
+ // want ' *' to close an italics--it might
1114
+ // start a list)
1115
+ "\\s+(?:\\\\[\\s\\S]|[^\\s\\*\\\\]|\\*\\*)|" +
1116
+ // - non-whitespace, non-*, non-backslash characters
1117
+ "[^\\s\\*\\\\]" + ")+?" +
1118
+ // followed by a non-space, non-* then *
1119
+ ")\\*(?!\\*)")),
1120
+ quality: function (capture) {
1121
+ // precedence by length, `em` wins ties:
1122
+ return capture[0].length + 0.2;
1123
+ },
1124
+ parse: function (capture, parse, state) {
1125
+ return {
1126
+ content: parse(capture[2] || capture[1], state)
1127
+ };
1128
+ },
1129
+ react: function (node, output, state) {
1130
+ return reactElement("em", state.key, {
1131
+ children: output(node.content, state)
1132
+ });
1133
+ },
1134
+ html: function (node, output, state) {
1135
+ return htmlTag("em", output(node.content, state));
1136
+ }
1137
+ },
1138
+ strong: {
1139
+ order: currOrder /* same as em */,
1140
+ match: inlineRegex(/^\*\*((?:\\[\s\S]|[^\\])+?)\*\*(?!\*)/),
1141
+ quality: function (capture) {
1142
+ // precedence by length, wins ties vs `u`:
1143
+ return capture[0].length + 0.1;
1144
+ },
1145
+ parse: parseCaptureInline,
1146
+ react: function (node, output, state) {
1147
+ return reactElement("strong", state.key, {
1148
+ children: output(node.content, state)
1149
+ });
1150
+ },
1151
+ html: function (node, output, state) {
1152
+ return htmlTag("strong", output(node.content, state));
1153
+ }
1154
+ },
1155
+ u: {
1156
+ order: currOrder++ /* same as em&strong; increment for next rule */,
1157
+ match: inlineRegex(/^__((?:\\[\s\S]|[^\\])+?)__(?!_)/),
1158
+ quality: function (capture) {
1159
+ // precedence by length, loses all ties
1160
+ return capture[0].length;
1161
+ },
1162
+ parse: parseCaptureInline,
1163
+ react: function (node, output, state) {
1164
+ return reactElement("u", state.key, {
1165
+ children: output(node.content, state)
1166
+ });
1167
+ },
1168
+ html: function (node, output, state) {
1169
+ return htmlTag("u", output(node.content, state));
1170
+ }
1171
+ },
1172
+ del: {
1173
+ order: currOrder++,
1174
+ match: inlineRegex(/^~~(?=\S)((?:\\[\s\S]|~(?!~)|[^\s~\\]|\s(?!~~))+?)~~/),
1175
+ parse: parseCaptureInline,
1176
+ react: function (node, output, state) {
1177
+ return reactElement("del", state.key, {
1178
+ children: output(node.content, state)
1179
+ });
1180
+ },
1181
+ html: function (node, output, state) {
1182
+ return htmlTag("del", output(node.content, state));
1183
+ }
1184
+ },
1185
+ inlineCode: {
1186
+ order: currOrder++,
1187
+ match: inlineRegex(/^(`+)([\s\S]*?[^`])\1(?!`)/),
1188
+ parse: function (capture, parse, state) {
1189
+ return {
1190
+ content: capture[2].replace(INLINE_CODE_ESCAPE_BACKTICKS_R, "$1")
1191
+ };
1192
+ },
1193
+ react: function (node, output, state) {
1194
+ return reactElement("code", state.key, {
1195
+ children: node.content
1196
+ });
1197
+ },
1198
+ html: function (node, output, state) {
1199
+ return htmlTag("code", sanitizeText(node.content));
1200
+ }
1201
+ },
1202
+ br: {
1203
+ order: currOrder++,
1204
+ match: anyScopeRegex(/^ {2,}\n/),
1205
+ parse: ignoreCapture,
1206
+ react: function (node, output, state) {
1207
+ return reactElement("br", state.key, EMPTY_PROPS);
1208
+ },
1209
+ html: function (node, output, state) {
1210
+ return "<br>";
1211
+ }
1212
+ },
1213
+ text: {
1214
+ order: currOrder++,
1215
+ // Here we look for anything followed by non-symbols,
1216
+ // double newlines, or double-space-newlines
1217
+ // We break on any symbol characters so that this grammar
1218
+ // is easy to extend without needing to modify this regex
1219
+ match: anyScopeRegex(/^[\s\S]+?(?=[^0-9A-Za-z\s\u00c0-\uffff]|\n\n| {2,}\n|\w+:\S|$)/),
1220
+ parse: function (capture, parse, state) {
1221
+ return {
1222
+ content: capture[0]
1223
+ };
1224
+ },
1225
+ react: function (node, output, state) {
1226
+ return node.content;
1227
+ },
1228
+ html: function (node, output, state) {
1229
+ return sanitizeText(node.content);
1230
+ }
1231
+ }
1232
+ };
1233
+
1234
+ /** (deprecated) */
1235
+ var ruleOutput = function (rules, property) {
1236
+ if (!property && typeof console !== "undefined") {
1237
+ console.warn("simple-markdown ruleOutput should take 'react' or " + "'html' as the second argument.");
1238
+ }
1239
+ var nestedRuleOutput = function (ast, outputFunc, state) {
1240
+ // @ts-expect-error - TS2349 - This expression is not callable.
1241
+ // Type 'unknown' has no call signatures.
1242
+ return rules[ast.type][property](ast, outputFunc, state);
1243
+ };
1244
+ return nestedRuleOutput;
1245
+ };
1246
+
1247
+ /** (deprecated)
1248
+ */
1249
+ var reactFor = function (outputFunc) {
1250
+ var nestedOutput = function (ast, state) {
1251
+ state = state || {};
1252
+ if (Array.isArray(ast)) {
1253
+ var oldKey = state.key;
1254
+ var result = [];
1255
+
1256
+ // map nestedOutput over the ast, except group any text
1257
+ // nodes together into a single string output.
1258
+ var lastResult = null;
1259
+ for (var i = 0; i < ast.length; i++) {
1260
+ state.key = "" + i;
1261
+ var nodeOut = nestedOutput(ast[i], state);
1262
+ if (typeof nodeOut === "string" && typeof lastResult === "string") {
1263
+ // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
1264
+ lastResult = lastResult + nodeOut;
1265
+ result[result.length - 1] = lastResult;
1266
+ } else {
1267
+ result.push(nodeOut);
1268
+ // @ts-expect-error - TS2322 - Type 'ReactNode' is not assignable to type 'null'.
1269
+ lastResult = nodeOut;
1270
+ }
1271
+ }
1272
+ state.key = oldKey;
1273
+ return result;
1274
+ } else {
1275
+ return outputFunc(ast, nestedOutput, state);
1276
+ }
1277
+ };
1278
+ return nestedOutput;
1279
+ };
1280
+
1281
+ /** (deprecated)
1282
+ */
1283
+ var htmlFor = function (outputFunc) {
1284
+ var nestedOutput = function (ast, state) {
1285
+ state = state || {};
1286
+ if (Array.isArray(ast)) {
1287
+ return ast.map(function (node) {
1288
+ return nestedOutput(node, state);
1289
+ }).join("");
1290
+ } else {
1291
+ return outputFunc(ast, nestedOutput, state);
1292
+ }
1293
+ };
1294
+ return nestedOutput;
1295
+ };
1296
+ var outputFor = function (rules, property) {
1297
+ let defaultState = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1298
+ if (!property) {
1299
+ throw new Error("simple-markdown: outputFor: `property` must be " + "defined. " + "if you just upgraded, you probably need to replace `outputFor` " + "with `reactFor`");
1300
+ }
1301
+ var latestState;
1302
+ var arrayRule = rules.Array || defaultRules.Array;
1303
+
1304
+ // Tricks to convince tsc that this var is not null:
1305
+ // @ts-expect-error - TS2538 - Type 'symbol' cannot be used as an index type.
1306
+ var arrayRuleCheck = arrayRule[property];
1307
+ if (!arrayRuleCheck) {
1308
+ throw new Error("simple-markdown: outputFor: to join nodes of type `" +
1309
+ // @ts-expect-error - TS2469 - The '+' operator cannot be applied to type 'symbol'.
1310
+ property + "` you must provide an `Array:` joiner rule with that type, " + "Please see the docs for details on specifying an Array rule.");
1311
+ }
1312
+ var arrayRuleOutput = arrayRuleCheck;
1313
+ var nestedOutput = function (ast, state) {
1314
+ state = state || latestState;
1315
+ latestState = state;
1316
+ if (Array.isArray(ast)) {
1317
+ return arrayRuleOutput(ast, nestedOutput, state);
1318
+ } else {
1319
+ // @ts-expect-error - TS2349 - This expression is not callable.
1320
+ // Type 'unknown' has no call signatures.
1321
+ return rules[ast.type][property](ast, nestedOutput, state);
1322
+ }
1323
+ };
1324
+ var outerOutput = function (ast, state) {
1325
+ latestState = populateInitialState(state, defaultState);
1326
+ return nestedOutput(ast, latestState);
1327
+ };
1328
+ return outerOutput;
1329
+ };
1330
+
1331
+ // @ts-expect-error - TS2345 - Argument of type 'DefaultRules' is not assignable to parameter of type 'ParserRules'.
1332
+ var defaultRawParse = parserFor(defaultRules);
1333
+ var defaultBlockParse = function (source, state) {
1334
+ state = state || {};
1335
+ state.inline = false;
1336
+ return defaultRawParse(source, state);
1337
+ };
1338
+ var defaultInlineParse = function (source, state) {
1339
+ state = state || {};
1340
+ state.inline = true;
1341
+ return defaultRawParse(source, state);
1342
+ };
1343
+ var defaultImplicitParse = function (source, state) {
1344
+ var isBlock = BLOCK_END_R.test(source);
1345
+ state = state || {};
1346
+ state.inline = !isBlock;
1347
+ return defaultRawParse(source, state);
1348
+ };
1349
+ var defaultReactOutput = outputFor(defaultRules, "react");
1350
+ var defaultHtmlOutput = outputFor(defaultRules, "html");
1351
+ var markdownToReact = function (source, state) {
1352
+ return defaultReactOutput(defaultBlockParse(source, state), state);
1353
+ };
1354
+ var markdownToHtml = function (source, state) {
1355
+ return defaultHtmlOutput(defaultBlockParse(source, state), state);
1356
+ };
1357
+
1358
+ // TODO: This needs definition
1359
+
1360
+ var ReactMarkdown = function (props) {
1361
+ var divProps = {};
1362
+ for (var prop in props) {
1363
+ if (prop !== "source" && Object.prototype.hasOwnProperty.call(props, prop)) {
1364
+ divProps[prop] = props[prop];
1365
+ }
1366
+ }
1367
+ divProps.children = markdownToReact(props.source);
1368
+ return reactElement("div", null, divProps);
1369
+ };
1370
+ var SimpleMarkdown = {
1371
+ defaultRules: defaultRules,
1372
+ parserFor: parserFor,
1373
+ outputFor: outputFor,
1374
+ inlineRegex: inlineRegex,
1375
+ blockRegex: blockRegex,
1376
+ anyScopeRegex: anyScopeRegex,
1377
+ parseInline: parseInline,
1378
+ parseBlock: parseBlock,
1379
+ // default wrappers:
1380
+ markdownToReact: markdownToReact,
1381
+ markdownToHtml: markdownToHtml,
1382
+ ReactMarkdown: ReactMarkdown,
1383
+ defaultBlockParse: defaultBlockParse,
1384
+ defaultInlineParse: defaultInlineParse,
1385
+ defaultImplicitParse: defaultImplicitParse,
1386
+ defaultReactOutput: defaultReactOutput,
1387
+ defaultHtmlOutput: defaultHtmlOutput,
1388
+ preprocess: preprocess,
1389
+ sanitizeText: sanitizeText,
1390
+ sanitizeUrl: sanitizeUrl,
1391
+ unescapeUrl: unescapeUrl,
1392
+ htmlTag: htmlTag,
1393
+ reactElement: reactElement,
1394
+ // deprecated:
1395
+ defaultRawParse: defaultRawParse,
1396
+ ruleOutput: ruleOutput,
1397
+ reactFor: reactFor,
1398
+ htmlFor: htmlFor,
1399
+ defaultParse: function () {
1400
+ if (typeof console !== "undefined") {
1401
+ console.warn("defaultParse is deprecated, please use `defaultImplicitParse`");
1402
+ }
1403
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1404
+ args[_key] = arguments[_key];
1405
+ }
1406
+ return defaultImplicitParse.apply(null, args);
1407
+ },
1408
+ defaultOutput: function () {
1409
+ if (typeof console !== "undefined") {
1410
+ console.warn("defaultOutput is deprecated, please use `defaultReactOutput`");
1411
+ }
1412
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
1413
+ args[_key2] = arguments[_key2];
1414
+ }
1415
+ return defaultReactOutput.apply(null, args);
1416
+ }
1417
+ };
1418
+
1419
+ exports["default"] = SimpleMarkdown;
1420
+ exports.libVersion = libVersion;
1421
+ //# sourceMappingURL=index.js.map