@khanacademy/perseus-linter 0.0.0-PR443-20230328215601

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.eslintrc.js +12 -0
  2. package/CHANGELOG.md +68 -0
  3. package/dist/es/index.js +1841 -0
  4. package/dist/es/index.js.map +1 -0
  5. package/dist/index.js +1835 -0
  6. package/dist/index.js.map +1 -0
  7. package/package.json +34 -0
  8. package/src/README.md +41 -0
  9. package/src/__tests__/matcher.test.ts +498 -0
  10. package/src/__tests__/rule.test.ts +110 -0
  11. package/src/__tests__/rules.test.ts +548 -0
  12. package/src/__tests__/selector-parser.test.ts +51 -0
  13. package/src/__tests__/tree-transformer.test.ts +444 -0
  14. package/src/index.ts +279 -0
  15. package/src/proptypes.ts +19 -0
  16. package/src/rule.ts +419 -0
  17. package/src/rules/absolute-url.ts +23 -0
  18. package/src/rules/all-rules.ts +71 -0
  19. package/src/rules/blockquoted-math.ts +9 -0
  20. package/src/rules/blockquoted-widget.ts +9 -0
  21. package/src/rules/double-spacing-after-terminal.ts +11 -0
  22. package/src/rules/extra-content-spacing.ts +11 -0
  23. package/src/rules/heading-level-1.ts +13 -0
  24. package/src/rules/heading-level-skip.ts +19 -0
  25. package/src/rules/heading-sentence-case.ts +10 -0
  26. package/src/rules/heading-title-case.ts +68 -0
  27. package/src/rules/image-alt-text.ts +20 -0
  28. package/src/rules/image-in-table.ts +9 -0
  29. package/src/rules/image-spaces-around-urls.ts +34 -0
  30. package/src/rules/image-widget.ts +49 -0
  31. package/src/rules/link-click-here.ts +10 -0
  32. package/src/rules/lint-utils.ts +47 -0
  33. package/src/rules/long-paragraph.ts +13 -0
  34. package/src/rules/math-adjacent.ts +9 -0
  35. package/src/rules/math-align-extra-break.ts +10 -0
  36. package/src/rules/math-align-linebreaks.ts +42 -0
  37. package/src/rules/math-empty.ts +9 -0
  38. package/src/rules/math-font-size.ts +11 -0
  39. package/src/rules/math-frac.ts +9 -0
  40. package/src/rules/math-nested.ts +10 -0
  41. package/src/rules/math-starts-with-space.ts +11 -0
  42. package/src/rules/math-text-empty.ts +9 -0
  43. package/src/rules/math-without-dollars.ts +13 -0
  44. package/src/rules/nested-lists.ts +10 -0
  45. package/src/rules/profanity.ts +9 -0
  46. package/src/rules/table-missing-cells.ts +19 -0
  47. package/src/rules/unbalanced-code-delimiters.ts +13 -0
  48. package/src/rules/unescaped-dollar.ts +9 -0
  49. package/src/rules/widget-in-table.ts +9 -0
  50. package/src/selector.ts +504 -0
  51. package/src/tree-transformer.ts +587 -0
  52. package/src/types.ts +7 -0
  53. package/tsconfig.json +12 -0
