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