@@ -0,0 +1,1841 @@
1
+ import { PerseusError, Errors } from '@khanacademy/perseus-error';
2
+ import PropTypes from 'prop-types';
3
+
4
+ function ownKeys(object, enumerableOnly) {
5
+ var keys = Object.keys(object);
6
+ if (Object.getOwnPropertySymbols) {
7
+ var symbols = Object.getOwnPropertySymbols(object);
8
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
9
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
10
+ })), keys.push.apply(keys, symbols);
11
+ }
12
+ return keys;
13
+ }
14
+ function _objectSpread2(target) {
15
+ for (var i = 1; i < arguments.length; i++) {
16
+ var source = null != arguments[i] ? arguments[i] : {};
17
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
18
+ _defineProperty(target, key, source[key]);
19
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
20
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
21
+ });
22
+ }
23
+ return target;
24
+ }
25
+ function _defineProperty(obj, key, value) {
26
+ key = _toPropertyKey(key);
27
+ if (key in obj) {
28
+ Object.defineProperty(obj, key, {
29
+ value: value,
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true
33
+ });
34
+ } else {
35
+ obj[key] = value;
36
+ }
37
+ return obj;
38
+ }
39
+ function _toPrimitive(input, hint) {
40
+ if (typeof input !== "object" || input === null) return input;
41
+ var prim = input[Symbol.toPrimitive];
42
+ if (prim !== undefined) {
43
+ var res = prim.call(input, hint || "default");
44
+ if (typeof res !== "object") return res;
45
+ throw new TypeError("@@toPrimitive must return a primitive value.");
46
+ }
47
+ return (hint === "string" ? String : Number)(input);
48
+ }
49
+ function _toPropertyKey(arg) {
50
+ var key = _toPrimitive(arg, "string");
51
+ return typeof key === "symbol" ? key : String(key);
52
+ }
53
+
54
+ /**
55
+ * This is the base class for all Selector types. The key method that all
56
+ * selector subclasses must implement is match(). It takes a TraversalState
57
+ * object (from a TreeTransformer traversal) and tests whether the selector
58
+ * matches at the current node. See the comment at the start of this file for
59
+ * more details on the match() method.
60
+ */
61
+ class Selector {
62
+ static parse(selectorText) {
63
+ return new Parser(selectorText).parse();
64
+ }
65
+
66
+ /**
67
+ * Return an array of the nodes that matched or null if no match.
68
+ * This is the base class so we just throw an exception. All Selector
69
+ * subclasses must provide an implementation of this method.
70
+ */
71
+ match(state) {
72
+ throw new PerseusError("Selector subclasses must implement match()", Errors.NotAllowed);
73
+ }
74
+
75
+ /**
76
+ * Selector subclasses all define a toString() method primarily
77
+ * because it makes it easy to write parser tests.
78
+ */
79
+ toString() {
80
+ return "Unknown selector class";
81
+ }
82
+ }
83
+
84
+ /**
85
+ * This class implements a parser for the selector grammar. Pass the source
86
+ * text to the Parser() constructor, and then call the parse() method to
87
+ * obtain a corresponding Selector object. parse() throws an exception
88
+ * if there are syntax errors in the selector.
89
+ *
90
+ * This class is not exported, and you don't need to use it directly.
91
+ * Instead call the static Selector.parse() method.
92
+ */
93
+ class Parser {
94
+ // We do lexing with a simple regular expression
95
+ // The array of tokens
96
+ // Which token in the array we're looking at now
97
+
98
+ constructor(s) {
99
+ _defineProperty(this, "tokens", void 0);
100
+ _defineProperty(this, "tokenIndex", void 0);
101
+ // Normalize whitespace:
102
+ // - remove leading and trailing whitespace
103
+ // - replace runs of whitespace with single space characters
104
+ s = s.trim().replace(/\s+/g, " ");
105
+ // Convert the string to an array of tokens. Note that the TOKENS
106
+ // pattern ignores spaces that do not appear before identifiers
107
+ // or the * wildcard.
108
+ this.tokens = s.match(Parser.TOKENS) || [];
109
+ this.tokenIndex = 0;
110
+ }
111
+
112
+ // Return the next token or the empty string if there are no more
113
+ nextToken() {
114
+ return this.tokens[this.tokenIndex] || "";
115
+ }
116
+
117
+ // Increment the token index to "consume" the token we were looking at
118
+ // and move on to the next one.
119
+ consume() {
120
+ this.tokenIndex++;
121
+ }
122
+
123
+ // Return true if the current token is an identifier or false otherwise
124
+ isIdentifier() {
125
+ // The Parser.TOKENS regexp ensures that we only have to check
126
+ // the first character of a token to know what kind of token it is.
127
+ var c = this.tokens[this.tokenIndex][0];
128
+ return c >= "a" && c <= "z" || c >= "A" && c <= "Z";
129
+ }
130
+
131
+ // Consume space tokens until the next token is not a space.
132
+ skipSpace() {
133
+ while (this.nextToken() === " ") {
134
+ this.consume();
135
+ }
136
+ }
137
+
138
+ // Parse a comma-separated sequence of tree selectors. This is the
139
+ // entry point for the Parser class and the only method that clients
140
+ // ever need to call.
141
+ parse() {
142
+ // We expect at least one tree selector
143
+ var ts = this.parseTreeSelector();
144
+
145
+ // Now see what's next
146
+ var token = this.nextToken();
147
+
148
+ // If there is no next token then we're done parsing and can return
149
+ // the tree selector object we got above
150
+ if (!token) {
151
+ return ts;
152
+ }
153
+
154
+ // Otherwise, there is more go come and we're going to need a
155
+ // list of tree selectors
156
+ var treeSelectors = [ts];
157
+ while (token) {
158
+ // The only character we allow after a tree selector is a comma
159
+ if (token === ",") {
160
+ this.consume();
161
+ } else {
162
+ throw new ParseError("Expected comma");
163
+ }
164
+
165
+ // And if we saw a comma, then it must be followed by another
166
+ // tree selector
167
+ treeSelectors.push(this.parseTreeSelector());
168
+ token = this.nextToken();
169
+ }
170
+
171
+ // If we parsed more than one tree selector, return them in a
172
+ // SelectorList object.
173
+ return new SelectorList(treeSelectors);
174
+ }
175
+
176
+ // Parse a sequence of node selectors linked together with
177
+ // hierarchy combinators: space, >, + and ~.
178
+ parseTreeSelector() {
179
+ this.skipSpace(); // Ignore space after a comma, for example
180
+
181
+ // A tree selector must begin with a node selector
182
+ var ns = this.parseNodeSelector();
183
+ for (;;) {
184
+ // Now check the next token. If there is none, or if it is a
185
+ // comma, then we're done with the treeSelector. Otherwise
186
+ // we expect a combinator followed by another node selector.
187
+ // If we don't see a combinator, we throw an error. If we
188
+ // do see a combinator and another node selector then we
189
+ // combine the current node selector with the new node selector
190
+ // using a Selector subclass that depends on the combinator.
191
+ var token = this.nextToken();
192
+ if (!token || token === ",") {
193
+ break;
194
+ } else if (token === " ") {
195
+ this.consume();
196
+ ns = new AncestorCombinator(ns, this.parseNodeSelector());
197
+ } else if (token === ">") {
198
+ this.consume();
199
+ ns = new ParentCombinator(ns, this.parseNodeSelector());
200
+ } else if (token === "+") {
201
+ this.consume();
202
+ ns = new PreviousCombinator(ns, this.parseNodeSelector());
203
+ } else if (token === "~") {
204
+ this.consume();
205
+ ns = new SiblingCombinator(ns, this.parseNodeSelector());
206
+ } else {
207
+ throw new ParseError("Unexpected token: " + token);
208
+ }
209
+ }
210
+ return ns;
211
+ }
212
+
213
+ // Parse a single node selector.
214
+ // For now, this is just a node type or a wildcard.
215
+ //
216
+ // TODO(davidflanagan): we may need to extend this with attribute
217
+ // selectors like 'heading[level=3]', or with pseudo-classes like
218
+ // paragraph:first-child
219
+ parseNodeSelector() {
220
+ // First, skip any whitespace
221
+ this.skipSpace();
222
+ var t = this.nextToken();
223
+ if (t === "*") {
224
+ this.consume();
225
+ return new AnyNode();
226
+ }
227
+ if (this.isIdentifier()) {
228
+ this.consume();
229
+ return new TypeSelector(t);
230
+ }
231
+ throw new ParseError("Expected node type");
232
+ }
233
+ }
234
+
235
+ // We break the input string into tokens with this regexp. Token types
236
+ // are identifiers, integers, punctuation and spaces. Note that spaces
237
+ // tokens are only returned when they appear before an identifier or
238
+ // wildcard token and are otherwise omitted.
239
+ _defineProperty(Parser, "TOKENS", void 0);
240
+ Parser.TOKENS = /([a-zA-Z][\w-]*)|(\d+)|[^\s]|(\s(?=[a-zA-Z\*]))/g;
241
+
242
+ /**
243
+ * This is a trivial Error subclass that the Parser uses to signal parse errors
244
+ */
245
+ class ParseError extends Error {
246
+ constructor(message) {
247
+ super(message);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * This Selector subclass is a list of selectors. It matches a node if any of
253
+ * the selectors on the list matches the node. It considers the selectors in
254
+ * order, and returns the array of nodes returned by whichever one matches
255
+ * first.
256
+ */
257
+ class SelectorList extends Selector {
258
+ constructor(selectors) {
259
+ super();
260
+ _defineProperty(this, "selectors", void 0);
261
+ this.selectors = selectors;
262
+ }
263
+ match(state) {
264
+ for (var i = 0; i < this.selectors.length; i++) {
265
+ var s = this.selectors[i];
266
+ var result = s.match(state);
267
+ if (result) {
268
+ return result;
269
+ }
270
+ }
271
+ return null;
272
+ }
273
+ toString() {
274
+ var result = "";
275
+ for (var i = 0; i < this.selectors.length; i++) {
276
+ result += i > 0 ? ", " : "";
277
+ result += this.selectors[i].toString();
278
+ }
279
+ return result;
280
+ }
281
+ }
282
+
283
+ /**
284
+ * This trivial Selector subclass implements the '*' wildcard and
285
+ * matches any node.
286
+ */
287
+ class AnyNode extends Selector {
288
+ match(state) {
289
+ return [state.currentNode()];
290
+ }
291
+ toString() {
292
+ return "*";
293
+ }
294
+ }
295
+
296
+ /**
297
+ * This selector subclass implements the <IDENTIFIER> part of the grammar.
298
+ * it matches any node whose `type` property is a specified string
299
+ */
300
+ class TypeSelector extends Selector {
301
+ constructor(type) {
302
+ super();
303
+ _defineProperty(this, "type", void 0);
304
+ this.type = type;
305
+ }
306
+ match(state) {
307
+ var node = state.currentNode();
308
+ if (node.type === this.type) {
309
+ return [node];
310
+ }
311
+ return null;
312
+ }
313
+ toString() {
314
+ return this.type;
315
+ }
316
+ }
317
+
318
+ /**
319
+ * This selector subclass is the superclass of the classes that implement
320
+ * matching for the four combinators. It defines left and right properties for
321
+ * the two selectors that are to be combined, but does not define a match
322
+ * method.
323
+ */
324
+ class SelectorCombinator extends Selector {
325
+ constructor(left, right) {
326
+ super();
327
+ _defineProperty(this, "left", void 0);
328
+ _defineProperty(this, "right", void 0);
329
+ this.left = left;
330
+ this.right = right;
331
+ }
332
+ }
333
+
334
+ /**
335
+ * This Selector subclass implements the space combinator. It matches if the
336
+ * right selector matches the current node and the left selector matches some
337
+ * ancestor of the current node.
338
+ */
339
+ class AncestorCombinator extends SelectorCombinator {
340
+ constructor(left, right) {
341
+ super(left, right);
342
+ }
343
+ match(state) {
344
+ var rightResult = this.right.match(state);
345
+ if (rightResult) {
346
+ state = state.clone();
347
+ while (state.hasParent()) {
348
+ state.goToParent();
349
+ var leftResult = this.left.match(state);
350
+ if (leftResult) {
351
+ return leftResult.concat(rightResult);
352
+ }
353
+ }
354
+ }
355
+ return null;
356
+ }
357
+ toString() {
358
+ return this.left.toString() + " " + this.right.toString();
359
+ }
360
+ }
361
+
362
+ /**
363
+ * This Selector subclass implements the > combinator. It matches if the
364
+ * right selector matches the current node and the left selector matches
365
+ * the parent of the current node.
366
+ */
367
+ class ParentCombinator extends SelectorCombinator {
368
+ constructor(left, right) {
369
+ super(left, right);
370
+ }
371
+ match(state) {
372
+ var rightResult = this.right.match(state);
373
+ if (rightResult) {
374
+ if (state.hasParent()) {
375
+ state = state.clone();
376
+ state.goToParent();
377
+ var leftResult = this.left.match(state);
378
+ if (leftResult) {
379
+ return leftResult.concat(rightResult);
380
+ }
381
+ }
382
+ }
383
+ return null;
384
+ }
385
+ toString() {
386
+ return this.left.toString() + " > " + this.right.toString();
387
+ }
388
+ }
389
+
390
+ /**
391
+ * This Selector subclass implements the + combinator. It matches if the
392
+ * right selector matches the current node and the left selector matches
393
+ * the immediate previous sibling of the current node.
394
+ */
395
+ class PreviousCombinator extends SelectorCombinator {
396
+ constructor(left, right) {
397
+ super(left, right);
398
+ }
399
+ match(state) {
400
+ var rightResult = this.right.match(state);
401
+ if (rightResult) {
402
+ if (state.hasPreviousSibling()) {
403
+ state = state.clone();
404
+ state.goToPreviousSibling();
405
+ var leftResult = this.left.match(state);
406
+ if (leftResult) {
407
+ return leftResult.concat(rightResult);
408
+ }
409
+ }
410
+ }
411
+ return null;
412
+ }
413
+ toString() {
414
+ return this.left.toString() + " + " + this.right.toString();
415
+ }
416
+ }
417
+
418
+ /**
419
+ * This Selector subclass implements the ~ combinator. It matches if the
420
+ * right selector matches the current node and the left selector matches
421
+ * any previous sibling of the current node.
422
+ */
423
+ class SiblingCombinator extends SelectorCombinator {
424
+ constructor(left, right) {
425
+ super(left, right);
426
+ }
427
+ match(state) {
428
+ var rightResult = this.right.match(state);
429
+ if (rightResult) {
430
+ state = state.clone();
431
+ while (state.hasPreviousSibling()) {
432
+ state.goToPreviousSibling();
433
+ var leftResult = this.left.match(state);
434
+ if (leftResult) {
435
+ return leftResult.concat(rightResult);
436
+ }
437
+ }
438
+ }
439
+ return null;
440
+ }
441
+ toString() {
442
+ return this.left.toString() + " ~ " + this.right.toString();
443
+ }
444
+ }
445
+
446
+ /**
447
+ * A Rule object describes a Perseus lint rule. See the comment at the top of
448
+ * this file for detailed description.
449
+ */
450
+ class Rule {
451
+ // The name of the rule
452
+ // The severity of the rule
453
+ // The specified selector or the DEFAULT_SELECTOR
454
+ // A regular expression if one was specified
455
+ // The lint-testing function or a default
456
+ // Checks to see if we should apply a rule or not
457
+ // The error message for use with the default function
458
+
459
+ // The comment at the top of this file has detailed docs for
460
+ // this constructor and its arguments
461
+ constructor(name, severity, selector, pattern, lint, applies) {
462
+ var _this = this;
463
+ _defineProperty(this, "name", void 0);
464
+ _defineProperty(this, "severity", void 0);
465
+ _defineProperty(this, "selector", void 0);
466
+ _defineProperty(this, "pattern", void 0);
467
+ _defineProperty(this, "lint", void 0);
468
+ _defineProperty(this, "applies", void 0);
469
+ _defineProperty(this, "message", void 0);
470
+ if (!selector && !pattern) {
471
+ throw new PerseusError("Lint rules must have a selector or pattern", Errors.InvalidInput, {
472
+ metadata: {
473
+ name
474
+ }
475
+ });
476
+ }
477
+ this.name = name || "unnamed rule";
478
+ this.severity = severity || Rule.Severity.BULK_WARNING;
479
+ this.selector = selector || Rule.DEFAULT_SELECTOR;
480
+ this.pattern = pattern || null;
481
+
482
+ // If we're called with an error message instead of a function then
483
+ // use a default function that will return the message.
484
+ if (typeof lint === "function") {
485
+ this.lint = lint;
486
+ this.message = null;
487
+ } else {
488
+ this.lint = function () {
489
+ return _this._defaultLintFunction(...arguments);
490
+ };
491
+ this.message = lint;
492
+ }
493
+ this.applies = applies || function () {
494
+ return true;
495
+ };
496
+ }
497
+
498
+ // A factory method for use with rules described in JSON files
499
+ // See the documentation at the start of this file for details.
500
+ static makeRule(options) {
501
+ return new Rule(options.name, options.severity, options.selector ? Selector.parse(options.selector) : null, Rule.makePattern(options.pattern), options.lint || options.message, options.applies);
502
+ }
503
+
504
+ // Check the node n to see if it violates this lint rule. A return value
505
+ // of false means there is no lint. A returned object indicates a lint
506
+ // error. See the documentation at the top of this file for details.
507
+ check(node, traversalState, content, context) {
508
+ // First, see if we match the selector.
509
+ // If no selector was passed to the constructor, we use a
510
+ // default selector that matches text nodes.
511
+ var selectorMatch = this.selector.match(traversalState);
512
+
513
+ // If the selector did not match, then we're done
514
+ if (!selectorMatch) {
515
+ return null;
516
+ }
517
+
518
+ // If the selector matched, then see if the pattern matches
519
+ var patternMatch;
520
+ if (this.pattern) {
521
+ patternMatch = content.match(this.pattern);
522
+ } else {
523
+ // If there is no pattern, then just match all of the content.
524
+ // Use a fake RegExp match object to represent this default match.
525
+ patternMatch = Rule.FakePatternMatch(content, content, 0);
526
+ }
527
+
528
+ // If there was a pattern and it didn't match, then we're done
529
+ if (!patternMatch) {
530
+ return null;
531
+ }
532
+ try {
533
+ // If we get here, then the selector and pattern have matched
534
+ // so now we call the lint function to see if there is lint.
535
+ var error = this.lint(traversalState, content, selectorMatch, patternMatch, context);
536
+ if (!error) {
537
+ return null; // No lint; we're done
538
+ }
539
+
540
+ if (typeof error === "string") {
541
+ // If the lint function returned a string we assume it
542
+ // applies to the entire content of the node and return it.
543
+ return {
544
+ rule: this.name,
545
+ severity: this.severity,
546
+ message: error,
547
+ start: 0,
548
+ end: content.length
549
+ };
550
+ }
551
+ // If the lint function returned an object, then we just
552
+ // add the rule name to the message, start and end.
553
+ return {
554
+ rule: this.name,
555
+ severity: this.severity,
556
+ message: error.message,
557
+ start: error.start,
558
+ end: error.end
559
+ };
560
+ } catch (e) {
561
+ // If the lint function threw an exception we handle that as
562
+ // a special type of lint. We want the user to see the lint
563
+ // warning in this case (even though it is out of their control)
564
+ // so that the bug gets reported. Otherwise we'd never know that
565
+ // a rule was failing.
566
+ return {
567
+ rule: "lint-rule-failure",
568
+ message: "Exception in rule ".concat(this.name, ": ").concat(e.message, "\nStack trace:\n").concat(e.stack),
569
+ start: 0,
570
+ end: content.length
571
+ };
572
+ }
573
+ }
574
+
575
+ // This internal method is the default lint function that we use when a
576
+ // rule is defined without a function. This is useful for rules where the
577
+ // selector and/or pattern match are enough to indicate lint. This
578
+ // function unconditionally returns the error message that was passed in
579
+ // place of a function, but also adds start and end properties that
580
+ // specify which particular portion of the node content matched the
581
+ // pattern.
582
+ _defaultLintFunction(state, content, selectorMatch, patternMatch, context) {
583
+ return {
584
+ message: this.message || "",
585
+ start: patternMatch.index,
586
+ end: patternMatch.index + patternMatch[0].length
587
+ };
588
+ }
589
+
590
+ // The makeRule() factory function uses this static method to turn its
591
+ // argument into a RegExp. If the argument is already a RegExp, we just
592
+ // return it. Otherwise, we compile it into a RegExp and return that.
593
+ // The reason this is necessary is that Rule.makeRule() is designed for
594
+ // use with data from JSON files and JSON files can't include RegExp
595
+ // literals. Strings passed to this function do not need to be delimited
596
+ // with / characters unless you want to include flags for the RegExp.
597
+ //
598
+ // Examples:
599
+ //
600
+ // input "" ==> output null
601
+ // input /foo/ ==> output /foo/
602
+ // input "foo" ==> output /foo/
603
+ // input "/foo/i" ==> output /foo/i
604
+ //
605
+ static makePattern(pattern) {
606
+ if (!pattern) {
607
+ return null;
608
+ }
609
+ if (pattern instanceof RegExp) {
610
+ return pattern;
611
+ }
612
+ if (pattern[0] === "/") {
613
+ var lastSlash = pattern.lastIndexOf("/");
614
+ var expression = pattern.substring(1, lastSlash);
615
+ var flags = pattern.substring(lastSlash + 1);
616
+ // @ts-expect-error [FEI-5003] - TS2713 - Cannot access 'RegExp.flags' because 'RegExp' is a type, but not a namespace. Did you mean to retrieve the type of the property 'flags' in 'RegExp' with 'RegExp["flags"]'?
617
+ return new RegExp(expression, flags);
618
+ }
619
+ return new RegExp(pattern);
620
+ }
621
+
622
+ // This static method returns an string array with index and input
623
+ // properties added, in order to simulate the return value of the
624
+ // String.match() method. We use it when a Rule has no pattern and we
625
+ // want to simulate a match on the entire content string.
626
+ static FakePatternMatch(input, match, index) {
627
+ var result = [match];
628
+ result.index = index;
629
+ result.input = input;
630
+ return result;
631
+ }
632
+ }
633
+ _defineProperty(Rule, "DEFAULT_SELECTOR", void 0);
634
+ _defineProperty(Rule, "Severity", {
635
+ ERROR: 1,
636
+ WARNING: 2,
637
+ GUIDELINE: 3,
638
+ BULK_WARNING: 4
639
+ });
640
+ Rule.DEFAULT_SELECTOR = Selector.parse("text");
641
+
642
+ /* eslint-disable no-useless-escape */
643
+ // Return the portion of a URL between // and /. This is the authority
644
+ // portion which is usually just the hostname, but may also include
645
+ // a username, password or port. We don't strip those things out because
646
+ // we typically want to reject any URL that includes them
647
+ var HOSTNAME = /\/\/([^\/]+)/;
648
+
649
+ // Return the hostname of the URL, with any "www." prefix removed.
650
+ // If this is a relative URL with no hostname, return an empty string.
651
+ function getHostname(url) {
652
+ if (!url) {
653
+ return "";
654
+ }
655
+ var match = url.match(HOSTNAME);
656
+ return match ? match[1] : "";
657
+ }
658
+
659
+ var AbsoluteUrl = Rule.makeRule({
660
+ name: "absolute-url",
661
+ severity: Rule.Severity.GUIDELINE,
662
+ selector: "link, image",
663
+ lint: function lint(state, content, nodes, match) {
664
+ var url = nodes[0].target;
665
+ var hostname = getHostname(url);
666
+ if (hostname === "khanacademy.org" || hostname.endsWith(".khanacademy.org")) {
667
+ return "Don't use absolute URLs:\nWhen linking to KA content or images, omit the\nhttps://www.khanacademy.org URL prefix.\nUse a relative URL beginning with / instead.";
668
+ }
669
+ }
670
+ });
671
+
672
+ var BlockquotedMath = Rule.makeRule({
673
+ name: "blockquoted-math",
674
+ severity: Rule.Severity.WARNING,
675
+ selector: "blockQuote math, blockQuote blockMath",
676
+ message: "Blockquoted math:\nmath should not be indented."
677
+ });
678
+
679
+ var BlockquotedWidget = Rule.makeRule({
680
+ name: "blockquoted-widget",
681
+ severity: Rule.Severity.WARNING,
682
+ selector: "blockQuote widget",
683
+ message: "Blockquoted widget:\nwidgets should not be indented."
684
+ });
685
+
686
+ /* eslint-disable no-useless-escape */
687
+ var DoubleSpacingAfterTerminal = Rule.makeRule({
688
+ name: "double-spacing-after-terminal",
689
+ severity: Rule.Severity.BULK_WARNING,
690
+ selector: "paragraph",
691
+ pattern: /[.!\?] {2}/i,
692
+ message: "Use a single space after a sentence-ending period, or\nany other kind of terminal punctuation."
693
+ });
694
+
695
+ var ExtraContentSpacing = Rule.makeRule({
696
+ name: "extra-content-spacing",
697
+ selector: "paragraph",
698
+ pattern: /\s+$/,
699
+ applies: function applies(context) {
700
+ return context.contentType === "article";
701
+ },
702
+ message: "No extra whitespace at the end of content blocks."
703
+ });
704
+
705
+ var HeadingLevel1 = Rule.makeRule({
706
+ name: "heading-level-1",
707
+ severity: Rule.Severity.WARNING,
708
+ selector: "heading",
709
+ lint: function lint(state, content, nodes, match) {
710
+ if (nodes[0].level === 1) {
711
+ return "Don't use level-1 headings:\nBegin headings with two or more # characters.";
712
+ }
713
+ }
714
+ });
715
+
716
+ var HeadingLevelSkip = Rule.makeRule({
717
+ name: "heading-level-skip",
718
+ severity: Rule.Severity.WARNING,
719
+ selector: "heading ~ heading",
720
+ lint: function lint(state, content, nodes, match) {
721
+ var currentHeading = nodes[1];
722
+ var previousHeading = nodes[0];
723
+ // A heading can have a level less than, the same as
724
+ // or one more than the previous heading. But going up
725
+ // by 2 or more levels is not right
726
+ if (currentHeading.level > previousHeading.level + 1) {
727
+ return "Skipped heading level:\nthis heading is level ".concat(currentHeading.level, " but\nthe previous heading was level ").concat(previousHeading.level);
728
+ }
729
+ }
730
+ });
731
+
732
+ var HeadingSentenceCase = Rule.makeRule({
733
+ name: "heading-sentence-case",
734
+ severity: Rule.Severity.GUIDELINE,
735
+ selector: "heading",
736
+ pattern: /^\W*[a-z]/,
737
+ // first letter is lowercase
738
+ message: "First letter is lowercase:\nthe first letter of a heading should be capitalized."
739
+ });
740
+
741
+ // These are 3-letter and longer words that we would not expect to be
742
+ // capitalized even in a title-case heading. See
743
+ // http://blog.apastyle.org/apastyle/2012/03/title-case-and-sentence-case-capitalization-in-apa-style.html
744
+ var littleWords = {
745
+ and: true,
746
+ nor: true,
747
+ but: true,
748
+ the: true,
749
+ for: true
750
+ };
751
+ function isCapitalized(word) {
752
+ var c = word[0];
753
+ return c === c.toUpperCase();
754
+ }
755
+ var HeadingTitleCase = Rule.makeRule({
756
+ name: "heading-title-case",
757
+ severity: Rule.Severity.GUIDELINE,
758
+ selector: "heading",
759
+ pattern: /[^\s:]\s+[A-Z]+[a-z]/,
760
+ locale: "en",
761
+ lint: function lint(state, content, nodes, match) {
762
+ // We want to assert that heading text is in sentence case, not
763
+ // title case. The pattern above requires a capital letter at the
764
+ // start of the heading and allows them after a colon, or in
765
+ // acronyms that are all capitalized.
766
+ //
767
+ // But we can't warn just because the pattern matched because
768
+ // proper nouns are also allowed bo be capitalized. We're not
769
+ // going to do dictionary lookup to check for proper nouns, so
770
+ // we try a heuristic: if the title is more than 3 words long
771
+ // and if all the words are capitalized or are on the list of
772
+ // words that don't get capitalized, then we'll assume that
773
+ // the heading is incorrectly in title case and will warn.
774
+ // But if there is at least one non-capitalized long word then
775
+ // we're not in title case and we should not warn.
776
+ //
777
+ // TODO(davidflanagan): if this rule causes a lot of false
778
+ // positives, we should tweak it or remove it. Note that it will
779
+ // fail for headings like "World War II in Russia"
780
+ //
781
+ // TODO(davidflanagan): This rule is specific to English.
782
+ // It is marked with a locale property above, but that is NYI
783
+ //
784
+ // for APA style rules for title case
785
+
786
+ var heading = content.trim();
787
+ var words = heading.split(/\s+/);
788
+
789
+ // Remove the first word and the little words
790
+ words.shift();
791
+ words = words.filter(
792
+ // eslint-disable-next-line no-prototype-builtins
793
+ w => w.length > 2 && !littleWords.hasOwnProperty(w));
794
+
795
+ // If there are at least 3 remaining words and all
796
+ // are capitalized, then the heading is in title case.
797
+ if (words.length >= 3 && words.every(w => isCapitalized(w))) {
798
+ return "Title-case heading:\nThis heading appears to be in title-case, but should be sentence-case.\nOnly capitalize the first letter and proper nouns.";
799
+ }
800
+ }
801
+ });
802
+
803
+ var ImageAltText = Rule.makeRule({
804
+ name: "image-alt-text",
805
+ severity: Rule.Severity.WARNING,
806
+ selector: "image",
807
+ lint: function lint(state, content, nodes, match) {
808
+ var image = nodes[0];
809
+ if (!image.alt || !image.alt.trim()) {
810
+ return "Images should have alt text:\nfor accessibility, all images should have alt text.\nSpecify alt text inside square brackets after the !.";
811
+ }
812
+ if (image.alt.length < 8) {
813
+ return "Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ".concat(image.alt.length, " characters long.");
814
+ }
815
+ }
816
+ });
817
+
818
+ var ImageInTable = Rule.makeRule({
819
+ name: "image-in-table",
820
+ severity: Rule.Severity.BULK_WARNING,
821
+ selector: "table image",
822
+ message: "Image in table:\ndo not put images inside of tables."
823
+ });
824
+
825
+ var ImageSpacesAroundUrls = Rule.makeRule({
826
+ name: "image-spaces-around-urls",
827
+ severity: Rule.Severity.ERROR,
828
+ selector: "image",
829
+ lint: function lint(state, content, nodes, match, context) {
830
+ var image = nodes[0];
831
+ var url = image.target;
832
+
833
+ // The markdown parser strips leading and trailing spaces for us,
834
+ // but they're still a problem for our translation process, so
835
+ // we need to go check for them in the unparsed source string
836
+ // if we have it.
837
+ if (context && context.content) {
838
+ // Find the url in the original content and make sure that the
839
+ // character before is '(' and the character after is ')'
840
+ var index = context.content.indexOf(url);
841
+ if (index === -1) {
842
+ // It is not an error if we didn't find it.
843
+ return;
844
+ }
845
+ if (context.content[index - 1] !== "(" || context.content[index + url.length] !== ")") {
846
+ return "Whitespace before or after image url:\nFor images, don't include any space or newlines after '(' or before ')'.\nWhitespace in image URLs causes translation difficulties.";
847
+ }
848
+ }
849
+ }
850
+ });
851
+
852
+ // Normally we have one rule per file. But since our selector class
853
+ // can't match specific widget types directly, this rule implements
854
+ // a number of image widget related rules in one place. This should
855
+ // slightly increase efficiency, but it means that if there is more
856
+ // than one problem with an image widget, the user will only see one
857
+ // problem at a time.
858
+ var ImageWidget = Rule.makeRule({
859
+ name: "image-widget",
860
+ severity: Rule.Severity.WARNING,
861
+ selector: "widget",
862
+ lint: function lint(state, content, nodes, match, context) {
863
+ // This rule only looks at image widgets
864
+ if (state.currentNode().widgetType !== "image") {
865
+ return;
866
+ }
867
+
868
+ // If it can't find a definition for the widget it does nothing
869
+ var widget = context && context.widgets && context.widgets[state.currentNode().id];
870
+ if (!widget) {
871
+ return;
872
+ }
873
+
874
+ // Make sure there is alt text
875
+ var alt = widget.options.alt;
876
+ if (!alt) {
877
+ return "Images should have alt text:\nfor accessibility, all images should have a text description.\nAdd a description in the \"Alt Text\" box of the image widget.";
878
+ }
879
+
880
+ // Make sure the alt text it is not trivial
881
+ if (alt.trim().length < 8) {
882
+ return "Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ".concat(alt.trim().length, " characters long.");
883
+ }
884
+
885
+ // Make sure there is no math in the caption
886
+ if (widget.options.caption && widget.options.caption.match(/[^\\]\$/)) {
887
+ return "No math in image captions:\nDon't include math expressions in image captions.";
888
+ }
889
+ }
890
+ });
891
+
892
+ var LinkClickHere = Rule.makeRule({
893
+ name: "link-click-here",
894
+ severity: Rule.Severity.WARNING,
895
+ selector: "link",
896
+ pattern: /click here/i,
897
+ message: "Inappropriate link text:\nDo not use the words \"click here\" in links."
898
+ });
899
+
900
+ var LongParagraph = Rule.makeRule({
901
+ name: "long-paragraph",
902
+ severity: Rule.Severity.GUIDELINE,
903
+ selector: "paragraph",
904
+ pattern: /^.{501,}/,
905
+ lint: function lint(state, content, nodes, match) {
906
+ return "Paragraph too long:\nThis paragraph is ".concat(content.length, " characters long.\nShorten it to 500 characters or fewer.");
907
+ }
908
+ });
909
+
910
+ var MathAdjacent = Rule.makeRule({
911
+ name: "math-adjacent",
912
+ severity: Rule.Severity.WARNING,
913
+ selector: "blockMath+blockMath",
914
+ message: "Adjacent math blocks:\ncombine the blocks between \\begin{align} and \\end{align}"
915
+ });
916
+
917
+ var MathAlignExtraBreak = Rule.makeRule({
918
+ name: "math-align-extra-break",
919
+ severity: Rule.Severity.WARNING,
920
+ selector: "blockMath",
921
+ pattern: /(\\{2,})\s*\\end{align}/,
922
+ message: "Extra space at end of block:\nDon't end an align block with backslashes"
923
+ });
924
+
925
+ var MathAlignLinebreaks = Rule.makeRule({
926
+ name: "math-align-linebreaks",
927
+ severity: Rule.Severity.WARNING,
928
+ selector: "blockMath",
929
+ // Match any align block with double backslashes in it
930
+ // Use [\s\S]* instead of .* so we match newlines as well.
931
+ pattern: /\\begin{align}[\s\S]*\\\\[\s\S]+\\end{align}/,
932
+ // Look for double backslashes and ensure that they are
933
+ // followed by optional space and another pair of backslashes.
934
+ // Note that this rule can't know where line breaks belong so
935
+ // it can't tell whether backslashes are completely missing. It just
936
+ // enforces that you don't have the wrong number of pairs of backslashes.
937
+ lint: function lint(state, content, nodes, match) {
938
+ var text = match[0];
939
+ while (text.length) {
940
+ var index = text.indexOf("\\\\");
941
+ if (index === -1) {
942
+ // No more backslash pairs, so we found no lint
943
+ return null;
944
+ }
945
+ text = text.substring(index + 2);
946
+
947
+ // Now we expect to find optional spaces, another pair of
948
+ // backslashes, and more optional spaces not followed immediately
949
+ // by another pair of backslashes.
950
+ var nextpair = text.match(/^\s*\\\\\s*(?!\\\\)/);
951
+
952
+ // If that does not match then we either have too few or too
953
+ // many pairs of backslashes.
954
+ if (!nextpair) {
955
+ return "Use four backslashes between lines of an align block";
956
+ }
957
+
958
+ // If it did match, then, shorten the string and continue looping
959
+ // (because a single align block may have multiple lines that
960
+ // all must be separated by two sets of double backslashes).
961
+ text = text.substring(nextpair[0].length);
962
+ }
963
+ }
964
+ });
965
+
966
+ var MathEmpty = Rule.makeRule({
967
+ name: "math-empty",
968
+ severity: Rule.Severity.WARNING,
969
+ selector: "math, blockMath",
970
+ pattern: /^$/,
971
+ message: "Empty math: don't use $$ in your markdown."
972
+ });
973
+
974
+ var MathFontSize = Rule.makeRule({
975
+ name: "math-font-size",
976
+ severity: Rule.Severity.GUIDELINE,
977
+ selector: "math, blockMath",
978
+ pattern: /\\(tiny|Tiny|small|large|Large|LARGE|huge|Huge|scriptsize|normalsize)\s*{/,
979
+ message: "Math font size:\nDon't change the default font size with \\Large{} or similar commands"
980
+ });
981
+
982
+ var MathFrac = Rule.makeRule({
983
+ name: "math-frac",
984
+ severity: Rule.Severity.GUIDELINE,
985
+ selector: "math, blockMath",
986
+ pattern: /\\frac[ {]/,
987
+ message: "Use \\dfrac instead of \\frac in your math expressions."
988
+ });
989
+
990
+ var MathNested = Rule.makeRule({
991
+ name: "math-nested",
992
+ severity: Rule.Severity.ERROR,
993
+ selector: "math, blockMath",
994
+ pattern: /\\text{[^$}]*\$[^$}]*\$[^}]*}/,
995
+ message: "Nested math:\nDon't nest math expressions inside \\text{} blocks"
996
+ });
997
+
998
+ var MathStartsWithSpace = Rule.makeRule({
999
+ name: "math-starts-with-space",
1000
+ severity: Rule.Severity.GUIDELINE,
1001
+ selector: "math, blockMath",
1002
+ pattern: /^\s*(~|\\qquad|\\quad|\\,|\\;|\\:|\\ |\\!|\\enspace|\\phantom)/,
1003
+ message: "Math starts with space:\nmath should not be indented. Do not begin math expressions with\nLaTeX space commands like ~, \\;, \\quad, or \\phantom"
1004
+ });
1005
+
1006
+ var MathTextEmpty = Rule.makeRule({
1007
+ name: "math-text-empty",
1008
+ severity: Rule.Severity.WARNING,
1009
+ selector: "math, blockMath",
1010
+ pattern: /\\text{\s*}/,
1011
+ message: "Empty \\text{} block in math expression"
1012
+ });
1013
+
1014
+ // Because no selector is specified, this rule only applies to text nodes.
1015
+ // Math and code hold their content directly and do not have text nodes
1016
+ // beneath them (unlike the HTML DOM) so this rule automatically does not
1017
+ // apply inside $$ or ``.
1018
+ var MathWithoutDollars = Rule.makeRule({
1019
+ name: "math-without-dollars",
1020
+ severity: Rule.Severity.GUIDELINE,
1021
+ pattern: /\\\w+{[^}]*}|{|}/,
1022
+ message: "This looks like LaTeX:\ndid you mean to put it inside dollar signs?"
1023
+ });
1024
+
1025
+ var NestedLists = Rule.makeRule({
1026
+ name: "nested-lists",
1027
+ severity: Rule.Severity.WARNING,
1028
+ selector: "list list",
1029
+ message: "Nested lists:\nnested lists are hard to read on mobile devices;\ndo not use additional indentation."
1030
+ });
1031
+
1032
+ var Profanity = Rule.makeRule({
1033
+ name: "profanity",
1034
+ // This list could obviously be expanded a lot, but I figured we
1035
+ // could start with https://en.wikipedia.org/wiki/Seven_dirty_words
1036
+ pattern: /\b(shit|piss|fuck|cunt|cocksucker|motherfucker|tits)\b/i,
1037
+ message: "Avoid profanity"
1038
+ });
1039
+
1040
+ var TableMissingCells = Rule.makeRule({
1041
+ name: "table-missing-cells",
1042
+ severity: Rule.Severity.WARNING,
1043
+ selector: "table",
1044
+ lint: function lint(state, content, nodes, match) {
1045
+ var table = nodes[0];
1046
+ var headerLength = table.header.length;
1047
+ var rowLengths = table.cells.map(r => r.length);
1048
+ for (var r = 0; r < rowLengths.length; r++) {
1049
+ if (rowLengths[r] !== headerLength) {
1050
+ return "Table rows don't match header:\nThe table header has ".concat(headerLength, " cells, but\nRow ").concat(r + 1, " has ").concat(rowLengths[r], " cells.");
1051
+ }
1052
+ }
1053
+ }
1054
+ });
1055
+
1056
+ // Because no selector is specified, this rule only applies to text nodes.
1057
+ // Math and code hold their content directly and do not have text nodes
1058
+ // beneath them (unlike the HTML DOM) so this rule automatically does not
1059
+ // apply inside $$ or ``.
1060
+ var UnbalancedCodeDelimiters = Rule.makeRule({
1061
+ name: "unbalanced-code-delimiters",
1062
+ severity: Rule.Severity.ERROR,
1063
+ pattern: /[`~]+/,
1064
+ message: "Unbalanced code delimiters:\ncode blocks should begin and end with the same type and number of delimiters"
1065
+ });
1066
+
1067
+ var UnescapedDollar = Rule.makeRule({
1068
+ name: "unescaped-dollar",
1069
+ severity: Rule.Severity.ERROR,
1070
+ selector: "unescapedDollar",
1071
+ message: "Unescaped dollar sign:\nDollar signs must appear in pairs or be escaped as \\$"
1072
+ });
1073
+
1074
+ var WidgetInTable = Rule.makeRule({
1075
+ name: "widget-in-table",
1076
+ severity: Rule.Severity.BULK_WARNING,
1077
+ selector: "table widget",
1078
+ message: "Widget in table:\ndo not put widgets inside of tables."
1079
+ });
1080
+
1081
+ // TODO(davidflanagan):
1082
+ var AllRules = [AbsoluteUrl, BlockquotedMath, BlockquotedWidget, DoubleSpacingAfterTerminal, ExtraContentSpacing, HeadingLevel1, HeadingLevelSkip, HeadingSentenceCase, HeadingTitleCase, ImageAltText, ImageInTable, LinkClickHere, LongParagraph, MathAdjacent, MathAlignExtraBreak, MathAlignLinebreaks, MathEmpty, MathFontSize, MathFrac, MathNested, MathStartsWithSpace, MathTextEmpty, NestedLists, TableMissingCells, UnescapedDollar, WidgetInTable, Profanity, MathWithoutDollars, UnbalancedCodeDelimiters, ImageSpacesAroundUrls, ImageWidget];
1083
+
1084
+ // TreeNode is the type of a node in a parse tree. The only real requirement is
1085
+ // that every node has a string-valued `type` property
1086
+
1087
+ // This is the TreeTransformer class described in detail at the
1088
+ // top of this file.
1089
+ class TreeTransformer {
1090
+ // To create a tree transformer, just pass the root node of the tree
1091
+ constructor(root) {
1092
+ _defineProperty(this, "root", void 0);
1093
+ this.root = root;
1094
+ }
1095
+
1096
+ // A utility function for determing whether an arbitrary value is a node
1097
+ static isNode(n) {
1098
+ return n && typeof n === "object" && typeof n.type === "string";
1099
+ }
1100
+
1101
+ // Determines whether a value is a node with type "text" and has
1102
+ // a text-valued `content` property.
1103
+ static isTextNode(n) {
1104
+ return TreeTransformer.isNode(n) && n.type === "text" && typeof n.content === "string";
1105
+ }
1106
+
1107
+ // This is the main entry point for the traverse() method. See the comment
1108
+ // at the top of this file for a detailed description. Note that this
1109
+ // method just creates a new TraversalState object to use for this
1110
+ // traversal and then invokes the internal _traverse() method to begin the
1111
+ // recursion.
1112
+ traverse(f) {
1113
+ this._traverse(this.root, new TraversalState(this.root), f);
1114
+ }
1115
+
1116
+ // Do a post-order traversal of node and its descendants, invoking the
1117
+ // callback function f() once for each node and returning the concatenated
1118
+ // text content of the node and its descendants. f() is passed three
1119
+ // arguments: the current node, a TraversalState object representing the
1120
+ // current state of the traversal, and a string that holds the
1121
+ // concatenated text of the node and its descendants.
1122
+ //
1123
+ // This private method holds all the traversal logic and implementation
1124
+ // details. Note that this method uses the TraversalState object to store
1125
+ // information about the structure of the tree.
1126
+ _traverse(n, state, f) {
1127
+ var content = "";
1128
+ if (TreeTransformer.isNode(n)) {
1129
+ // If we were called on a node object, then we handle it
1130
+ // this way.
1131
+ var _node = n; // safe cast; we just tested
1132
+
1133
+ // Put the node on the stack before recursing on its children
1134
+ state._containers.push(_node);
1135
+ state._ancestors.push(_node);
1136
+
1137
+ // Record the node's text content if it has any.
1138
+ // Usually this is for nodes with a type property of "text",
1139
+ // but other nodes types like "math" may also have content.
1140
+ // TODO(mdr): We found a new Flow error when upgrading:
1141
+ // "node.content (property `content` is missing in `TreeNode` [1].)"
1142
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'.
1143
+ if (typeof _node.content === "string") {
1144
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'.
1145
+ content = _node.content;
1146
+ }
1147
+
1148
+ // Recurse on the node. If there was content above, then there
1149
+ // probably won't be any children to recurse on, but we check
1150
+ // anyway.
1151
+ //
1152
+ // If we wanted to make the traversal completely specific to the
1153
+ // actual Perseus parse trees that we'll be dealing with we could
1154
+ // put a switch statement here to dispatch on the node type
1155
+ // property with specific recursion steps for each known type of
1156
+ // node.
1157
+ var keys = Object.keys(_node);
1158
+ keys.forEach(key => {
1159
+ // Never recurse on the type property
1160
+ if (key === "type") {
1161
+ return;
1162
+ }
1163
+ // Ignore properties that are null or primitive and only
1164
+ // recurse on objects and arrays. Note that we don't do a
1165
+ // isNode() check here. That is done in the recursive call to
1166
+ // _traverse(). Note that the recursive call on each child
1167
+ // returns the text content of the child and we add that
1168
+ // content to the content for this node. Also note that we
1169
+ // push the name of the property we're recursing over onto a
1170
+ // TraversalState stack.
1171
+ var value = _node[key];
1172
+ if (value && typeof value === "object") {
1173
+ state._indexes.push(key);
1174
+ content += this._traverse(value, state, f);
1175
+ state._indexes.pop();
1176
+ }
1177
+ });
1178
+
1179
+ // Restore the stacks after recursing on the children
1180
+ state._currentNode = state._ancestors.pop();
1181
+ state._containers.pop();
1182
+
1183
+ // And finally call the traversal callback for this node. Note
1184
+ // that this is post-order traversal. We call the callback on the
1185
+ // way back up the tree, not on the way down. That way we already
1186
+ // know all the content contained within the node.
1187
+ f(_node, state, content);
1188
+ } else if (Array.isArray(n)) {
1189
+ // If we were called on an array instead of a node, then
1190
+ // this is the code we use to recurse.
1191
+ var nodes = n;
1192
+
1193
+ // Push the array onto the stack. This will allow the
1194
+ // TraversalState object to locate siblings of this node.
1195
+ state._containers.push(nodes);
1196
+
1197
+ // Now loop through this array and recurse on each element in it.
1198
+ // Before recursing on an element, we push its array index on a
1199
+ // TraversalState stack so that the TraversalState sibling methods
1200
+ // can work. Note that TraversalState methods can alter the length
1201
+ // of the array, and change the index of the current node, so we
1202
+ // are careful here to test the array length on each iteration and
1203
+ // to reset the index when we pop the stack. Also note that we
1204
+ // concatentate the text content of the children.
1205
+ var index = 0;
1206
+ while (index < nodes.length) {
1207
+ state._indexes.push(index);
1208
+ content += this._traverse(nodes[index], state, f);
1209
+ // Casting to convince Flow that this is a number
1210
+ index = state._indexes.pop() + 1;
1211
+ }
1212
+
1213
+ // Pop the array off the stack. Note, however, that we do not call
1214
+ // the traversal callback on the array. That function is only
1215
+ // called for nodes, not arrays of nodes.
1216
+ state._containers.pop();
1217
+ }
1218
+
1219
+ // The _traverse() method always returns the text content of
1220
+ // this node and its children. This is the one piece of state that
1221
+ // is not tracked in the TraversalState object.
1222
+ return content;
1223
+ }
1224
+ }
1225
+
1226
+ // An instance of this class is passed to the callback function for
1227
+ // each node traversed. The class itself is not exported, but its
1228
+ // methods define the API available to the traversal callback.
1229
+
1230
+ /**
1231
+ * This class represents the state of a tree traversal. An instance is created
1232
+ * by the traverse() method of the TreeTransformer class to maintain the state
1233
+ * for that traversal, and the instance is passed to the traversal callback
1234
+ * function for each node that is traversed. This class is not intended to be
1235
+ * instantiated directly, but is exported so that its type can be used for
1236
+ * Flow annotaions.
1237
+ **/
1238
+ class TraversalState {
1239
+ // The root node of the tree being traversed
1240
+
1241
+ // These are internal state properties. Use the accessor methods defined
1242
+ // below instead of using these properties directly. Note that the
1243
+ // _containers and _indexes stacks can have two different types of
1244
+ // elements, depending on whether we just recursed on an array or on a
1245
+ // node. This is hard for Flow to deal with, so you'll see a number of
1246
+ // Flow casts through the any type when working with these two properties.
1247
+
1248
+ // The constructor just stores the root node and creates empty stacks.
1249
+ constructor(root) {
1250
+ _defineProperty(this, "root", void 0);
1251
+ _defineProperty(this, "_currentNode", void 0);
1252
+ _defineProperty(this, "_containers", void 0);
1253
+ _defineProperty(this, "_indexes", void 0);
1254
+ _defineProperty(this, "_ancestors", void 0);
1255
+ this.root = root;
1256
+
1257
+ // When the callback is called, this property will hold the
1258
+ // node that is currently being traversed.
1259
+ this._currentNode = null;
1260
+
1261
+ // This is a stack of the objects and arrays that we've
1262
+ // traversed through before reaching the currentNode.
1263
+ // It is different than the ancestors array.
1264
+ this._containers = new Stack();
1265
+
1266
+ // This stack has the same number of elements as the _containers
1267
+ // stack. The last element of this._indexes[] is the index of
1268
+ // the current node in the object or array that is the last element
1269
+ // of this._containers[]. If the last element of this._containers[] is
1270
+ // an array, then the last element of this stack will be a number.
1271
+ // Otherwise if the last container is an object, then the last index
1272
+ // will be a string property name.
1273
+ this._indexes = new Stack();
1274
+
1275
+ // This is a stack of the ancestor nodes of the current one.
1276
+ // It is different than the containers[] stack because it only
1277
+ // includes nodes, not arrays.
1278
+ this._ancestors = new Stack();
1279
+ }
1280
+
1281
+ /**
1282
+ * Return the current node in the traversal. Any time the traversal
1283
+ * callback is called, this method will return the name value as the
1284
+ * first argument to the callback.
1285
+ */
1286
+ currentNode() {
1287
+ return this._currentNode || this.root;
1288
+ }
1289
+
1290
+ /**
1291
+ * Return the parent of the current node, if there is one, or null.
1292
+ */
1293
+ parent() {
1294
+ return this._ancestors.top();
1295
+ }
1296
+
1297
+ /**
1298
+ * Return an array of ancestor nodes. The first element of this array is
1299
+ * the same as this.parent() and the last element is the root node. If we
1300
+ * are currently at the root node, the the returned array will be empty.
1301
+ * This method makes a copy of the internal state, so modifications to the
1302
+ * returned array have no effect on the traversal.
1303
+ */
1304
+ ancestors() {
1305
+ return this._ancestors.values();
1306
+ }
1307
+
1308
+ /**
1309
+ * Return the next sibling of this node, if it has one, or null otherwise.
1310
+ */
1311
+ nextSibling() {
1312
+ var siblings = this._containers.top();
1313
+
1314
+ // If we're at the root of the tree or if the parent is an
1315
+ // object instead of an array, then there are no siblings.
1316
+ if (!siblings || !Array.isArray(siblings)) {
1317
+ return null;
1318
+ }
1319
+
1320
+ // The top index is a number because the top container is an array
1321
+ var index = this._indexes.top();
1322
+ if (siblings.length > index + 1) {
1323
+ return siblings[index + 1];
1324
+ }
1325
+ return null; // There is no next sibling
1326
+ }
1327
+
1328
+ /**
1329
+ * Return the previous sibling of this node, if it has one, or null
1330
+ * otherwise.
1331
+ */
1332
+ previousSibling() {
1333
+ var siblings = this._containers.top();
1334
+
1335
+ // If we're at the root of the tree or if the parent is an
1336
+ // object instead of an array, then there are no siblings.
1337
+ if (!siblings || !Array.isArray(siblings)) {
1338
+ return null;
1339
+ }
1340
+
1341
+ // The top index is a number because the top container is an array
1342
+ var index = this._indexes.top();
1343
+ if (index > 0) {
1344
+ return siblings[index - 1];
1345
+ }
1346
+ return null; // There is no previous sibling
1347
+ }
1348
+
1349
+ /**
1350
+ * Remove the next sibling node (if there is one) from the tree. Returns
1351
+ * the removed sibling or null. This method makes it easy to traverse a
1352
+ * tree and concatenate adjacent text nodes into a single node.
1353
+ */
1354
+ removeNextSibling() {
1355
+ var siblings = this._containers.top();
1356
+ if (siblings && Array.isArray(siblings)) {
1357
+ // top index is a number because top container is an array
1358
+ var index = this._indexes.top();
1359
+ if (siblings.length > index + 1) {
1360
+ return siblings.splice(index + 1, 1)[0];
1361
+ }
1362
+ }
1363
+ return null;
1364
+ }
1365
+
1366
+ /**
1367
+ * Replace the current node in the tree with the specified nodes. If no
1368
+ * nodes are passed, this is a node deletion. If one node (or array) is
1369
+ * passed, this is a 1-for-1 replacement. If more than one node is passed
1370
+ * then this is a combination of deletion and insertion. The new node or
1371
+ * nodes will not be traversed, so this method can safely be used to
1372
+ * reparent the current node node beneath a new parent.
1373
+ *
1374
+ * This method throws an error if you attempt to replace the root node of
1375
+ * the tree.
1376
+ */
1377
+ replace() {
1378
+ var parent = this._containers.top();
1379
+ if (!parent) {
1380
+ throw new PerseusError("Can't replace the root of the tree", Errors.Internal);
1381
+ }
1382
+
1383
+ // The top of the container stack is either an array or an object
1384
+ // and the top of the indexes stack is a corresponding array index
1385
+ // or object property. This is hard for Flow, so we have to do some
1386
+ // unsafe casting and be careful when we use which cast version
1387
+ for (var _len = arguments.length, replacements = new Array(_len), _key = 0; _key < _len; _key++) {
1388
+ replacements[_key] = arguments[_key];
1389
+ }
1390
+ if (Array.isArray(parent)) {
1391
+ var index = this._indexes.top();
1392
+ // For an array parent we just splice the new nodes in
1393
+ parent.splice(index, 1, ...replacements);
1394
+ // Adjust the index to account for the changed array length.
1395
+ // We don't want to traverse any of the newly inserted nodes.
1396
+ this._indexes.pop();
1397
+ this._indexes.push(index + replacements.length - 1);
1398
+ } else {
1399
+ var property = this._indexes.top();
1400
+ // For an object parent we care how many new nodes there are
1401
+ if (replacements.length === 0) {
1402
+ // Deletion
1403
+ delete parent[property];
1404
+ } else if (replacements.length === 1) {
1405
+ // Replacement
1406
+ parent[property] = replacements[0];
1407
+ } else {
1408
+ // Replace one node with an array of nodes
1409
+ parent[property] = replacements;
1410
+ }
1411
+ }
1412
+ }
1413
+
1414
+ /**
1415
+ * Returns true if the current node has a previous sibling and false
1416
+ * otherwise. If this method returns false, then previousSibling() will
1417
+ * return null, and goToPreviousSibling() will throw an error.
1418
+ */
1419
+ hasPreviousSibling() {
1420
+ return Array.isArray(this._containers.top()) && this._indexes.top() > 0;
1421
+ }
1422
+
1423
+ /**
1424
+ * Modify this traversal state object to have the state it would have had
1425
+ * when visiting the previous sibling. Note that you may want to use
1426
+ * clone() to make a copy before modifying the state object like this.
1427
+ * This mutator method is not typically used during ordinary tree
1428
+ * traversals, but is used by the Selector class for matching multi-node
1429
+ * selectors.
1430
+ */
1431
+ goToPreviousSibling() {
1432
+ if (!this.hasPreviousSibling()) {
1433
+ throw new PerseusError("goToPreviousSibling(): node has no previous sibling", Errors.Internal);
1434
+ }
1435
+ this._currentNode = this.previousSibling();
1436
+ // Since we know that we have a previous sibling, we know that
1437
+ // the value on top of the stack is a number, but we have to do
1438
+ // this unsafe cast because Flow doesn't know that.
1439
+ var index = this._indexes.pop();
1440
+ this._indexes.push(index - 1);
1441
+ }
1442
+
1443
+ /**
1444
+ * Returns true if the current node has an ancestor and false otherwise.
1445
+ * If this method returns false, then the parent() method will return
1446
+ * null and goToParent() will throw an error
1447
+ */
1448
+ hasParent() {
1449
+ return this._ancestors.size() !== 0;
1450
+ }
1451
+
1452
+ /**
1453
+ * Modify this object to look like it will look when we (later) visit the
1454
+ * parent node of this node. You should not modify the instance passed to
1455
+ * the tree traversal callback. Instead, make a copy with the clone()
1456
+ * method and modify that. This mutator method is not typically used
1457
+ * during ordinary tree traversals, but is used by the Selector class for
1458
+ * matching multi-node selectors that involve parent and ancestor
1459
+ * selectors.
1460
+ */
1461
+ goToParent() {
1462
+ if (!this.hasParent()) {
1463
+ throw new PerseusError("goToParent(): node has no ancestor", Errors.NotAllowed);
1464
+ }
1465
+ this._currentNode = this._ancestors.pop();
1466
+
1467
+ // We need to pop the containers and indexes stacks at least once
1468
+ // and more as needed until we restore the invariant that
1469
+ // this._containers.top()[this.indexes.top()] === this._currentNode
1470
+ //
1471
+ while (this._containers.size() &&
1472
+ // This is safe, but easier to just disable flow than do casts
1473
+ // $FlowFixMe[incompatible-use]
1474
+ this._containers.top()[this._indexes.top()] !== this._currentNode) {
1475
+ this._containers.pop();
1476
+ this._indexes.pop();
1477
+ }
1478
+ }
1479
+
1480
+ /**
1481
+ * Return a new TraversalState object that is a copy of this one.
1482
+ * This method is useful in conjunction with the mutating methods
1483
+ * goToParent() and goToPreviousSibling().
1484
+ */
1485
+ clone() {
1486
+ var clone = new TraversalState(this.root);
1487
+ clone._currentNode = this._currentNode;
1488
+ clone._containers = this._containers.clone();
1489
+ clone._indexes = this._indexes.clone();
1490
+ clone._ancestors = this._ancestors.clone();
1491
+ return clone;
1492
+ }
1493
+
1494
+ /**
1495
+ * Returns true if this TraversalState object is equal to that
1496
+ * TraversalState object, or false otherwise. This method exists
1497
+ * primarily for use by our unit tests.
1498
+ */
1499
+ equals(that) {
1500
+ return this.root === that.root && this._currentNode === that._currentNode && this._containers.equals(that._containers) && this._indexes.equals(that._indexes) && this._ancestors.equals(that._ancestors);
1501
+ }
1502
+ }
1503
+
1504
+ /**
1505
+ * This class is an internal utility that just treats an array as a stack
1506
+ * and gives us a top() method so we don't have to write expressions like
1507
+ * `ancestors[ancestors.length-1]`. The values() method automatically
1508
+ * copies the internal array so we don't have to worry about client code
1509
+ * modifying our internal stacks. The use of this Stack abstraction makes
1510
+ * the TraversalState class simpler in a number of places.
1511
+ */
1512
+ class Stack {
1513
+ constructor(array) {
1514
+ _defineProperty(this, "stack", void 0);
1515
+ this.stack = array ? array.slice(0) : [];
1516
+ }
1517
+
1518
+ /** Push a value onto the stack. */
1519
+ push(v) {
1520
+ this.stack.push(v);
1521
+ }
1522
+
1523
+ /** Pop a value off of the stack. */
1524
+ pop() {
1525
+ // @ts-expect-error [FEI-5003] - TS2322 - Type 'T | undefined' is not assignable to type 'T'.
1526
+ return this.stack.pop();
1527
+ }
1528
+
1529
+ /** Return the top value of the stack without popping it. */
1530
+ top() {
1531
+ return this.stack[this.stack.length - 1];
1532
+ }
1533
+
1534
+ /** Return a copy of the stack as an array */
1535
+ values() {
1536
+ return this.stack.slice(0);
1537
+ }
1538
+
1539
+ /** Return the number of elements in the stack */
1540
+ size() {
1541
+ return this.stack.length;
1542
+ }
1543
+
1544
+ /** Return a string representation of the stack */
1545
+ toString() {
1546
+ return this.stack.toString();
1547
+ }
1548
+
1549
+ /** Return a shallow copy of the stack */
1550
+ clone() {
1551
+ return new Stack(this.stack);
1552
+ }
1553
+
1554
+ /**
1555
+ * Compare this stack to another and return true if the contents of
1556
+ * the two arrays are the same.
1557
+ */
1558
+ equals(that) {
1559
+ if (!that || !that.stack || that.stack.length !== this.stack.length) {
1560
+ return false;
1561
+ }
1562
+ for (var i = 0; i < this.stack.length; i++) {
1563
+ if (this.stack[i] !== that.stack[i]) {
1564
+ return false;
1565
+ }
1566
+ }
1567
+ return true;
1568
+ }
1569
+ }
1570
+
1571
+ // Define the shape of the linter context object that is passed through the
1572
+ var linterContextProps = PropTypes.shape({
1573
+ contentType: PropTypes.string,
1574
+ highlightLint: PropTypes.bool,
1575
+ paths: PropTypes.arrayOf(PropTypes.string),
1576
+ stack: PropTypes.arrayOf(PropTypes.string)
1577
+ });
1578
+ var linterContextDefault = {
1579
+ contentType: "",
1580
+ highlightLint: false,
1581
+ paths: [],
1582
+ stack: []
1583
+ };
1584
+
1585
+ var allLintRules = AllRules.filter(r => r.severity < Rule.Severity.BULK_WARNING);
1586
+
1587
+ //
1588
+ // Run the Perseus linter over the specified markdown parse tree,
1589
+ // with the specified context object, and
1590
+ // return a (possibly empty) array of lint warning objects. If the
1591
+ // highlight argument is true, this function also modifies the parse
1592
+ // tree to add "lint" nodes that can be visually rendered,
1593
+ // highlighting the problems for the user. The optional rules argument
1594
+ // is an array of Rule objects specifying which lint rules should be
1595
+ // applied to this parse tree. When omitted, a default set of rules is used.
1596
+ //
1597
+ // The context object may have additional properties that some lint
1598
+ // rules require:
1599
+ //
1600
+ // context.content is the source content string that was parsed to create
1601
+ // the parse tree.
1602
+ //
1603
+ // context.widgets is the widgets object associated
1604
+ // with the content string
1605
+ //
1606
+ // TODO: to make this even more general, allow the first argument to be
1607
+ // a string and run the parser over it in that case? (but ignore highlight
1608
+ // in that case). This would allow the one function to be used for both
1609
+ // online linting and batch linting.
1610
+ //
1611
+ function runLinter(tree, context, highlight) {
1612
+ var rules = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : allLintRules;
1613
+ var warnings = [];
1614
+ var tt = new TreeTransformer(tree);
1615
+
1616
+ // The markdown parser often outputs adjacent text nodes. We
1617
+ // coalesce them before linting for efficiency and accuracy.
1618
+ tt.traverse((node, state, content) => {
1619
+ if (TreeTransformer.isTextNode(node)) {
1620
+ var next = state.nextSibling();
1621
+ while (TreeTransformer.isTextNode(next)) {
1622
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'. | TS2533 - Object is possibly 'null' or 'undefined'. | TS2339 - Property 'content' does not exist on type 'TreeNode'.
1623
+ node.content += next.content;
1624
+ state.removeNextSibling();
1625
+ next = state.nextSibling();
1626
+ }
1627
+ }
1628
+ });
1629
+
1630
+ // HTML tables are complicated, and the CSS we use in
1631
+ // ../components/lint.jsx to display lint does not work to
1632
+ // correctly position the lint indicators in the margin when the
1633
+ // lint is inside a table. So as a workaround we keep track of all
1634
+ // the lint that appears within a table and move it up to the
1635
+ // table element itself.
1636
+ //
1637
+ // It is not ideal to have to do this here,
1638
+ // but it is cleaner here than fixing up the lint during rendering
1639
+ // in perseus-markdown.jsx. If our lint display was simpler and
1640
+ // did not require indicators in the margin, this wouldn't be a
1641
+ // problem. Or, if we modified the lint display stuff so that
1642
+ // indicator positioning and tooltip display were both handled
1643
+ // with JavaScript (instead of pure CSS), then we could avoid this
1644
+ // issue too. But using JavaScript has its own downsides: there is
1645
+ // risk that the linter JavaScript would interfere with
1646
+ // widget-related Javascript.
1647
+ var tableWarnings = [];
1648
+ var insideTable = false;
1649
+
1650
+ // Traverse through the nodes of the parse tree. At each node, loop
1651
+ // through the array of lint rules and check whether there is a
1652
+ // lint violation at that node.
1653
+ tt.traverse((node, state, content) => {
1654
+ var nodeWarnings = [];
1655
+
1656
+ // If our rule is only designed to be tested against a particular
1657
+ // content type and we're not in that content type, we don't need to
1658
+ // consider that rule.
1659
+ var applicableRules = rules.filter(r => r.applies(context));
1660
+
1661
+ // Generate a stack so we can identify our position in the tree in
1662
+ // lint rules
1663
+ var stack = [...context.stack];
1664
+ stack.push(node.type);
1665
+ var nodeContext = _objectSpread2(_objectSpread2({}, context), {}, {
1666
+ stack: stack.join(".")
1667
+ });
1668
+ applicableRules.forEach(rule => {
1669
+ var warning = rule.check(node, state, content, nodeContext);
1670
+ if (warning) {
1671
+ // The start and end locations are relative to this
1672
+ // particular node, and so are not generally very useful.
1673
+ // TODO: When the markdown parser saves the node
1674
+ // locations in the source string then we can add
1675
+ // these numbers to that one and get and absolute
1676
+ // character range that will be useful
1677
+ if (warning.start || warning.end) {
1678
+ warning.target = content.substring(warning.start, warning.end);
1679
+ }
1680
+
1681
+ // Add the warning to the list of all lint we've found
1682
+ warnings.push(warning);
1683
+
1684
+ // If we're going to be highlighting lint, then we also
1685
+ // need to keep track of warnings specific to this node.
1686
+ if (highlight) {
1687
+ nodeWarnings.push(warning);
1688
+ }
1689
+ }
1690
+ });
1691
+
1692
+ // If we're not highlighting lint in the tree, then we're done
1693
+ // traversing this node.
1694
+ if (!highlight) {
1695
+ return;
1696
+ }
1697
+
1698
+ // If the node we are currently at is a table, and there was lint
1699
+ // inside the table, then we want to add that lint here
1700
+ if (node.type === "table") {
1701
+ if (tableWarnings.length) {
1702
+ nodeWarnings.push(...tableWarnings);
1703
+ }
1704
+
1705
+ // We're not in a table anymore, and don't have to remember
1706
+ // the warnings for the table
1707
+ insideTable = false;
1708
+ tableWarnings = [];
1709
+ } else if (!insideTable) {
1710
+ // Otherwise, if we are not already inside a table, check
1711
+ // to see if we've entered one. Because this is a post-order
1712
+ // traversal we'll see the table contents before the table itself.
1713
+ // Note that once we're inside the table, we don't have to
1714
+ // do this check each time... We can just wait until we ascend
1715
+ // up to the table, then we'll know we're out of it.
1716
+ insideTable = state.ancestors().some(n => n.type === "table");
1717
+ }
1718
+
1719
+ // If we are inside a table and there were any warnings on
1720
+ // this node, then we need to save the warnings for display
1721
+ // on the table itself
1722
+ if (insideTable && nodeWarnings.length) {
1723
+ // @ts-expect-error [FEI-5003] - TS2345 - Argument of type 'any' is not assignable to parameter of type 'never'.
1724
+ tableWarnings.push(...nodeWarnings);
1725
+ }
1726
+
1727
+ // If there were any warnings on this node, and if we're highlighting
1728
+ // lint, then reparent the node so we can highlight it. Note that
1729
+ // a single node can have multiple warnings. If this happends we
1730
+ // concatenate the warnings and newline separate them. (The lint.jsx
1731
+ // component that displays the warnings may want to convert the
1732
+ // newlines into <br> tags.) We also provide a lint rule name
1733
+ // so that lint.jsx can link to a document that provides more details
1734
+ // on that particular lint rule. If there is more than one warning
1735
+ // we only link to the first rule, however.
1736
+ //
1737
+ // Note that even if we're inside a table, we still reparent the
1738
+ // linty node so that it can be highlighted. We just make a note
1739
+ // of whether this lint is inside a table or not.
1740
+ if (nodeWarnings.length) {
1741
+ nodeWarnings.sort((a, b) => {
1742
+ return a.severity - b.severity;
1743
+ });
1744
+ if (node.type !== "text" || nodeWarnings.length > 1) {
1745
+ // If the linty node is not a text node, or if there is more
1746
+ // than one warning on a text node, then reparent the entire
1747
+ // node under a new lint node and put the warnings there.
1748
+ state.replace({
1749
+ type: "lint",
1750
+ // @ts-expect-error [FEI-5003] - TS2345 - Argument of type '{ type: string; content: TreeNode; message: string; ruleName: any; blockHighlight: any; insideTable: boolean; severity: any; }' is not assignable to parameter of type 'TreeNode'.
1751
+ content: node,
1752
+ message: nodeWarnings.map(w => w.message).join("\n\n"),
1753
+ ruleName: nodeWarnings[0].rule,
1754
+ blockHighlight: nodeContext.blockHighlight,
1755
+ insideTable: insideTable,
1756
+ severity: nodeWarnings[0].severity
1757
+ });
1758
+ } else {
1759
+ //
1760
+ // Otherwise, it is a single warning on a text node, and we
1761
+ // only want to highlight the actual linty part of that string
1762
+ // of text. So we want to replace the text node with (in the
1763
+ // general case) three nodes:
1764
+ //
1765
+ // 1) A new text node that holds the non-linty prefix
1766
+ //
1767
+ // 2) A lint node that is the parent of a new text node
1768
+ // that holds the linty part
1769
+ //
1770
+ // 3) A new text node that holds the non-linty suffix
1771
+ //
1772
+ // If the lint begins and/or ends at the boundaries of the
1773
+ // original text node, then nodes 1 and/or 3 won't exist, of
1774
+ // course.
1775
+ //
1776
+ // Note that we could generalize this to work with multple
1777
+ // warnings on a text node as long as the warnings are
1778
+ // non-overlapping. Hopefully, though, multiple warnings in a
1779
+ // single text node will be rare in practice. Also, we don't
1780
+ // have a good way to display multiple lint indicators on a
1781
+ // single line, so keeping them combined in that case might
1782
+ // be the best thing, anyway.
1783
+ //
1784
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'.
1785
+ var _content = node.content; // Text nodes have content
1786
+ var warning = nodeWarnings[0]; // There is only one warning.
1787
+ // These are the lint boundaries within the content
1788
+ var start = warning.start || 0;
1789
+ var end = warning.end || _content.length;
1790
+ var prefix = _content.substring(0, start);
1791
+ var lint = _content.substring(start, end);
1792
+ var suffix = _content.substring(end);
1793
+ // TODO(FEI-5003): Give this a real type.
1794
+ var replacements = []; // What we'll replace the node with
1795
+
1796
+ // The prefix text node, if there is one
1797
+ if (prefix) {
1798
+ replacements.push({
1799
+ type: "text",
1800
+ content: prefix
1801
+ });
1802
+ }
1803
+
1804
+ // The lint node wrapped around the linty text
1805
+ replacements.push({
1806
+ type: "lint",
1807
+ content: {
1808
+ type: "text",
1809
+ content: lint
1810
+ },
1811
+ message: warning.message,
1812
+ ruleName: warning.rule,
1813
+ insideTable: insideTable,
1814
+ severity: warning.severity
1815
+ });
1816
+
1817
+ // The suffix node, if there is one
1818
+ if (suffix) {
1819
+ replacements.push({
1820
+ type: "text",
1821
+ content: suffix
1822
+ });
1823
+ }
1824
+
1825
+ // Now replace the lint text node with the one to three
1826
+ // nodes in the replacement array
1827
+ state.replace(...replacements);
1828
+ }
1829
+ }
1830
+ });
1831
+ return warnings;
1832
+ }
1833
+ function pushContextStack(context, name) {
1834
+ var stack = context.stack || [];
1835
+ return _objectSpread2(_objectSpread2({}, context), {}, {
1836
+ stack: stack.concat(name)
1837
+ });
1838
+ }
1839
+
1840
+ export { Rule, linterContextDefault, linterContextProps, pushContextStack, allLintRules as rules, runLinter };
1841
+ //# sourceMappingURL=index.js.map