@khanacademy/perseus-linter 0.1.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/es/index.js +3152 -0
  3. package/dist/es/index.js.map +1 -0
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.js +3129 -0
  6. package/dist/index.js.flow +2 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +31 -0
  9. package/src/README.md +41 -0
  10. package/src/__tests__/matcher_test.js +498 -0
  11. package/src/__tests__/rule_test.js +102 -0
  12. package/src/__tests__/rules_test.js +488 -0
  13. package/src/__tests__/selector-parser_test.js +52 -0
  14. package/src/__tests__/tree-transformer_test.js +446 -0
  15. package/src/index.js +281 -0
  16. package/src/proptypes.js +29 -0
  17. package/src/rule.js +412 -0
  18. package/src/rules/absolute-url.js +24 -0
  19. package/src/rules/all-rules.js +72 -0
  20. package/src/rules/blockquoted-math.js +10 -0
  21. package/src/rules/blockquoted-widget.js +10 -0
  22. package/src/rules/double-spacing-after-terminal.js +12 -0
  23. package/src/rules/extra-content-spacing.js +12 -0
  24. package/src/rules/heading-level-1.js +14 -0
  25. package/src/rules/heading-level-skip.js +20 -0
  26. package/src/rules/heading-sentence-case.js +11 -0
  27. package/src/rules/heading-title-case.js +63 -0
  28. package/src/rules/image-alt-text.js +21 -0
  29. package/src/rules/image-in-table.js +10 -0
  30. package/src/rules/image-spaces-around-urls.js +35 -0
  31. package/src/rules/image-widget.js +50 -0
  32. package/src/rules/link-click-here.js +11 -0
  33. package/src/rules/lint-utils.js +48 -0
  34. package/src/rules/long-paragraph.js +14 -0
  35. package/src/rules/math-adjacent.js +10 -0
  36. package/src/rules/math-align-extra-break.js +11 -0
  37. package/src/rules/math-align-linebreaks.js +43 -0
  38. package/src/rules/math-empty.js +10 -0
  39. package/src/rules/math-font-size.js +12 -0
  40. package/src/rules/math-frac.js +10 -0
  41. package/src/rules/math-nested.js +11 -0
  42. package/src/rules/math-starts-with-space.js +12 -0
  43. package/src/rules/math-text-empty.js +10 -0
  44. package/src/rules/math-without-dollars.js +14 -0
  45. package/src/rules/nested-lists.js +11 -0
  46. package/src/rules/profanity.js +10 -0
  47. package/src/rules/table-missing-cells.js +20 -0
  48. package/src/rules/unbalanced-code-delimiters.js +14 -0
  49. package/src/rules/unescaped-dollar.js +10 -0
  50. package/src/rules/widget-in-table.js +10 -0
  51. package/src/selector.js +505 -0
  52. package/src/tree-transformer.js +587 -0
  53. package/src/types.js +10 -0
package/dist/index.js ADDED
@@ -0,0 +1,3129 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var perseusError = require('@khanacademy/perseus-error');
6
+
7
+ function _defineProperty(obj, key, value) {
8
+ if (key in obj) {
9
+ Object.defineProperty(obj, key, {
10
+ value: value,
11
+ enumerable: true,
12
+ configurable: true,
13
+ writable: true
14
+ });
15
+ } else {
16
+ obj[key] = value;
17
+ }
18
+
19
+ return obj;
20
+ }
21
+
22
+ /**
23
+ * This is the base class for all Selector types. The key method that all
24
+ * selector subclasses must implement is match(). It takes a TraversalState
25
+ * object (from a TreeTransformer traversal) and tests whether the selector
26
+ * matches at the current node. See the comment at the start of this file for
27
+ * more details on the match() method.
28
+ */
29
+ class Selector {
30
+ static parse(selectorText) {
31
+ return new Parser(selectorText).parse();
32
+ }
33
+ /**
34
+ * Return an array of the nodes that matched or null if no match.
35
+ * This is the base class so we just throw an exception. All Selector
36
+ * subclasses must provide an implementation of this method.
37
+ */
38
+
39
+
40
+ match(state) {
41
+ throw new perseusError.PerseusError("Selector subclasses must implement match()", perseusError.Errors.NotAllowed);
42
+ }
43
+ /**
44
+ * Selector subclasses all define a toString() method primarily
45
+ * because it makes it easy to write parser tests.
46
+ */
47
+
48
+
49
+ toString() {
50
+ return "Unknown selector class";
51
+ }
52
+
53
+ }
54
+ /**
55
+ * This class implements a parser for the selector grammar. Pass the source
56
+ * text to the Parser() constructor, and then call the parse() method to
57
+ * obtain a corresponding Selector object. parse() throws an exception
58
+ * if there are syntax errors in the selector.
59
+ *
60
+ * This class is not exported, and you don't need to use it directly.
61
+ * Instead call the static Selector.parse() method.
62
+ */
63
+
64
+ class Parser {
65
+ // We do lexing with a simple regular expression
66
+ // The array of tokens
67
+ // Which token in the array we're looking at now
68
+ constructor(s) {
69
+ _defineProperty(this, "tokens", void 0);
70
+
71
+ _defineProperty(this, "tokenIndex", void 0);
72
+
73
+ // Normalize whitespace:
74
+ // - remove leading and trailing whitespace
75
+ // - replace runs of whitespace with single space characters
76
+ s = s.trim().replace(/\s+/g, " "); // Convert the string to an array of tokens. Note that the TOKENS
77
+ // pattern ignores spaces that do not appear before identifiers
78
+ // or the * wildcard.
79
+
80
+ this.tokens = s.match(Parser.TOKENS) || [];
81
+ this.tokenIndex = 0;
82
+ } // Return the next token or the empty string if there are no more
83
+
84
+
85
+ nextToken() {
86
+ return this.tokens[this.tokenIndex] || "";
87
+ } // Increment the token index to "consume" the token we were looking at
88
+ // and move on to the next one.
89
+
90
+
91
+ consume() {
92
+ this.tokenIndex++;
93
+ } // Return true if the current token is an identifier or false otherwise
94
+
95
+
96
+ isIdentifier() {
97
+ // The Parser.TOKENS regexp ensures that we only have to check
98
+ // the first character of a token to know what kind of token it is.
99
+ const c = this.tokens[this.tokenIndex][0];
100
+ return c >= "a" && c <= "z" || c >= "A" && c <= "Z";
101
+ } // Consume space tokens until the next token is not a space.
102
+
103
+
104
+ skipSpace() {
105
+ while (this.nextToken() === " ") {
106
+ this.consume();
107
+ }
108
+ } // Parse a comma-separated sequence of tree selectors. This is the
109
+ // entry point for the Parser class and the only method that clients
110
+ // ever need to call.
111
+
112
+
113
+ parse() {
114
+ // We expect at least one tree selector
115
+ const ts = this.parseTreeSelector(); // Now see what's next
116
+
117
+ let token = this.nextToken(); // If there is no next token then we're done parsing and can return
118
+ // the tree selector object we got above
119
+
120
+ if (!token) {
121
+ return ts;
122
+ } // Otherwise, there is more go come and we're going to need a
123
+ // list of tree selectors
124
+
125
+
126
+ const treeSelectors = [ts];
127
+
128
+ while (token) {
129
+ // The only character we allow after a tree selector is a comma
130
+ if (token === ",") {
131
+ this.consume();
132
+ } else {
133
+ throw new ParseError("Expected comma");
134
+ } // And if we saw a comma, then it must be followed by another
135
+ // tree selector
136
+
137
+
138
+ treeSelectors.push(this.parseTreeSelector());
139
+ token = this.nextToken();
140
+ } // If we parsed more than one tree selector, return them in a
141
+ // SelectorList object.
142
+
143
+
144
+ return new SelectorList(treeSelectors);
145
+ } // Parse a sequence of node selectors linked together with
146
+ // hierarchy combinators: space, >, + and ~.
147
+
148
+
149
+ parseTreeSelector() {
150
+ this.skipSpace(); // Ignore space after a comma, for example
151
+ // A tree selector must begin with a node selector
152
+
153
+ let ns = this.parseNodeSelector();
154
+
155
+ for (;;) {
156
+ // Now check the next token. If there is none, or if it is a
157
+ // comma, then we're done with the treeSelector. Otherwise
158
+ // we expect a combinator followed by another node selector.
159
+ // If we don't see a combinator, we throw an error. If we
160
+ // do see a combinator and another node selector then we
161
+ // combine the current node selector with the new node selector
162
+ // using a Selector subclass that depends on the combinator.
163
+ const token = this.nextToken();
164
+
165
+ if (!token || token === ",") {
166
+ break;
167
+ } else if (token === " ") {
168
+ this.consume();
169
+ ns = new AncestorCombinator(ns, this.parseNodeSelector());
170
+ } else if (token === ">") {
171
+ this.consume();
172
+ ns = new ParentCombinator(ns, this.parseNodeSelector());
173
+ } else if (token === "+") {
174
+ this.consume();
175
+ ns = new PreviousCombinator(ns, this.parseNodeSelector());
176
+ } else if (token === "~") {
177
+ this.consume();
178
+ ns = new SiblingCombinator(ns, this.parseNodeSelector());
179
+ } else {
180
+ throw new ParseError("Unexpected token: " + token);
181
+ }
182
+ }
183
+
184
+ return ns;
185
+ } // Parse a single node selector.
186
+ // For now, this is just a node type or a wildcard.
187
+ //
188
+ // TODO(davidflanagan): we may need to extend this with attribute
189
+ // selectors like 'heading[level=3]', or with pseudo-classes like
190
+ // paragraph:first-child
191
+
192
+
193
+ parseNodeSelector() {
194
+ // First, skip any whitespace
195
+ this.skipSpace();
196
+ const t = this.nextToken();
197
+
198
+ if (t === "*") {
199
+ this.consume();
200
+ return new AnyNode();
201
+ }
202
+
203
+ if (this.isIdentifier()) {
204
+ this.consume();
205
+ return new TypeSelector(t);
206
+ }
207
+
208
+ throw new ParseError("Expected node type");
209
+ }
210
+
211
+ } // We break the input string into tokens with this regexp. Token types
212
+ // are identifiers, integers, punctuation and spaces. Note that spaces
213
+ // tokens are only returned when they appear before an identifier or
214
+ // wildcard token and are otherwise omitted.
215
+
216
+
217
+ _defineProperty(Parser, "TOKENS", void 0);
218
+
219
+ Parser.TOKENS = /([a-zA-Z][\w-]*)|(\d+)|[^\s]|(\s(?=[a-zA-Z\*]))/g;
220
+ /**
221
+ * This is a trivial Error subclass that the Parser uses to signal parse errors
222
+ */
223
+
224
+ class ParseError extends Error {
225
+ constructor(message) {
226
+ super(message);
227
+ }
228
+
229
+ }
230
+ /**
231
+ * This Selector subclass is a list of selectors. It matches a node if any of
232
+ * the selectors on the list matches the node. It considers the selectors in
233
+ * order, and returns the array of nodes returned by whichever one matches
234
+ * first.
235
+ */
236
+
237
+
238
+ class SelectorList extends Selector {
239
+ constructor(selectors) {
240
+ super();
241
+
242
+ _defineProperty(this, "selectors", void 0);
243
+
244
+ this.selectors = selectors;
245
+ }
246
+
247
+ match(state) {
248
+ for (let i = 0; i < this.selectors.length; i++) {
249
+ const s = this.selectors[i];
250
+ const result = s.match(state);
251
+
252
+ if (result) {
253
+ return result;
254
+ }
255
+ }
256
+
257
+ return null;
258
+ }
259
+
260
+ toString() {
261
+ let result = "";
262
+
263
+ for (let i = 0; i < this.selectors.length; i++) {
264
+ result += i > 0 ? ", " : "";
265
+ result += this.selectors[i].toString();
266
+ }
267
+
268
+ return result;
269
+ }
270
+
271
+ }
272
+ /**
273
+ * This trivial Selector subclass implements the '*' wildcard and
274
+ * matches any node.
275
+ */
276
+
277
+
278
+ class AnyNode extends Selector {
279
+ match(state) {
280
+ return [state.currentNode()];
281
+ }
282
+
283
+ toString() {
284
+ return "*";
285
+ }
286
+
287
+ }
288
+ /**
289
+ * This selector subclass implements the <IDENTIFIER> part of the grammar.
290
+ * it matches any node whose `type` property is a specified string
291
+ */
292
+
293
+
294
+ class TypeSelector extends Selector {
295
+ constructor(type) {
296
+ super();
297
+
298
+ _defineProperty(this, "type", void 0);
299
+
300
+ this.type = type;
301
+ }
302
+
303
+ match(state) {
304
+ const node = state.currentNode();
305
+
306
+ if (node.type === this.type) {
307
+ return [node];
308
+ }
309
+
310
+ return null;
311
+ }
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
+
325
+
326
+ class SelectorCombinator extends Selector {
327
+ constructor(left, right) {
328
+ super();
329
+
330
+ _defineProperty(this, "left", void 0);
331
+
332
+ _defineProperty(this, "right", void 0);
333
+
334
+ this.left = left;
335
+ this.right = right;
336
+ }
337
+
338
+ }
339
+ /**
340
+ * This Selector subclass implements the space combinator. It matches if the
341
+ * right selector matches the current node and the left selector matches some
342
+ * ancestor of the current node.
343
+ */
344
+
345
+
346
+ class AncestorCombinator extends SelectorCombinator {
347
+ constructor(left, right) {
348
+ super(left, right);
349
+ }
350
+
351
+ match(state) {
352
+ const rightResult = this.right.match(state);
353
+
354
+ if (rightResult) {
355
+ state = state.clone();
356
+
357
+ while (state.hasParent()) {
358
+ state.goToParent();
359
+ const leftResult = this.left.match(state);
360
+
361
+ if (leftResult) {
362
+ return leftResult.concat(rightResult);
363
+ }
364
+ }
365
+ }
366
+
367
+ return null;
368
+ }
369
+
370
+ toString() {
371
+ return this.left.toString() + " " + this.right.toString();
372
+ }
373
+
374
+ }
375
+ /**
376
+ * This Selector subclass implements the > combinator. It matches if the
377
+ * right selector matches the current node and the left selector matches
378
+ * the parent of the current node.
379
+ */
380
+
381
+
382
+ class ParentCombinator extends SelectorCombinator {
383
+ constructor(left, right) {
384
+ super(left, right);
385
+ }
386
+
387
+ match(state) {
388
+ const rightResult = this.right.match(state);
389
+
390
+ if (rightResult) {
391
+ if (state.hasParent()) {
392
+ state = state.clone();
393
+ state.goToParent();
394
+ const leftResult = this.left.match(state);
395
+
396
+ if (leftResult) {
397
+ return leftResult.concat(rightResult);
398
+ }
399
+ }
400
+ }
401
+
402
+ return null;
403
+ }
404
+
405
+ toString() {
406
+ return this.left.toString() + " > " + this.right.toString();
407
+ }
408
+
409
+ }
410
+ /**
411
+ * This Selector subclass implements the + combinator. It matches if the
412
+ * right selector matches the current node and the left selector matches
413
+ * the immediate previous sibling of the current node.
414
+ */
415
+
416
+
417
+ class PreviousCombinator extends SelectorCombinator {
418
+ constructor(left, right) {
419
+ super(left, right);
420
+ }
421
+
422
+ match(state) {
423
+ const rightResult = this.right.match(state);
424
+
425
+ if (rightResult) {
426
+ if (state.hasPreviousSibling()) {
427
+ state = state.clone();
428
+ state.goToPreviousSibling();
429
+ const leftResult = this.left.match(state);
430
+
431
+ if (leftResult) {
432
+ return leftResult.concat(rightResult);
433
+ }
434
+ }
435
+ }
436
+
437
+ return null;
438
+ }
439
+
440
+ toString() {
441
+ return this.left.toString() + " + " + this.right.toString();
442
+ }
443
+
444
+ }
445
+ /**
446
+ * This Selector subclass implements the ~ combinator. It matches if the
447
+ * right selector matches the current node and the left selector matches
448
+ * any previous sibling of the current node.
449
+ */
450
+
451
+
452
+ class SiblingCombinator extends SelectorCombinator {
453
+ constructor(left, right) {
454
+ super(left, right);
455
+ }
456
+
457
+ match(state) {
458
+ const rightResult = this.right.match(state);
459
+
460
+ if (rightResult) {
461
+ state = state.clone();
462
+
463
+ while (state.hasPreviousSibling()) {
464
+ state.goToPreviousSibling();
465
+ const leftResult = this.left.match(state);
466
+
467
+ if (leftResult) {
468
+ return leftResult.concat(rightResult);
469
+ }
470
+ }
471
+ }
472
+
473
+ return null;
474
+ }
475
+
476
+ toString() {
477
+ return this.left.toString() + " ~ " + this.right.toString();
478
+ }
479
+
480
+ }
481
+
482
+ /**
483
+ * A Rule object describes a Gorgon lint rule. See the comment at the top of
484
+ * this file for detailed description.
485
+ */
486
+ class Rule {
487
+ // The name of the rule
488
+ // The severity of the rule
489
+ // The specified selector or the DEFAULT_SELECTOR
490
+ // A regular expression if one was specified
491
+ // The lint-testing function or a default
492
+ // Checks to see if we should apply a rule or not
493
+ // The error message for use with the default function
494
+ // The comment at the top of this file has detailed docs for
495
+ // this constructor and its arguments
496
+ constructor(name, severity, selector, pattern, lint, applies) {
497
+ var _this = this;
498
+
499
+ _defineProperty(this, "name", void 0);
500
+
501
+ _defineProperty(this, "severity", void 0);
502
+
503
+ _defineProperty(this, "selector", void 0);
504
+
505
+ _defineProperty(this, "pattern", void 0);
506
+
507
+ _defineProperty(this, "lint", void 0);
508
+
509
+ _defineProperty(this, "applies", void 0);
510
+
511
+ _defineProperty(this, "message", void 0);
512
+
513
+ if (!selector && !pattern) {
514
+ throw new perseusError.PerseusError("Lint rules must have a selector or pattern", perseusError.Errors.InvalidInput, {
515
+ metadata: {
516
+ name
517
+ }
518
+ });
519
+ }
520
+
521
+ this.name = name || "unnamed rule";
522
+ this.severity = severity || Rule.Severity.BULK_WARNING;
523
+ this.selector = selector || Rule.DEFAULT_SELECTOR;
524
+ this.pattern = pattern || null; // If we're called with an error message instead of a function then
525
+ // use a default function that will return the message.
526
+
527
+ if (typeof lint === "function") {
528
+ this.lint = lint;
529
+ this.message = null;
530
+ } else {
531
+ this.lint = function () {
532
+ return _this._defaultLintFunction(...arguments);
533
+ };
534
+
535
+ this.message = lint;
536
+ }
537
+
538
+ this.applies = applies || function () {
539
+ return true;
540
+ };
541
+ } // A factory method for use with rules described in JSON files
542
+ // See the documentation at the start of this file for details.
543
+
544
+
545
+ static makeRule(options) {
546
+ return new Rule(options.name, options.severity, options.selector ? Selector.parse(options.selector) : null, Rule.makePattern(options.pattern), options.lint || options.message, options.applies);
547
+ } // Check the node n to see if it violates this lint rule. A return value
548
+ // of false means there is no lint. A returned object indicates a lint
549
+ // error. See the documentation at the top of this file for details.
550
+
551
+
552
+ check(node, traversalState, content, context) {
553
+ // First, see if we match the selector.
554
+ // If no selector was passed to the constructor, we use a
555
+ // default selector that matches text nodes.
556
+ const selectorMatch = this.selector.match(traversalState); // If the selector did not match, then we're done
557
+
558
+ if (!selectorMatch) {
559
+ return null;
560
+ } // If the selector matched, then see if the pattern matches
561
+
562
+
563
+ let patternMatch;
564
+
565
+ if (this.pattern) {
566
+ patternMatch = content.match(this.pattern);
567
+ } else {
568
+ // If there is no pattern, then just match all of the content.
569
+ // Use a fake RegExp match object to represent this default match.
570
+ patternMatch = Rule.FakePatternMatch(content, content, 0);
571
+ } // If there was a pattern and it didn't match, then we're done
572
+
573
+
574
+ if (!patternMatch) {
575
+ return null;
576
+ }
577
+
578
+ try {
579
+ // If we get here, then the selector and pattern have matched
580
+ // so now we call the lint function to see if there is lint.
581
+ const error = this.lint(traversalState, content, selectorMatch, patternMatch, context);
582
+
583
+ if (!error) {
584
+ return null; // No lint; we're done
585
+ }
586
+
587
+ if (typeof error === "string") {
588
+ // If the lint function returned a string we assume it
589
+ // applies to the entire content of the node and return it.
590
+ return {
591
+ rule: this.name,
592
+ severity: this.severity,
593
+ message: error,
594
+ start: 0,
595
+ end: content.length
596
+ };
597
+ } // If the lint function returned an object, then we just
598
+ // add the rule name to the message, start and end.
599
+
600
+
601
+ return {
602
+ rule: this.name,
603
+ severity: this.severity,
604
+ message: error.message,
605
+ start: error.start,
606
+ end: error.end
607
+ };
608
+ } catch (e) {
609
+ // If the lint function threw an exception we handle that as
610
+ // a special type of lint. We want the user to see the lint
611
+ // warning in this case (even though it is out of their control)
612
+ // so that the bug gets reported. Otherwise we'd never know that
613
+ // a rule was failing.
614
+ return {
615
+ rule: "lint-rule-failure",
616
+ message: "Exception in rule ".concat(this.name, ": ").concat(e.message, "\nStack trace:\n").concat(e.stack),
617
+ start: 0,
618
+ end: content.length
619
+ };
620
+ }
621
+ } // This internal method is the default lint function that we use when a
622
+ // rule is defined without a function. This is useful for rules where the
623
+ // selector and/or pattern match are enough to indicate lint. This
624
+ // function unconditionally returns the error message that was passed in
625
+ // place of a function, but also adds start and end properties that
626
+ // specify which particular portion of the node content matched the
627
+ // pattern.
628
+
629
+
630
+ _defaultLintFunction(state, content, selectorMatch, patternMatch, context) {
631
+ return {
632
+ message: this.message || "",
633
+ start: patternMatch.index,
634
+ end: patternMatch.index + patternMatch[0].length
635
+ };
636
+ } // The makeRule() factory function uses this static method to turn its
637
+ // argument into a RegExp. If the argument is already a RegExp, we just
638
+ // return it. Otherwise, we compile it into a RegExp and return that.
639
+ // The reason this is necessary is that Rule.makeRule() is designed for
640
+ // use with data from JSON files and JSON files can't include RegExp
641
+ // literals. Strings passed to this function do not need to be delimited
642
+ // with / characters unless you want to include flags for the RegExp.
643
+ //
644
+ // Examples:
645
+ //
646
+ // input "" ==> output null
647
+ // input /foo/ ==> output /foo/
648
+ // input "foo" ==> output /foo/
649
+ // input "/foo/i" ==> output /foo/i
650
+ //
651
+
652
+
653
+ static makePattern(pattern) {
654
+ if (!pattern) {
655
+ return null;
656
+ }
657
+
658
+ if (pattern instanceof RegExp) {
659
+ return pattern;
660
+ }
661
+
662
+ if (pattern[0] === "/") {
663
+ const lastSlash = pattern.lastIndexOf("/");
664
+ const expression = pattern.substring(1, lastSlash);
665
+ const flags = pattern.substring(lastSlash + 1);
666
+ return new RegExp(expression, flags);
667
+ }
668
+
669
+ return new RegExp(pattern);
670
+ } // This static method returns an string array with index and input
671
+ // properties added, in order to simulate the return value of the
672
+ // String.match() method. We use it when a Rule has no pattern and we
673
+ // want to simulate a match on the entire content string.
674
+
675
+
676
+ static FakePatternMatch(input, match, index) {
677
+ const result = [match];
678
+ result.index = index;
679
+ result.input = input;
680
+ return result;
681
+ }
682
+
683
+ }
684
+
685
+ _defineProperty(Rule, "DEFAULT_SELECTOR", void 0);
686
+
687
+ _defineProperty(Rule, "Severity", {
688
+ ERROR: 1,
689
+ WARNING: 2,
690
+ GUIDELINE: 3,
691
+ BULK_WARNING: 4
692
+ });
693
+
694
+ Rule.DEFAULT_SELECTOR = Selector.parse("text");
695
+
696
+ /* eslint-disable no-useless-escape */
697
+ // Return the portion of a URL between // and /. This is the authority
698
+ // portion which is usually just the hostname, but may also include
699
+ // a username, password or port. We don't strip those things out because
700
+ // we typically want to reject any URL that includes them
701
+ const HOSTNAME = /\/\/([^\/]+)/; // Return the hostname of the URL, with any "www." prefix removed.
702
+ // If this is a relative URL with no hostname, return an empty string.
703
+
704
+ function getHostname(url) {
705
+ if (!url) {
706
+ return "";
707
+ }
708
+
709
+ const match = url.match(HOSTNAME);
710
+ return match ? match[1] : "";
711
+ } // This list of domains that count as internal domains is from
712
+
713
+ var AbsoluteUrl = Rule.makeRule({
714
+ name: "absolute-url",
715
+ severity: Rule.Severity.GUIDELINE,
716
+ selector: "link, image",
717
+ lint: function (state, content, nodes, match) {
718
+ const url = nodes[0].target;
719
+ const hostname = getHostname(url);
720
+
721
+ if (hostname === "khanacademy.org" || hostname.endsWith(".khanacademy.org")) {
722
+ 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.";
723
+ }
724
+ }
725
+ });
726
+
727
+ var BlockquotedMath = Rule.makeRule({
728
+ name: "blockquoted-math",
729
+ severity: Rule.Severity.WARNING,
730
+ selector: "blockQuote math, blockQuote blockMath",
731
+ message: "Blockquoted math:\nmath should not be indented."
732
+ });
733
+
734
+ var BlockquotedWidget = Rule.makeRule({
735
+ name: "blockquoted-widget",
736
+ severity: Rule.Severity.WARNING,
737
+ selector: "blockQuote widget",
738
+ message: "Blockquoted widget:\nwidgets should not be indented."
739
+ });
740
+
741
+ /* eslint-disable no-useless-escape */
742
+ var DoubleSpacingAfterTerminal = Rule.makeRule({
743
+ name: "double-spacing-after-terminal",
744
+ severity: Rule.Severity.BULK_WARNING,
745
+ selector: "paragraph",
746
+ pattern: /[.!\?] {2}/i,
747
+ message: "Use a single space after a sentence-ending period, or\nany other kind of terminal punctuation."
748
+ });
749
+
750
+ var ExtraContentSpacing = Rule.makeRule({
751
+ name: "extra-content-spacing",
752
+ selector: "paragraph",
753
+ pattern: /\s+$/,
754
+ applies: function (context) {
755
+ return context.contentType === "article";
756
+ },
757
+ message: "No extra whitespace at the end of content blocks."
758
+ });
759
+
760
+ var HeadingLevel1 = Rule.makeRule({
761
+ name: "heading-level-1",
762
+ severity: Rule.Severity.WARNING,
763
+ selector: "heading",
764
+ lint: function (state, content, nodes, match) {
765
+ if (nodes[0].level === 1) {
766
+ return "Don't use level-1 headings:\nBegin headings with two or more # characters.";
767
+ }
768
+ }
769
+ });
770
+
771
+ var HeadingLevelSkip = Rule.makeRule({
772
+ name: "heading-level-skip",
773
+ severity: Rule.Severity.WARNING,
774
+ selector: "heading ~ heading",
775
+ lint: function (state, content, nodes, match) {
776
+ const currentHeading = nodes[1];
777
+ const previousHeading = nodes[0]; // A heading can have a level less than, the same as
778
+ // or one more than the previous heading. But going up
779
+ // by 2 or more levels is not right
780
+
781
+ if (currentHeading.level > previousHeading.level + 1) {
782
+ return "Skipped heading level:\nthis heading is level ".concat(currentHeading.level, " but\nthe previous heading was level ").concat(previousHeading.level);
783
+ }
784
+ }
785
+ });
786
+
787
+ var HeadingSentenceCase = Rule.makeRule({
788
+ name: "heading-sentence-case",
789
+ severity: Rule.Severity.GUIDELINE,
790
+ selector: "heading",
791
+ pattern: /^\W*[a-z]/,
792
+ // first letter is lowercase
793
+ message: "First letter is lowercase:\nthe first letter of a heading should be capitalized."
794
+ });
795
+
796
+ // capitalized even in a title-case heading. See
797
+ // http://blog.apastyle.org/apastyle/2012/03/title-case-and-sentence-case-capitalization-in-apa-style.html
798
+
799
+ const littleWords = {
800
+ and: true,
801
+ nor: true,
802
+ but: true,
803
+ the: true,
804
+ for: true
805
+ };
806
+
807
+ function isCapitalized(word) {
808
+ const c = word[0];
809
+ return c === c.toUpperCase();
810
+ }
811
+
812
+ var HeadingTitleCase = Rule.makeRule({
813
+ name: "heading-title-case",
814
+ severity: Rule.Severity.GUIDELINE,
815
+ selector: "heading",
816
+ pattern: /[^\s:]\s+[A-Z]+[a-z]/,
817
+ locale: "en",
818
+ lint: function (state, content, nodes, match) {
819
+ // We want to assert that heading text is in sentence case, not
820
+ // title case. The pattern above requires a capital letter at the
821
+ // start of the heading and allows them after a colon, or in
822
+ // acronyms that are all capitalized.
823
+ //
824
+ // But we can't warn just because the pattern matched because
825
+ // proper nouns are also allowed bo be capitalized. We're not
826
+ // going to do dictionary lookup to check for proper nouns, so
827
+ // we try a heuristic: if the title is more than 3 words long
828
+ // and if all the words are capitalized or are on the list of
829
+ // words that don't get capitalized, then we'll assume that
830
+ // the heading is incorrectly in title case and will warn.
831
+ // But if there is at least one non-capitalized long word then
832
+ // we're not in title case and we should not warn.
833
+ //
834
+ // TODO(davidflanagan): if this rule causes a lot of false
835
+ // positives, we should tweak it or remove it. Note that it will
836
+ // fail for headings like "World War II in Russia"
837
+ //
838
+ // TODO(davidflanagan): This rule is specific to English.
839
+ // It is marked with a locale property above, but that is NYI
840
+ //
841
+ // for APA style rules for title case
842
+ const heading = content.trim();
843
+ let words = heading.split(/\s+/); // Remove the first word and the little words
844
+
845
+ words.shift();
846
+ words = words.filter( // eslint-disable-next-line no-prototype-builtins
847
+ w => w.length > 2 && !littleWords.hasOwnProperty(w)); // If there are at least 3 remaining words and all
848
+ // are capitalized, then the heading is in title case.
849
+
850
+ if (words.length >= 3 && words.every(w => isCapitalized(w))) {
851
+ 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.";
852
+ }
853
+ }
854
+ });
855
+
856
+ var ImageAltText = Rule.makeRule({
857
+ name: "image-alt-text",
858
+ severity: Rule.Severity.WARNING,
859
+ selector: "image",
860
+ lint: function (state, content, nodes, match) {
861
+ const image = nodes[0];
862
+
863
+ if (!image.alt || !image.alt.trim()) {
864
+ return "Images should have alt text:\nfor accessibility, all images should have alt text.\nSpecify alt text inside square brackets after the !.";
865
+ }
866
+
867
+ if (image.alt.length < 8) {
868
+ 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.");
869
+ }
870
+ }
871
+ });
872
+
873
+ var ImageInTable = Rule.makeRule({
874
+ name: "image-in-table",
875
+ severity: Rule.Severity.BULK_WARNING,
876
+ selector: "table image",
877
+ message: "Image in table:\ndo not put images inside of tables."
878
+ });
879
+
880
+ var ImageSpacesAroundUrls = Rule.makeRule({
881
+ name: "image-spaces-around-urls",
882
+ severity: Rule.Severity.ERROR,
883
+ selector: "image",
884
+ lint: function (state, content, nodes, match, context) {
885
+ const image = nodes[0];
886
+ const url = image.target; // The markdown parser strips leading and trailing spaces for us,
887
+ // but they're still a problem for our translation process, so
888
+ // we need to go check for them in the unparsed source string
889
+ // if we have it.
890
+
891
+ if (context && context.content) {
892
+ // Find the url in the original content and make sure that the
893
+ // character before is '(' and the character after is ')'
894
+ const index = context.content.indexOf(url);
895
+
896
+ if (index === -1) {
897
+ // It is not an error if we didn't find it.
898
+ return;
899
+ }
900
+
901
+ if (context.content[index - 1] !== "(" || context.content[index + url.length] !== ")") {
902
+ 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.";
903
+ }
904
+ }
905
+ }
906
+ });
907
+
908
+ // can't match specific widget types directly, this rule implements
909
+ // a number of image widget related rules in one place. This should
910
+ // slightly increase efficiency, but it means that if there is more
911
+ // than one problem with an image widget, the user will only see one
912
+ // problem at a time.
913
+
914
+ var ImageWidget = Rule.makeRule({
915
+ name: "image-widget",
916
+ severity: Rule.Severity.WARNING,
917
+ selector: "widget",
918
+ lint: function (state, content, nodes, match, context) {
919
+ // This rule only looks at image widgets
920
+ if (state.currentNode().widgetType !== "image") {
921
+ return;
922
+ } // If it can't find a definition for the widget it does nothing
923
+
924
+
925
+ const widget = context && context.widgets && context.widgets[state.currentNode().id];
926
+
927
+ if (!widget) {
928
+ return;
929
+ } // Make sure there is alt text
930
+
931
+
932
+ const alt = widget.options.alt;
933
+
934
+ if (!alt) {
935
+ 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.";
936
+ } // Make sure the alt text it is not trivial
937
+
938
+
939
+ if (alt.trim().length < 8) {
940
+ 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.");
941
+ } // Make sure there is no math in the caption
942
+
943
+
944
+ if (widget.options.caption && widget.options.caption.match(/[^\\]\$/)) {
945
+ return "No math in image captions:\nDon't include math expressions in image captions.";
946
+ }
947
+ }
948
+ });
949
+
950
+ var LinkClickHere = Rule.makeRule({
951
+ name: "link-click-here",
952
+ severity: Rule.Severity.WARNING,
953
+ selector: "link",
954
+ pattern: /click here/i,
955
+ message: "Inappropriate link text:\nDo not use the words \"click here\" in links."
956
+ });
957
+
958
+ var LongParagraph = Rule.makeRule({
959
+ name: "long-paragraph",
960
+ severity: Rule.Severity.GUIDELINE,
961
+ selector: "paragraph",
962
+ pattern: /^.{501,}/,
963
+ lint: function (state, content, nodes, match) {
964
+ return "Paragraph too long:\nThis paragraph is ".concat(content.length, " characters long.\nShorten it to 500 characters or fewer.");
965
+ }
966
+ });
967
+
968
+ var MathAdjacent = Rule.makeRule({
969
+ name: "math-adjacent",
970
+ severity: Rule.Severity.WARNING,
971
+ selector: "blockMath+blockMath",
972
+ message: "Adjacent math blocks:\ncombine the blocks between \\begin{align} and \\end{align}"
973
+ });
974
+
975
+ var MathAlignExtraBreak = Rule.makeRule({
976
+ name: "math-align-extra-break",
977
+ severity: Rule.Severity.WARNING,
978
+ selector: "blockMath",
979
+ pattern: /(\\{2,})\s*\\end{align}/,
980
+ message: "Extra space at end of block:\nDon't end an align block with backslashes"
981
+ });
982
+
983
+ var MathAlignLinebreaks = Rule.makeRule({
984
+ name: "math-align-linebreaks",
985
+ severity: Rule.Severity.WARNING,
986
+ selector: "blockMath",
987
+ // Match any align block with double backslashes in it
988
+ // Use [\s\S]* instead of .* so we match newlines as well.
989
+ pattern: /\\begin{align}[\s\S]*\\\\[\s\S]+\\end{align}/,
990
+ // Look for double backslashes and ensure that they are
991
+ // followed by optional space and another pair of backslashes.
992
+ // Note that this rule can't know where line breaks belong so
993
+ // it can't tell whether backslashes are completely missing. It just
994
+ // enforces that you don't have the wrong number of pairs of backslashes.
995
+ lint: function (state, content, nodes, match) {
996
+ let text = match[0];
997
+
998
+ while (text.length) {
999
+ const index = text.indexOf("\\\\");
1000
+
1001
+ if (index === -1) {
1002
+ // No more backslash pairs, so we found no lint
1003
+ return null;
1004
+ }
1005
+
1006
+ text = text.substring(index + 2); // Now we expect to find optional spaces, another pair of
1007
+ // backslashes, and more optional spaces not followed immediately
1008
+ // by another pair of backslashes.
1009
+
1010
+ const nextpair = text.match(/^\s*\\\\\s*(?!\\\\)/); // If that does not match then we either have too few or too
1011
+ // many pairs of backslashes.
1012
+
1013
+ if (!nextpair) {
1014
+ return "Use four backslashes between lines of an align block";
1015
+ } // If it did match, then, shorten the string and continue looping
1016
+ // (because a single align block may have multiple lines that
1017
+ // all must be separated by two sets of double backslashes).
1018
+
1019
+
1020
+ text = text.substring(nextpair[0].length);
1021
+ }
1022
+ }
1023
+ });
1024
+
1025
+ var MathEmpty = Rule.makeRule({
1026
+ name: "math-empty",
1027
+ severity: Rule.Severity.WARNING,
1028
+ selector: "math, blockMath",
1029
+ pattern: /^$/,
1030
+ message: "Empty math: don't use $$ in your markdown."
1031
+ });
1032
+
1033
+ var MathFontSize = Rule.makeRule({
1034
+ name: "math-font-size",
1035
+ severity: Rule.Severity.GUIDELINE,
1036
+ selector: "math, blockMath",
1037
+ pattern: /\\(tiny|Tiny|small|large|Large|LARGE|huge|Huge|scriptsize|normalsize)\s*{/,
1038
+ message: "Math font size:\nDon't change the default font size with \\Large{} or similar commands"
1039
+ });
1040
+
1041
+ var MathFrac = Rule.makeRule({
1042
+ name: "math-frac",
1043
+ severity: Rule.Severity.GUIDELINE,
1044
+ selector: "math, blockMath",
1045
+ pattern: /\\frac[ {]/,
1046
+ message: "Use \\dfrac instead of \\frac in your math expressions."
1047
+ });
1048
+
1049
+ var MathNested = Rule.makeRule({
1050
+ name: "math-nested",
1051
+ severity: Rule.Severity.ERROR,
1052
+ selector: "math, blockMath",
1053
+ pattern: /\\text{[^$}]*\$[^$}]*\$[^}]*}/,
1054
+ message: "Nested math:\nDon't nest math expressions inside \\text{} blocks"
1055
+ });
1056
+
1057
+ var MathStartsWithSpace = Rule.makeRule({
1058
+ name: "math-starts-with-space",
1059
+ severity: Rule.Severity.GUIDELINE,
1060
+ selector: "math, blockMath",
1061
+ pattern: /^\s*(~|\\qquad|\\quad|\\,|\\;|\\:|\\ |\\!|\\enspace|\\phantom)/,
1062
+ message: "Math starts with space:\nmath should not be indented. Do not begin math expressions with\nLaTeX space commands like ~, \\;, \\quad, or \\phantom"
1063
+ });
1064
+
1065
+ var MathTextEmpty = Rule.makeRule({
1066
+ name: "math-text-empty",
1067
+ severity: Rule.Severity.WARNING,
1068
+ selector: "math, blockMath",
1069
+ pattern: /\\text{\s*}/,
1070
+ message: "Empty \\text{} block in math expression"
1071
+ });
1072
+
1073
+ // Math and code hold their content directly and do not have text nodes
1074
+ // beneath them (unlike the HTML DOM) so this rule automatically does not
1075
+ // apply inside $$ or ``.
1076
+
1077
+ var MathWithoutDollars = Rule.makeRule({
1078
+ name: "math-without-dollars",
1079
+ severity: Rule.Severity.GUIDELINE,
1080
+ pattern: /\\\w+{[^}]*}|{|}/,
1081
+ message: "This looks like LaTeX:\ndid you mean to put it inside dollar signs?"
1082
+ });
1083
+
1084
+ var NestedLists = Rule.makeRule({
1085
+ name: "nested-lists",
1086
+ severity: Rule.Severity.WARNING,
1087
+ selector: "list list",
1088
+ message: "Nested lists:\nnested lists are hard to read on mobile devices;\ndo not use additional indentation."
1089
+ });
1090
+
1091
+ var Profanity = Rule.makeRule({
1092
+ name: "profanity",
1093
+ // This list could obviously be expanded a lot, but I figured we
1094
+ // could start with https://en.wikipedia.org/wiki/Seven_dirty_words
1095
+ pattern: /\b(shit|piss|fuck|cunt|cocksucker|motherfucker|tits)\b/i,
1096
+ message: "Avoid profanity"
1097
+ });
1098
+
1099
+ var TableMissingCells = Rule.makeRule({
1100
+ name: "table-missing-cells",
1101
+ severity: Rule.Severity.WARNING,
1102
+ selector: "table",
1103
+ lint: function (state, content, nodes, match) {
1104
+ const table = nodes[0];
1105
+ const headerLength = table.header.length;
1106
+ const rowLengths = table.cells.map(r => r.length);
1107
+
1108
+ for (let r = 0; r < rowLengths.length; r++) {
1109
+ if (rowLengths[r] !== headerLength) {
1110
+ return "Table rows don't match header:\nThe table header has ".concat(headerLength, " cells, but\nRow ").concat(r + 1, " has ").concat(rowLengths[r], " cells.");
1111
+ }
1112
+ }
1113
+ }
1114
+ });
1115
+
1116
+ // Math and code hold their content directly and do not have text nodes
1117
+ // beneath them (unlike the HTML DOM) so this rule automatically does not
1118
+ // apply inside $$ or ``.
1119
+
1120
+ var UnbalancedCodeDelimiters = Rule.makeRule({
1121
+ name: "unbalanced-code-delimiters",
1122
+ severity: Rule.Severity.ERROR,
1123
+ pattern: /[`~]+/,
1124
+ message: "Unbalanced code delimiters:\ncode blocks should begin and end with the same type and number of delimiters"
1125
+ });
1126
+
1127
+ var UnescapedDollar = Rule.makeRule({
1128
+ name: "unescaped-dollar",
1129
+ severity: Rule.Severity.ERROR,
1130
+ selector: "unescapedDollar",
1131
+ message: "Unescaped dollar sign:\nDollar signs must appear in pairs or be escaped as \\$"
1132
+ });
1133
+
1134
+ var WidgetInTable = Rule.makeRule({
1135
+ name: "widget-in-table",
1136
+ severity: Rule.Severity.BULK_WARNING,
1137
+ selector: "table widget",
1138
+ message: "Widget in table:\ndo not put widgets inside of tables."
1139
+ });
1140
+
1141
+ // TODO(davidflanagan):
1142
+ 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];
1143
+
1144
+ // that every node has a string-valued `type` property
1145
+
1146
+ // This is the TreeTransformer class described in detail at the
1147
+ // top of this file.
1148
+ class TreeTransformer {
1149
+ // To create a tree transformer, just pass the root node of the tree
1150
+ constructor(root) {
1151
+ _defineProperty(this, "root", void 0);
1152
+
1153
+ this.root = root;
1154
+ } // A utility function for determing whether an arbitrary value is a node
1155
+
1156
+
1157
+ static isNode(n) {
1158
+ return n && typeof n === "object" && typeof n.type === "string";
1159
+ } // Determines whether a value is a node with type "text" and has
1160
+ // a text-valued `content` property.
1161
+
1162
+
1163
+ static isTextNode(n) {
1164
+ return TreeTransformer.isNode(n) && n.type === "text" && typeof n.content === "string";
1165
+ } // This is the main entry point for the traverse() method. See the comment
1166
+ // at the top of this file for a detailed description. Note that this
1167
+ // method just creates a new TraversalState object to use for this
1168
+ // traversal and then invokes the internal _traverse() method to begin the
1169
+ // recursion.
1170
+
1171
+
1172
+ traverse(f) {
1173
+ this._traverse(this.root, new TraversalState(this.root), f);
1174
+ } // Do a post-order traversal of node and its descendants, invoking the
1175
+ // callback function f() once for each node and returning the concatenated
1176
+ // text content of the node and its descendants. f() is passed three
1177
+ // arguments: the current node, a TraversalState object representing the
1178
+ // current state of the traversal, and a string that holds the
1179
+ // concatenated text of the node and its descendants.
1180
+ //
1181
+ // This private method holds all the traversal logic and implementation
1182
+ // details. Note that this method uses the TraversalState object to store
1183
+ // information about the structure of the tree.
1184
+
1185
+
1186
+ _traverse( // eslint-disable-next-line flowtype/no-mutable-array
1187
+ n, state, f) {
1188
+ let content = "";
1189
+
1190
+ if (TreeTransformer.isNode(n)) {
1191
+ // If we were called on a node object, then we handle it
1192
+ // this way.
1193
+ const node = n; // safe cast; we just tested
1194
+ // Put the node on the stack before recursing on its children
1195
+
1196
+ state._containers.push(node);
1197
+
1198
+ state._ancestors.push(node); // Record the node's text content if it has any.
1199
+ // Usually this is for nodes with a type property of "text",
1200
+ // but other nodes types like "math" may also have content.
1201
+ // TODO(mdr): We found a new Flow error when upgrading:
1202
+ // "node.content (property `content` is missing in `TreeNode` [1].)"
1203
+ // $FlowFixMe[prop-missing](0.57.3->0.75.0)
1204
+
1205
+
1206
+ if (typeof node.content === "string") {
1207
+ content = node.content;
1208
+ } // Recurse on the node. If there was content above, then there
1209
+ // probably won't be any children to recurse on, but we check
1210
+ // anyway.
1211
+ //
1212
+ // If we wanted to make the traversal completely specific to the
1213
+ // actual Perseus parse trees that we'll be dealing with we could
1214
+ // put a switch statement here to dispatch on the node type
1215
+ // property with specific recursion steps for each known type of
1216
+ // node.
1217
+
1218
+
1219
+ const keys = Object.keys(node);
1220
+ keys.forEach(key => {
1221
+ // Never recurse on the type property
1222
+ if (key === "type") {
1223
+ return;
1224
+ } // Ignore properties that are null or primitive and only
1225
+ // recurse on objects and arrays. Note that we don't do a
1226
+ // isNode() check here. That is done in the recursive call to
1227
+ // _traverse(). Note that the recursive call on each child
1228
+ // returns the text content of the child and we add that
1229
+ // content to the content for this node. Also note that we
1230
+ // push the name of the property we're recursing over onto a
1231
+ // TraversalState stack.
1232
+
1233
+
1234
+ const value = node[key];
1235
+
1236
+ if (value && typeof value === "object") {
1237
+ state._indexes.push(key);
1238
+
1239
+ content += this._traverse(value, state, f);
1240
+
1241
+ state._indexes.pop();
1242
+ }
1243
+ }); // Restore the stacks after recursing on the children
1244
+
1245
+ state._currentNode = state._ancestors.pop();
1246
+
1247
+ state._containers.pop(); // And finally call the traversal callback for this node. Note
1248
+ // that this is post-order traversal. We call the callback on the
1249
+ // way back up the tree, not on the way down. That way we already
1250
+ // know all the content contained within the node.
1251
+
1252
+
1253
+ f(node, state, content);
1254
+ } else if (Array.isArray(n)) {
1255
+ // If we were called on an array instead of a node, then
1256
+ // this is the code we use to recurse.
1257
+ const nodes = n; // Push the array onto the stack. This will allow the
1258
+ // TraversalState object to locate siblings of this node.
1259
+
1260
+ state._containers.push(nodes); // Now loop through this array and recurse on each element in it.
1261
+ // Before recursing on an element, we push its array index on a
1262
+ // TraversalState stack so that the TraversalState sibling methods
1263
+ // can work. Note that TraversalState methods can alter the length
1264
+ // of the array, and change the index of the current node, so we
1265
+ // are careful here to test the array length on each iteration and
1266
+ // to reset the index when we pop the stack. Also note that we
1267
+ // concatentate the text content of the children.
1268
+
1269
+
1270
+ let index = 0;
1271
+
1272
+ while (index < nodes.length) {
1273
+ state._indexes.push(index);
1274
+
1275
+ content += this._traverse(nodes[index], state, f); // Casting to convince Flow that this is a number
1276
+
1277
+ index = state._indexes.pop() + 1;
1278
+ } // Pop the array off the stack. Note, however, that we do not call
1279
+ // the traversal callback on the array. That function is only
1280
+ // called for nodes, not arrays of nodes.
1281
+
1282
+
1283
+ state._containers.pop();
1284
+ } // The _traverse() method always returns the text content of
1285
+ // this node and its children. This is the one piece of state that
1286
+ // is not tracked in the TraversalState object.
1287
+
1288
+
1289
+ return content;
1290
+ }
1291
+
1292
+ } // An instance of this class is passed to the callback function for
1293
+ // each node traversed. The class itself is not exported, but its
1294
+ // methods define the API available to the traversal callback.
1295
+
1296
+ /**
1297
+ * This class represents the state of a tree traversal. An instance is created
1298
+ * by the traverse() method of the TreeTransformer class to maintain the state
1299
+ * for that traversal, and the instance is passed to the traversal callback
1300
+ * function for each node that is traversed. This class is not intended to be
1301
+ * instantiated directly, but is exported so that its type can be used for
1302
+ * Flow annotaions.
1303
+ **/
1304
+
1305
+ class TraversalState {
1306
+ // The root node of the tree being traversed
1307
+ // These are internal state properties. Use the accessor methods defined
1308
+ // below instead of using these properties directly. Note that the
1309
+ // _containers and _indexes stacks can have two different types of
1310
+ // elements, depending on whether we just recursed on an array or on a
1311
+ // node. This is hard for Flow to deal with, so you'll see a number of
1312
+ // Flow casts through the any type when working with these two properties.
1313
+ // eslint-disable-next-line flowtype/no-mutable-array
1314
+ // The constructor just stores the root node and creates empty stacks.
1315
+ constructor(root) {
1316
+ _defineProperty(this, "root", void 0);
1317
+
1318
+ _defineProperty(this, "_currentNode", void 0);
1319
+
1320
+ _defineProperty(this, "_containers", void 0);
1321
+
1322
+ _defineProperty(this, "_indexes", void 0);
1323
+
1324
+ _defineProperty(this, "_ancestors", void 0);
1325
+
1326
+ this.root = root; // When the callback is called, this property will hold the
1327
+ // node that is currently being traversed.
1328
+
1329
+ this._currentNode = null; // This is a stack of the objects and arrays that we've
1330
+ // traversed through before reaching the currentNode.
1331
+ // It is different than the ancestors array.
1332
+
1333
+ this._containers = new Stack(); // This stack has the same number of elements as the _containers
1334
+ // stack. The last element of this._indexes[] is the index of
1335
+ // the current node in the object or array that is the last element
1336
+ // of this._containers[]. If the last element of this._containers[] is
1337
+ // an array, then the last element of this stack will be a number.
1338
+ // Otherwise if the last container is an object, then the last index
1339
+ // will be a string property name.
1340
+
1341
+ this._indexes = new Stack(); // This is a stack of the ancestor nodes of the current one.
1342
+ // It is different than the containers[] stack because it only
1343
+ // includes nodes, not arrays.
1344
+
1345
+ this._ancestors = new Stack();
1346
+ }
1347
+ /**
1348
+ * Return the current node in the traversal. Any time the traversal
1349
+ * callback is called, this method will return the name value as the
1350
+ * first argument to the callback.
1351
+ */
1352
+
1353
+
1354
+ currentNode() {
1355
+ return this._currentNode || this.root;
1356
+ }
1357
+ /**
1358
+ * Return the parent of the current node, if there is one, or null.
1359
+ */
1360
+
1361
+
1362
+ parent() {
1363
+ return this._ancestors.top();
1364
+ }
1365
+ /**
1366
+ * Return an array of ancestor nodes. The first element of this array is
1367
+ * the same as this.parent() and the last element is the root node. If we
1368
+ * are currently at the root node, the the returned array will be empty.
1369
+ * This method makes a copy of the internal state, so modifications to the
1370
+ * returned array have no effect on the traversal.
1371
+ */
1372
+
1373
+
1374
+ ancestors() {
1375
+ return this._ancestors.values();
1376
+ }
1377
+ /**
1378
+ * Return the next sibling of this node, if it has one, or null otherwise.
1379
+ */
1380
+
1381
+
1382
+ nextSibling() {
1383
+ const siblings = this._containers.top(); // If we're at the root of the tree or if the parent is an
1384
+ // object instead of an array, then there are no siblings.
1385
+
1386
+
1387
+ if (!siblings || !Array.isArray(siblings)) {
1388
+ return null;
1389
+ } // The top index is a number because the top container is an array
1390
+
1391
+
1392
+ const index = this._indexes.top();
1393
+
1394
+ if (siblings.length > index + 1) {
1395
+ return siblings[index + 1];
1396
+ }
1397
+
1398
+ return null; // There is no next sibling
1399
+ }
1400
+ /**
1401
+ * Return the previous sibling of this node, if it has one, or null
1402
+ * otherwise.
1403
+ */
1404
+
1405
+
1406
+ previousSibling() {
1407
+ const siblings = this._containers.top(); // If we're at the root of the tree or if the parent is an
1408
+ // object instead of an array, then there are no siblings.
1409
+
1410
+
1411
+ if (!siblings || !Array.isArray(siblings)) {
1412
+ return null;
1413
+ } // The top index is a number because the top container is an array
1414
+
1415
+
1416
+ const index = this._indexes.top();
1417
+
1418
+ if (index > 0) {
1419
+ return siblings[index - 1];
1420
+ }
1421
+
1422
+ return null; // There is no previous sibling
1423
+ }
1424
+ /**
1425
+ * Remove the next sibling node (if there is one) from the tree. Returns
1426
+ * the removed sibling or null. This method makes it easy to traverse a
1427
+ * tree and concatenate adjacent text nodes into a single node.
1428
+ */
1429
+
1430
+
1431
+ removeNextSibling() {
1432
+ const siblings = this._containers.top();
1433
+
1434
+ if (siblings && Array.isArray(siblings)) {
1435
+ // top index is a number because top container is an array
1436
+ const index = this._indexes.top();
1437
+
1438
+ if (siblings.length > index + 1) {
1439
+ return siblings.splice(index + 1, 1)[0];
1440
+ }
1441
+ }
1442
+
1443
+ return null;
1444
+ }
1445
+ /**
1446
+ * Replace the current node in the tree with the specified nodes. If no
1447
+ * nodes are passed, this is a node deletion. If one node (or array) is
1448
+ * passed, this is a 1-for-1 replacement. If more than one node is passed
1449
+ * then this is a combination of deletion and insertion. The new node or
1450
+ * nodes will not be traversed, so this method can safely be used to
1451
+ * reparent the current node node beneath a new parent.
1452
+ *
1453
+ * This method throws an error if you attempt to replace the root node of
1454
+ * the tree.
1455
+ */
1456
+
1457
+
1458
+ replace() {
1459
+ const parent = this._containers.top();
1460
+
1461
+ if (!parent) {
1462
+ throw new perseusError.PerseusError("Can't replace the root of the tree", perseusError.Errors.Internal);
1463
+ } // The top of the container stack is either an array or an object
1464
+ // and the top of the indexes stack is a corresponding array index
1465
+ // or object property. This is hard for Flow, so we have to do some
1466
+ // unsafe casting and be careful when we use which cast version
1467
+
1468
+
1469
+ for (var _len = arguments.length, replacements = new Array(_len), _key = 0; _key < _len; _key++) {
1470
+ replacements[_key] = arguments[_key];
1471
+ }
1472
+
1473
+ if (Array.isArray(parent)) {
1474
+ const index = this._indexes.top(); // For an array parent we just splice the new nodes in
1475
+
1476
+
1477
+ parent.splice(index, 1, ...replacements); // Adjust the index to account for the changed array length.
1478
+ // We don't want to traverse any of the newly inserted nodes.
1479
+
1480
+ this._indexes.pop();
1481
+
1482
+ this._indexes.push(index + replacements.length - 1);
1483
+ } else {
1484
+ const property = this._indexes.top(); // For an object parent we care how many new nodes there are
1485
+
1486
+
1487
+ if (replacements.length === 0) {
1488
+ // Deletion
1489
+ delete parent[property];
1490
+ } else if (replacements.length === 1) {
1491
+ // Replacement
1492
+ parent[property] = replacements[0];
1493
+ } else {
1494
+ // Replace one node with an array of nodes
1495
+ parent[property] = replacements;
1496
+ }
1497
+ }
1498
+ }
1499
+ /**
1500
+ * Returns true if the current node has a previous sibling and false
1501
+ * otherwise. If this method returns false, then previousSibling() will
1502
+ * return null, and goToPreviousSibling() will throw an error.
1503
+ */
1504
+
1505
+
1506
+ hasPreviousSibling() {
1507
+ return Array.isArray(this._containers.top()) && this._indexes.top() > 0;
1508
+ }
1509
+ /**
1510
+ * Modify this traversal state object to have the state it would have had
1511
+ * when visiting the previous sibling. Note that you may want to use
1512
+ * clone() to make a copy before modifying the state object like this.
1513
+ * This mutator method is not typically used during ordinary tree
1514
+ * traversals, but is used by the Selector class for matching multi-node
1515
+ * selectors.
1516
+ */
1517
+
1518
+
1519
+ goToPreviousSibling() {
1520
+ if (!this.hasPreviousSibling()) {
1521
+ throw new perseusError.PerseusError("goToPreviousSibling(): node has no previous sibling", perseusError.Errors.Internal);
1522
+ }
1523
+
1524
+ this._currentNode = this.previousSibling(); // Since we know that we have a previous sibling, we know that
1525
+ // the value on top of the stack is a number, but we have to do
1526
+ // this unsafe cast because Flow doesn't know that.
1527
+
1528
+ const index = this._indexes.pop();
1529
+
1530
+ this._indexes.push(index - 1);
1531
+ }
1532
+ /**
1533
+ * Returns true if the current node has an ancestor and false otherwise.
1534
+ * If this method returns false, then the parent() method will return
1535
+ * null and goToParent() will throw an error
1536
+ */
1537
+
1538
+
1539
+ hasParent() {
1540
+ return this._ancestors.size() !== 0;
1541
+ }
1542
+ /**
1543
+ * Modify this object to look like it will look when we (later) visit the
1544
+ * parent node of this node. You should not modify the instance passed to
1545
+ * the tree traversal callback. Instead, make a copy with the clone()
1546
+ * method and modify that. This mutator method is not typically used
1547
+ * during ordinary tree traversals, but is used by the Selector class for
1548
+ * matching multi-node selectors that involve parent and ancestor
1549
+ * selectors.
1550
+ */
1551
+
1552
+
1553
+ goToParent() {
1554
+ if (!this.hasParent()) {
1555
+ throw new perseusError.PerseusError("goToParent(): node has no ancestor", perseusError.Errors.NotAllowed);
1556
+ }
1557
+
1558
+ this._currentNode = this._ancestors.pop(); // We need to pop the containers and indexes stacks at least once
1559
+ // and more as needed until we restore the invariant that
1560
+ // this._containers.top()[this.indexes.top()] === this._currentNode
1561
+ //
1562
+
1563
+ while (this._containers.size() && // This is safe, but easier to just disable flow than do casts
1564
+ // $FlowFixMe[incompatible-use]
1565
+ this._containers.top()[this._indexes.top()] !== this._currentNode) {
1566
+ this._containers.pop();
1567
+
1568
+ this._indexes.pop();
1569
+ }
1570
+ }
1571
+ /**
1572
+ * Return a new TraversalState object that is a copy of this one.
1573
+ * This method is useful in conjunction with the mutating methods
1574
+ * goToParent() and goToPreviousSibling().
1575
+ */
1576
+
1577
+
1578
+ clone() {
1579
+ const clone = new TraversalState(this.root);
1580
+ clone._currentNode = this._currentNode;
1581
+ clone._containers = this._containers.clone();
1582
+ clone._indexes = this._indexes.clone();
1583
+ clone._ancestors = this._ancestors.clone();
1584
+ return clone;
1585
+ }
1586
+ /**
1587
+ * Returns true if this TraversalState object is equal to that
1588
+ * TraversalState object, or false otherwise. This method exists
1589
+ * primarily for use by our unit tests.
1590
+ */
1591
+
1592
+
1593
+ equals(that) {
1594
+ return this.root === that.root && this._currentNode === that._currentNode && this._containers.equals(that._containers) && this._indexes.equals(that._indexes) && this._ancestors.equals(that._ancestors);
1595
+ }
1596
+
1597
+ }
1598
+ /**
1599
+ * This class is an internal utility that just treats an array as a stack
1600
+ * and gives us a top() method so we don't have to write expressions like
1601
+ * `ancestors[ancestors.length-1]`. The values() method automatically
1602
+ * copies the internal array so we don't have to worry about client code
1603
+ * modifying our internal stacks. The use of this Stack abstraction makes
1604
+ * the TraversalState class simpler in a number of places.
1605
+ */
1606
+
1607
+ class Stack {
1608
+ // eslint-disable-next-line flowtype/no-mutable-array
1609
+ constructor(array) {
1610
+ _defineProperty(this, "stack", void 0);
1611
+
1612
+ this.stack = array ? array.slice(0) : [];
1613
+ }
1614
+ /** Push a value onto the stack. */
1615
+
1616
+
1617
+ push(v) {
1618
+ this.stack.push(v);
1619
+ }
1620
+ /** Pop a value off of the stack. */
1621
+
1622
+
1623
+ pop() {
1624
+ return this.stack.pop();
1625
+ }
1626
+ /** Return the top value of the stack without popping it. */
1627
+
1628
+
1629
+ top() {
1630
+ return this.stack[this.stack.length - 1];
1631
+ }
1632
+ /** Return a copy of the stack as an array */
1633
+
1634
+
1635
+ values() {
1636
+ return this.stack.slice(0);
1637
+ }
1638
+ /** Return the number of elements in the stack */
1639
+
1640
+
1641
+ size() {
1642
+ return this.stack.length;
1643
+ }
1644
+ /** Return a string representation of the stack */
1645
+
1646
+
1647
+ toString() {
1648
+ return this.stack.toString();
1649
+ }
1650
+ /** Return a shallow copy of the stack */
1651
+
1652
+
1653
+ clone() {
1654
+ return new Stack(this.stack);
1655
+ }
1656
+ /**
1657
+ * Compare this stack to another and return true if the contents of
1658
+ * the two arrays are the same.
1659
+ */
1660
+
1661
+
1662
+ equals(that) {
1663
+ if (!that || !that.stack || that.stack.length !== this.stack.length) {
1664
+ return false;
1665
+ }
1666
+
1667
+ for (let i = 0; i < this.stack.length; i++) {
1668
+ if (this.stack[i] !== that.stack[i]) {
1669
+ return false;
1670
+ }
1671
+ }
1672
+
1673
+ return true;
1674
+ }
1675
+
1676
+ }
1677
+
1678
+ var propTypes = {exports: {}};
1679
+
1680
+ var reactIs = {exports: {}};
1681
+
1682
+ var reactIs_production_min = {};
1683
+
1684
+ /** @license React v16.13.1
1685
+ * react-is.production.min.js
1686
+ *
1687
+ * Copyright (c) Facebook, Inc. and its affiliates.
1688
+ *
1689
+ * This source code is licensed under the MIT license found in the
1690
+ * LICENSE file in the root directory of this source tree.
1691
+ */
1692
+
1693
+ var hasRequiredReactIs_production_min;
1694
+
1695
+ function requireReactIs_production_min () {
1696
+ if (hasRequiredReactIs_production_min) return reactIs_production_min;
1697
+ hasRequiredReactIs_production_min = 1;
1698
+ var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
1699
+ Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
1700
+ function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}reactIs_production_min.AsyncMode=l;reactIs_production_min.ConcurrentMode=m;reactIs_production_min.ContextConsumer=k;reactIs_production_min.ContextProvider=h;reactIs_production_min.Element=c;reactIs_production_min.ForwardRef=n;reactIs_production_min.Fragment=e;reactIs_production_min.Lazy=t;reactIs_production_min.Memo=r;reactIs_production_min.Portal=d;
1701
+ reactIs_production_min.Profiler=g;reactIs_production_min.StrictMode=f;reactIs_production_min.Suspense=p;reactIs_production_min.isAsyncMode=function(a){return A(a)||z(a)===l};reactIs_production_min.isConcurrentMode=A;reactIs_production_min.isContextConsumer=function(a){return z(a)===k};reactIs_production_min.isContextProvider=function(a){return z(a)===h};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};reactIs_production_min.isForwardRef=function(a){return z(a)===n};reactIs_production_min.isFragment=function(a){return z(a)===e};reactIs_production_min.isLazy=function(a){return z(a)===t};
1702
+ reactIs_production_min.isMemo=function(a){return z(a)===r};reactIs_production_min.isPortal=function(a){return z(a)===d};reactIs_production_min.isProfiler=function(a){return z(a)===g};reactIs_production_min.isStrictMode=function(a){return z(a)===f};reactIs_production_min.isSuspense=function(a){return z(a)===p};
1703
+ reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};reactIs_production_min.typeOf=z;
1704
+ return reactIs_production_min;
1705
+ }
1706
+
1707
+ var reactIs_development = {};
1708
+
1709
+ /** @license React v16.13.1
1710
+ * react-is.development.js
1711
+ *
1712
+ * Copyright (c) Facebook, Inc. and its affiliates.
1713
+ *
1714
+ * This source code is licensed under the MIT license found in the
1715
+ * LICENSE file in the root directory of this source tree.
1716
+ */
1717
+
1718
+ var hasRequiredReactIs_development;
1719
+
1720
+ function requireReactIs_development () {
1721
+ if (hasRequiredReactIs_development) return reactIs_development;
1722
+ hasRequiredReactIs_development = 1;
1723
+
1724
+
1725
+
1726
+ if (process.env.NODE_ENV !== "production") {
1727
+ (function() {
1728
+
1729
+ // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
1730
+ // nor polyfill, then a plain number is used for performance.
1731
+ var hasSymbol = typeof Symbol === 'function' && Symbol.for;
1732
+ var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
1733
+ var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
1734
+ var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
1735
+ var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
1736
+ var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
1737
+ var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
1738
+ var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
1739
+ // (unstable) APIs that have been removed. Can we remove the symbols?
1740
+
1741
+ var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
1742
+ var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
1743
+ var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
1744
+ var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
1745
+ var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
1746
+ var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
1747
+ var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
1748
+ var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
1749
+ var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
1750
+ var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
1751
+ var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
1752
+
1753
+ function isValidElementType(type) {
1754
+ return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
1755
+ type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
1756
+ }
1757
+
1758
+ function typeOf(object) {
1759
+ if (typeof object === 'object' && object !== null) {
1760
+ var $$typeof = object.$$typeof;
1761
+
1762
+ switch ($$typeof) {
1763
+ case REACT_ELEMENT_TYPE:
1764
+ var type = object.type;
1765
+
1766
+ switch (type) {
1767
+ case REACT_ASYNC_MODE_TYPE:
1768
+ case REACT_CONCURRENT_MODE_TYPE:
1769
+ case REACT_FRAGMENT_TYPE:
1770
+ case REACT_PROFILER_TYPE:
1771
+ case REACT_STRICT_MODE_TYPE:
1772
+ case REACT_SUSPENSE_TYPE:
1773
+ return type;
1774
+
1775
+ default:
1776
+ var $$typeofType = type && type.$$typeof;
1777
+
1778
+ switch ($$typeofType) {
1779
+ case REACT_CONTEXT_TYPE:
1780
+ case REACT_FORWARD_REF_TYPE:
1781
+ case REACT_LAZY_TYPE:
1782
+ case REACT_MEMO_TYPE:
1783
+ case REACT_PROVIDER_TYPE:
1784
+ return $$typeofType;
1785
+
1786
+ default:
1787
+ return $$typeof;
1788
+ }
1789
+
1790
+ }
1791
+
1792
+ case REACT_PORTAL_TYPE:
1793
+ return $$typeof;
1794
+ }
1795
+ }
1796
+
1797
+ return undefined;
1798
+ } // AsyncMode is deprecated along with isAsyncMode
1799
+
1800
+ var AsyncMode = REACT_ASYNC_MODE_TYPE;
1801
+ var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
1802
+ var ContextConsumer = REACT_CONTEXT_TYPE;
1803
+ var ContextProvider = REACT_PROVIDER_TYPE;
1804
+ var Element = REACT_ELEMENT_TYPE;
1805
+ var ForwardRef = REACT_FORWARD_REF_TYPE;
1806
+ var Fragment = REACT_FRAGMENT_TYPE;
1807
+ var Lazy = REACT_LAZY_TYPE;
1808
+ var Memo = REACT_MEMO_TYPE;
1809
+ var Portal = REACT_PORTAL_TYPE;
1810
+ var Profiler = REACT_PROFILER_TYPE;
1811
+ var StrictMode = REACT_STRICT_MODE_TYPE;
1812
+ var Suspense = REACT_SUSPENSE_TYPE;
1813
+ var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
1814
+
1815
+ function isAsyncMode(object) {
1816
+ {
1817
+ if (!hasWarnedAboutDeprecatedIsAsyncMode) {
1818
+ hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
1819
+
1820
+ console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
1821
+ }
1822
+ }
1823
+
1824
+ return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
1825
+ }
1826
+ function isConcurrentMode(object) {
1827
+ return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
1828
+ }
1829
+ function isContextConsumer(object) {
1830
+ return typeOf(object) === REACT_CONTEXT_TYPE;
1831
+ }
1832
+ function isContextProvider(object) {
1833
+ return typeOf(object) === REACT_PROVIDER_TYPE;
1834
+ }
1835
+ function isElement(object) {
1836
+ return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1837
+ }
1838
+ function isForwardRef(object) {
1839
+ return typeOf(object) === REACT_FORWARD_REF_TYPE;
1840
+ }
1841
+ function isFragment(object) {
1842
+ return typeOf(object) === REACT_FRAGMENT_TYPE;
1843
+ }
1844
+ function isLazy(object) {
1845
+ return typeOf(object) === REACT_LAZY_TYPE;
1846
+ }
1847
+ function isMemo(object) {
1848
+ return typeOf(object) === REACT_MEMO_TYPE;
1849
+ }
1850
+ function isPortal(object) {
1851
+ return typeOf(object) === REACT_PORTAL_TYPE;
1852
+ }
1853
+ function isProfiler(object) {
1854
+ return typeOf(object) === REACT_PROFILER_TYPE;
1855
+ }
1856
+ function isStrictMode(object) {
1857
+ return typeOf(object) === REACT_STRICT_MODE_TYPE;
1858
+ }
1859
+ function isSuspense(object) {
1860
+ return typeOf(object) === REACT_SUSPENSE_TYPE;
1861
+ }
1862
+
1863
+ reactIs_development.AsyncMode = AsyncMode;
1864
+ reactIs_development.ConcurrentMode = ConcurrentMode;
1865
+ reactIs_development.ContextConsumer = ContextConsumer;
1866
+ reactIs_development.ContextProvider = ContextProvider;
1867
+ reactIs_development.Element = Element;
1868
+ reactIs_development.ForwardRef = ForwardRef;
1869
+ reactIs_development.Fragment = Fragment;
1870
+ reactIs_development.Lazy = Lazy;
1871
+ reactIs_development.Memo = Memo;
1872
+ reactIs_development.Portal = Portal;
1873
+ reactIs_development.Profiler = Profiler;
1874
+ reactIs_development.StrictMode = StrictMode;
1875
+ reactIs_development.Suspense = Suspense;
1876
+ reactIs_development.isAsyncMode = isAsyncMode;
1877
+ reactIs_development.isConcurrentMode = isConcurrentMode;
1878
+ reactIs_development.isContextConsumer = isContextConsumer;
1879
+ reactIs_development.isContextProvider = isContextProvider;
1880
+ reactIs_development.isElement = isElement;
1881
+ reactIs_development.isForwardRef = isForwardRef;
1882
+ reactIs_development.isFragment = isFragment;
1883
+ reactIs_development.isLazy = isLazy;
1884
+ reactIs_development.isMemo = isMemo;
1885
+ reactIs_development.isPortal = isPortal;
1886
+ reactIs_development.isProfiler = isProfiler;
1887
+ reactIs_development.isStrictMode = isStrictMode;
1888
+ reactIs_development.isSuspense = isSuspense;
1889
+ reactIs_development.isValidElementType = isValidElementType;
1890
+ reactIs_development.typeOf = typeOf;
1891
+ })();
1892
+ }
1893
+ return reactIs_development;
1894
+ }
1895
+
1896
+ var hasRequiredReactIs;
1897
+
1898
+ function requireReactIs () {
1899
+ if (hasRequiredReactIs) return reactIs.exports;
1900
+ hasRequiredReactIs = 1;
1901
+ (function (module) {
1902
+
1903
+ if (process.env.NODE_ENV === 'production') {
1904
+ module.exports = requireReactIs_production_min();
1905
+ } else {
1906
+ module.exports = requireReactIs_development();
1907
+ }
1908
+ } (reactIs));
1909
+ return reactIs.exports;
1910
+ }
1911
+
1912
+ /*
1913
+ object-assign
1914
+ (c) Sindre Sorhus
1915
+ @license MIT
1916
+ */
1917
+
1918
+ var objectAssign;
1919
+ var hasRequiredObjectAssign;
1920
+
1921
+ function requireObjectAssign () {
1922
+ if (hasRequiredObjectAssign) return objectAssign;
1923
+ hasRequiredObjectAssign = 1;
1924
+ /* eslint-disable no-unused-vars */
1925
+ var getOwnPropertySymbols = Object.getOwnPropertySymbols;
1926
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
1927
+ var propIsEnumerable = Object.prototype.propertyIsEnumerable;
1928
+
1929
+ function toObject(val) {
1930
+ if (val === null || val === undefined) {
1931
+ throw new TypeError('Object.assign cannot be called with null or undefined');
1932
+ }
1933
+
1934
+ return Object(val);
1935
+ }
1936
+
1937
+ function shouldUseNative() {
1938
+ try {
1939
+ if (!Object.assign) {
1940
+ return false;
1941
+ }
1942
+
1943
+ // Detect buggy property enumeration order in older V8 versions.
1944
+
1945
+ // https://bugs.chromium.org/p/v8/issues/detail?id=4118
1946
+ var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
1947
+ test1[5] = 'de';
1948
+ if (Object.getOwnPropertyNames(test1)[0] === '5') {
1949
+ return false;
1950
+ }
1951
+
1952
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
1953
+ var test2 = {};
1954
+ for (var i = 0; i < 10; i++) {
1955
+ test2['_' + String.fromCharCode(i)] = i;
1956
+ }
1957
+ var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
1958
+ return test2[n];
1959
+ });
1960
+ if (order2.join('') !== '0123456789') {
1961
+ return false;
1962
+ }
1963
+
1964
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
1965
+ var test3 = {};
1966
+ 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
1967
+ test3[letter] = letter;
1968
+ });
1969
+ if (Object.keys(Object.assign({}, test3)).join('') !==
1970
+ 'abcdefghijklmnopqrst') {
1971
+ return false;
1972
+ }
1973
+
1974
+ return true;
1975
+ } catch (err) {
1976
+ // We don't expect any of the above to throw, but better to be safe.
1977
+ return false;
1978
+ }
1979
+ }
1980
+
1981
+ objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
1982
+ var from;
1983
+ var to = toObject(target);
1984
+ var symbols;
1985
+
1986
+ for (var s = 1; s < arguments.length; s++) {
1987
+ from = Object(arguments[s]);
1988
+
1989
+ for (var key in from) {
1990
+ if (hasOwnProperty.call(from, key)) {
1991
+ to[key] = from[key];
1992
+ }
1993
+ }
1994
+
1995
+ if (getOwnPropertySymbols) {
1996
+ symbols = getOwnPropertySymbols(from);
1997
+ for (var i = 0; i < symbols.length; i++) {
1998
+ if (propIsEnumerable.call(from, symbols[i])) {
1999
+ to[symbols[i]] = from[symbols[i]];
2000
+ }
2001
+ }
2002
+ }
2003
+ }
2004
+
2005
+ return to;
2006
+ };
2007
+ return objectAssign;
2008
+ }
2009
+
2010
+ /**
2011
+ * Copyright (c) 2013-present, Facebook, Inc.
2012
+ *
2013
+ * This source code is licensed under the MIT license found in the
2014
+ * LICENSE file in the root directory of this source tree.
2015
+ */
2016
+
2017
+ var ReactPropTypesSecret_1;
2018
+ var hasRequiredReactPropTypesSecret;
2019
+
2020
+ function requireReactPropTypesSecret () {
2021
+ if (hasRequiredReactPropTypesSecret) return ReactPropTypesSecret_1;
2022
+ hasRequiredReactPropTypesSecret = 1;
2023
+
2024
+ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
2025
+
2026
+ ReactPropTypesSecret_1 = ReactPropTypesSecret;
2027
+ return ReactPropTypesSecret_1;
2028
+ }
2029
+
2030
+ var has;
2031
+ var hasRequiredHas;
2032
+
2033
+ function requireHas () {
2034
+ if (hasRequiredHas) return has;
2035
+ hasRequiredHas = 1;
2036
+ has = Function.call.bind(Object.prototype.hasOwnProperty);
2037
+ return has;
2038
+ }
2039
+
2040
+ /**
2041
+ * Copyright (c) 2013-present, Facebook, Inc.
2042
+ *
2043
+ * This source code is licensed under the MIT license found in the
2044
+ * LICENSE file in the root directory of this source tree.
2045
+ */
2046
+
2047
+ var checkPropTypes_1;
2048
+ var hasRequiredCheckPropTypes;
2049
+
2050
+ function requireCheckPropTypes () {
2051
+ if (hasRequiredCheckPropTypes) return checkPropTypes_1;
2052
+ hasRequiredCheckPropTypes = 1;
2053
+
2054
+ var printWarning = function() {};
2055
+
2056
+ if (process.env.NODE_ENV !== 'production') {
2057
+ var ReactPropTypesSecret = requireReactPropTypesSecret();
2058
+ var loggedTypeFailures = {};
2059
+ var has = requireHas();
2060
+
2061
+ printWarning = function(text) {
2062
+ var message = 'Warning: ' + text;
2063
+ if (typeof console !== 'undefined') {
2064
+ console.error(message);
2065
+ }
2066
+ try {
2067
+ // --- Welcome to debugging React ---
2068
+ // This error was thrown as a convenience so that you can use this stack
2069
+ // to find the callsite that caused this warning to fire.
2070
+ throw new Error(message);
2071
+ } catch (x) { /**/ }
2072
+ };
2073
+ }
2074
+
2075
+ /**
2076
+ * Assert that the values match with the type specs.
2077
+ * Error messages are memorized and will only be shown once.
2078
+ *
2079
+ * @param {object} typeSpecs Map of name to a ReactPropType
2080
+ * @param {object} values Runtime values that need to be type-checked
2081
+ * @param {string} location e.g. "prop", "context", "child context"
2082
+ * @param {string} componentName Name of the component for error messages.
2083
+ * @param {?Function} getStack Returns the component stack.
2084
+ * @private
2085
+ */
2086
+ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
2087
+ if (process.env.NODE_ENV !== 'production') {
2088
+ for (var typeSpecName in typeSpecs) {
2089
+ if (has(typeSpecs, typeSpecName)) {
2090
+ var error;
2091
+ // Prop type validation may throw. In case they do, we don't want to
2092
+ // fail the render phase where it didn't fail before. So we log it.
2093
+ // After these have been cleaned up, we'll let them throw.
2094
+ try {
2095
+ // This is intentionally an invariant that gets caught. It's the same
2096
+ // behavior as without this statement except with a better message.
2097
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
2098
+ var err = Error(
2099
+ (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
2100
+ 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' +
2101
+ 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'
2102
+ );
2103
+ err.name = 'Invariant Violation';
2104
+ throw err;
2105
+ }
2106
+ error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
2107
+ } catch (ex) {
2108
+ error = ex;
2109
+ }
2110
+ if (error && !(error instanceof Error)) {
2111
+ printWarning(
2112
+ (componentName || 'React class') + ': type specification of ' +
2113
+ location + ' `' + typeSpecName + '` is invalid; the type checker ' +
2114
+ 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
2115
+ 'You may have forgotten to pass an argument to the type checker ' +
2116
+ 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
2117
+ 'shape all require an argument).'
2118
+ );
2119
+ }
2120
+ if (error instanceof Error && !(error.message in loggedTypeFailures)) {
2121
+ // Only monitor this failure once because there tends to be a lot of the
2122
+ // same error.
2123
+ loggedTypeFailures[error.message] = true;
2124
+
2125
+ var stack = getStack ? getStack() : '';
2126
+
2127
+ printWarning(
2128
+ 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
2129
+ );
2130
+ }
2131
+ }
2132
+ }
2133
+ }
2134
+ }
2135
+
2136
+ /**
2137
+ * Resets warning cache when testing.
2138
+ *
2139
+ * @private
2140
+ */
2141
+ checkPropTypes.resetWarningCache = function() {
2142
+ if (process.env.NODE_ENV !== 'production') {
2143
+ loggedTypeFailures = {};
2144
+ }
2145
+ };
2146
+
2147
+ checkPropTypes_1 = checkPropTypes;
2148
+ return checkPropTypes_1;
2149
+ }
2150
+
2151
+ /**
2152
+ * Copyright (c) 2013-present, Facebook, Inc.
2153
+ *
2154
+ * This source code is licensed under the MIT license found in the
2155
+ * LICENSE file in the root directory of this source tree.
2156
+ */
2157
+
2158
+ var factoryWithTypeCheckers;
2159
+ var hasRequiredFactoryWithTypeCheckers;
2160
+
2161
+ function requireFactoryWithTypeCheckers () {
2162
+ if (hasRequiredFactoryWithTypeCheckers) return factoryWithTypeCheckers;
2163
+ hasRequiredFactoryWithTypeCheckers = 1;
2164
+
2165
+ var ReactIs = requireReactIs();
2166
+ var assign = requireObjectAssign();
2167
+
2168
+ var ReactPropTypesSecret = requireReactPropTypesSecret();
2169
+ var has = requireHas();
2170
+ var checkPropTypes = requireCheckPropTypes();
2171
+
2172
+ var printWarning = function() {};
2173
+
2174
+ if (process.env.NODE_ENV !== 'production') {
2175
+ printWarning = function(text) {
2176
+ var message = 'Warning: ' + text;
2177
+ if (typeof console !== 'undefined') {
2178
+ console.error(message);
2179
+ }
2180
+ try {
2181
+ // --- Welcome to debugging React ---
2182
+ // This error was thrown as a convenience so that you can use this stack
2183
+ // to find the callsite that caused this warning to fire.
2184
+ throw new Error(message);
2185
+ } catch (x) {}
2186
+ };
2187
+ }
2188
+
2189
+ function emptyFunctionThatReturnsNull() {
2190
+ return null;
2191
+ }
2192
+
2193
+ factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
2194
+ /* global Symbol */
2195
+ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
2196
+ var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
2197
+
2198
+ /**
2199
+ * Returns the iterator method function contained on the iterable object.
2200
+ *
2201
+ * Be sure to invoke the function with the iterable as context:
2202
+ *
2203
+ * var iteratorFn = getIteratorFn(myIterable);
2204
+ * if (iteratorFn) {
2205
+ * var iterator = iteratorFn.call(myIterable);
2206
+ * ...
2207
+ * }
2208
+ *
2209
+ * @param {?object} maybeIterable
2210
+ * @return {?function}
2211
+ */
2212
+ function getIteratorFn(maybeIterable) {
2213
+ var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
2214
+ if (typeof iteratorFn === 'function') {
2215
+ return iteratorFn;
2216
+ }
2217
+ }
2218
+
2219
+ /**
2220
+ * Collection of methods that allow declaration and validation of props that are
2221
+ * supplied to React components. Example usage:
2222
+ *
2223
+ * var Props = require('ReactPropTypes');
2224
+ * var MyArticle = React.createClass({
2225
+ * propTypes: {
2226
+ * // An optional string prop named "description".
2227
+ * description: Props.string,
2228
+ *
2229
+ * // A required enum prop named "category".
2230
+ * category: Props.oneOf(['News','Photos']).isRequired,
2231
+ *
2232
+ * // A prop named "dialog" that requires an instance of Dialog.
2233
+ * dialog: Props.instanceOf(Dialog).isRequired
2234
+ * },
2235
+ * render: function() { ... }
2236
+ * });
2237
+ *
2238
+ * A more formal specification of how these methods are used:
2239
+ *
2240
+ * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
2241
+ * decl := ReactPropTypes.{type}(.isRequired)?
2242
+ *
2243
+ * Each and every declaration produces a function with the same signature. This
2244
+ * allows the creation of custom validation functions. For example:
2245
+ *
2246
+ * var MyLink = React.createClass({
2247
+ * propTypes: {
2248
+ * // An optional string or URI prop named "href".
2249
+ * href: function(props, propName, componentName) {
2250
+ * var propValue = props[propName];
2251
+ * if (propValue != null && typeof propValue !== 'string' &&
2252
+ * !(propValue instanceof URI)) {
2253
+ * return new Error(
2254
+ * 'Expected a string or an URI for ' + propName + ' in ' +
2255
+ * componentName
2256
+ * );
2257
+ * }
2258
+ * }
2259
+ * },
2260
+ * render: function() {...}
2261
+ * });
2262
+ *
2263
+ * @internal
2264
+ */
2265
+
2266
+ var ANONYMOUS = '<<anonymous>>';
2267
+
2268
+ // Important!
2269
+ // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
2270
+ var ReactPropTypes = {
2271
+ array: createPrimitiveTypeChecker('array'),
2272
+ bigint: createPrimitiveTypeChecker('bigint'),
2273
+ bool: createPrimitiveTypeChecker('boolean'),
2274
+ func: createPrimitiveTypeChecker('function'),
2275
+ number: createPrimitiveTypeChecker('number'),
2276
+ object: createPrimitiveTypeChecker('object'),
2277
+ string: createPrimitiveTypeChecker('string'),
2278
+ symbol: createPrimitiveTypeChecker('symbol'),
2279
+
2280
+ any: createAnyTypeChecker(),
2281
+ arrayOf: createArrayOfTypeChecker,
2282
+ element: createElementTypeChecker(),
2283
+ elementType: createElementTypeTypeChecker(),
2284
+ instanceOf: createInstanceTypeChecker,
2285
+ node: createNodeChecker(),
2286
+ objectOf: createObjectOfTypeChecker,
2287
+ oneOf: createEnumTypeChecker,
2288
+ oneOfType: createUnionTypeChecker,
2289
+ shape: createShapeTypeChecker,
2290
+ exact: createStrictShapeTypeChecker,
2291
+ };
2292
+
2293
+ /**
2294
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
2295
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
2296
+ */
2297
+ /*eslint-disable no-self-compare*/
2298
+ function is(x, y) {
2299
+ // SameValue algorithm
2300
+ if (x === y) {
2301
+ // Steps 1-5, 7-10
2302
+ // Steps 6.b-6.e: +0 != -0
2303
+ return x !== 0 || 1 / x === 1 / y;
2304
+ } else {
2305
+ // Step 6.a: NaN == NaN
2306
+ return x !== x && y !== y;
2307
+ }
2308
+ }
2309
+ /*eslint-enable no-self-compare*/
2310
+
2311
+ /**
2312
+ * We use an Error-like object for backward compatibility as people may call
2313
+ * PropTypes directly and inspect their output. However, we don't use real
2314
+ * Errors anymore. We don't inspect their stack anyway, and creating them
2315
+ * is prohibitively expensive if they are created too often, such as what
2316
+ * happens in oneOfType() for any type before the one that matched.
2317
+ */
2318
+ function PropTypeError(message, data) {
2319
+ this.message = message;
2320
+ this.data = data && typeof data === 'object' ? data: {};
2321
+ this.stack = '';
2322
+ }
2323
+ // Make `instanceof Error` still work for returned errors.
2324
+ PropTypeError.prototype = Error.prototype;
2325
+
2326
+ function createChainableTypeChecker(validate) {
2327
+ if (process.env.NODE_ENV !== 'production') {
2328
+ var manualPropTypeCallCache = {};
2329
+ var manualPropTypeWarningCount = 0;
2330
+ }
2331
+ function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
2332
+ componentName = componentName || ANONYMOUS;
2333
+ propFullName = propFullName || propName;
2334
+
2335
+ if (secret !== ReactPropTypesSecret) {
2336
+ if (throwOnDirectAccess) {
2337
+ // New behavior only for users of `prop-types` package
2338
+ var err = new Error(
2339
+ 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
2340
+ 'Use `PropTypes.checkPropTypes()` to call them. ' +
2341
+ 'Read more at http://fb.me/use-check-prop-types'
2342
+ );
2343
+ err.name = 'Invariant Violation';
2344
+ throw err;
2345
+ } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
2346
+ // Old behavior for people using React.PropTypes
2347
+ var cacheKey = componentName + ':' + propName;
2348
+ if (
2349
+ !manualPropTypeCallCache[cacheKey] &&
2350
+ // Avoid spamming the console because they are often not actionable except for lib authors
2351
+ manualPropTypeWarningCount < 3
2352
+ ) {
2353
+ printWarning(
2354
+ 'You are manually calling a React.PropTypes validation ' +
2355
+ 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
2356
+ 'and will throw in the standalone `prop-types` package. ' +
2357
+ 'You may be seeing this warning due to a third-party PropTypes ' +
2358
+ 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
2359
+ );
2360
+ manualPropTypeCallCache[cacheKey] = true;
2361
+ manualPropTypeWarningCount++;
2362
+ }
2363
+ }
2364
+ }
2365
+ if (props[propName] == null) {
2366
+ if (isRequired) {
2367
+ if (props[propName] === null) {
2368
+ return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
2369
+ }
2370
+ return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
2371
+ }
2372
+ return null;
2373
+ } else {
2374
+ return validate(props, propName, componentName, location, propFullName);
2375
+ }
2376
+ }
2377
+
2378
+ var chainedCheckType = checkType.bind(null, false);
2379
+ chainedCheckType.isRequired = checkType.bind(null, true);
2380
+
2381
+ return chainedCheckType;
2382
+ }
2383
+
2384
+ function createPrimitiveTypeChecker(expectedType) {
2385
+ function validate(props, propName, componentName, location, propFullName, secret) {
2386
+ var propValue = props[propName];
2387
+ var propType = getPropType(propValue);
2388
+ if (propType !== expectedType) {
2389
+ // `propValue` being instance of, say, date/regexp, pass the 'object'
2390
+ // check, but we can offer a more precise error message here rather than
2391
+ // 'of type `object`'.
2392
+ var preciseType = getPreciseType(propValue);
2393
+
2394
+ return new PropTypeError(
2395
+ 'Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'),
2396
+ {expectedType: expectedType}
2397
+ );
2398
+ }
2399
+ return null;
2400
+ }
2401
+ return createChainableTypeChecker(validate);
2402
+ }
2403
+
2404
+ function createAnyTypeChecker() {
2405
+ return createChainableTypeChecker(emptyFunctionThatReturnsNull);
2406
+ }
2407
+
2408
+ function createArrayOfTypeChecker(typeChecker) {
2409
+ function validate(props, propName, componentName, location, propFullName) {
2410
+ if (typeof typeChecker !== 'function') {
2411
+ return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
2412
+ }
2413
+ var propValue = props[propName];
2414
+ if (!Array.isArray(propValue)) {
2415
+ var propType = getPropType(propValue);
2416
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
2417
+ }
2418
+ for (var i = 0; i < propValue.length; i++) {
2419
+ var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
2420
+ if (error instanceof Error) {
2421
+ return error;
2422
+ }
2423
+ }
2424
+ return null;
2425
+ }
2426
+ return createChainableTypeChecker(validate);
2427
+ }
2428
+
2429
+ function createElementTypeChecker() {
2430
+ function validate(props, propName, componentName, location, propFullName) {
2431
+ var propValue = props[propName];
2432
+ if (!isValidElement(propValue)) {
2433
+ var propType = getPropType(propValue);
2434
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
2435
+ }
2436
+ return null;
2437
+ }
2438
+ return createChainableTypeChecker(validate);
2439
+ }
2440
+
2441
+ function createElementTypeTypeChecker() {
2442
+ function validate(props, propName, componentName, location, propFullName) {
2443
+ var propValue = props[propName];
2444
+ if (!ReactIs.isValidElementType(propValue)) {
2445
+ var propType = getPropType(propValue);
2446
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
2447
+ }
2448
+ return null;
2449
+ }
2450
+ return createChainableTypeChecker(validate);
2451
+ }
2452
+
2453
+ function createInstanceTypeChecker(expectedClass) {
2454
+ function validate(props, propName, componentName, location, propFullName) {
2455
+ if (!(props[propName] instanceof expectedClass)) {
2456
+ var expectedClassName = expectedClass.name || ANONYMOUS;
2457
+ var actualClassName = getClassName(props[propName]);
2458
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
2459
+ }
2460
+ return null;
2461
+ }
2462
+ return createChainableTypeChecker(validate);
2463
+ }
2464
+
2465
+ function createEnumTypeChecker(expectedValues) {
2466
+ if (!Array.isArray(expectedValues)) {
2467
+ if (process.env.NODE_ENV !== 'production') {
2468
+ if (arguments.length > 1) {
2469
+ printWarning(
2470
+ 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
2471
+ 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
2472
+ );
2473
+ } else {
2474
+ printWarning('Invalid argument supplied to oneOf, expected an array.');
2475
+ }
2476
+ }
2477
+ return emptyFunctionThatReturnsNull;
2478
+ }
2479
+
2480
+ function validate(props, propName, componentName, location, propFullName) {
2481
+ var propValue = props[propName];
2482
+ for (var i = 0; i < expectedValues.length; i++) {
2483
+ if (is(propValue, expectedValues[i])) {
2484
+ return null;
2485
+ }
2486
+ }
2487
+
2488
+ var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
2489
+ var type = getPreciseType(value);
2490
+ if (type === 'symbol') {
2491
+ return String(value);
2492
+ }
2493
+ return value;
2494
+ });
2495
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
2496
+ }
2497
+ return createChainableTypeChecker(validate);
2498
+ }
2499
+
2500
+ function createObjectOfTypeChecker(typeChecker) {
2501
+ function validate(props, propName, componentName, location, propFullName) {
2502
+ if (typeof typeChecker !== 'function') {
2503
+ return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
2504
+ }
2505
+ var propValue = props[propName];
2506
+ var propType = getPropType(propValue);
2507
+ if (propType !== 'object') {
2508
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
2509
+ }
2510
+ for (var key in propValue) {
2511
+ if (has(propValue, key)) {
2512
+ var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
2513
+ if (error instanceof Error) {
2514
+ return error;
2515
+ }
2516
+ }
2517
+ }
2518
+ return null;
2519
+ }
2520
+ return createChainableTypeChecker(validate);
2521
+ }
2522
+
2523
+ function createUnionTypeChecker(arrayOfTypeCheckers) {
2524
+ if (!Array.isArray(arrayOfTypeCheckers)) {
2525
+ process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
2526
+ return emptyFunctionThatReturnsNull;
2527
+ }
2528
+
2529
+ for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
2530
+ var checker = arrayOfTypeCheckers[i];
2531
+ if (typeof checker !== 'function') {
2532
+ printWarning(
2533
+ 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
2534
+ 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
2535
+ );
2536
+ return emptyFunctionThatReturnsNull;
2537
+ }
2538
+ }
2539
+
2540
+ function validate(props, propName, componentName, location, propFullName) {
2541
+ var expectedTypes = [];
2542
+ for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
2543
+ var checker = arrayOfTypeCheckers[i];
2544
+ var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
2545
+ if (checkerResult == null) {
2546
+ return null;
2547
+ }
2548
+ if (checkerResult.data && has(checkerResult.data, 'expectedType')) {
2549
+ expectedTypes.push(checkerResult.data.expectedType);
2550
+ }
2551
+ }
2552
+ var expectedTypesMessage = (expectedTypes.length > 0) ? ', expected one of type [' + expectedTypes.join(', ') + ']': '';
2553
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.'));
2554
+ }
2555
+ return createChainableTypeChecker(validate);
2556
+ }
2557
+
2558
+ function createNodeChecker() {
2559
+ function validate(props, propName, componentName, location, propFullName) {
2560
+ if (!isNode(props[propName])) {
2561
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
2562
+ }
2563
+ return null;
2564
+ }
2565
+ return createChainableTypeChecker(validate);
2566
+ }
2567
+
2568
+ function invalidValidatorError(componentName, location, propFullName, key, type) {
2569
+ return new PropTypeError(
2570
+ (componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' +
2571
+ 'it must be a function, usually from the `prop-types` package, but received `' + type + '`.'
2572
+ );
2573
+ }
2574
+
2575
+ function createShapeTypeChecker(shapeTypes) {
2576
+ function validate(props, propName, componentName, location, propFullName) {
2577
+ var propValue = props[propName];
2578
+ var propType = getPropType(propValue);
2579
+ if (propType !== 'object') {
2580
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
2581
+ }
2582
+ for (var key in shapeTypes) {
2583
+ var checker = shapeTypes[key];
2584
+ if (typeof checker !== 'function') {
2585
+ return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
2586
+ }
2587
+ var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
2588
+ if (error) {
2589
+ return error;
2590
+ }
2591
+ }
2592
+ return null;
2593
+ }
2594
+ return createChainableTypeChecker(validate);
2595
+ }
2596
+
2597
+ function createStrictShapeTypeChecker(shapeTypes) {
2598
+ function validate(props, propName, componentName, location, propFullName) {
2599
+ var propValue = props[propName];
2600
+ var propType = getPropType(propValue);
2601
+ if (propType !== 'object') {
2602
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
2603
+ }
2604
+ // We need to check all keys in case some are required but missing from props.
2605
+ var allKeys = assign({}, props[propName], shapeTypes);
2606
+ for (var key in allKeys) {
2607
+ var checker = shapeTypes[key];
2608
+ if (has(shapeTypes, key) && typeof checker !== 'function') {
2609
+ return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
2610
+ }
2611
+ if (!checker) {
2612
+ return new PropTypeError(
2613
+ 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
2614
+ '\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
2615
+ '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
2616
+ );
2617
+ }
2618
+ var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
2619
+ if (error) {
2620
+ return error;
2621
+ }
2622
+ }
2623
+ return null;
2624
+ }
2625
+
2626
+ return createChainableTypeChecker(validate);
2627
+ }
2628
+
2629
+ function isNode(propValue) {
2630
+ switch (typeof propValue) {
2631
+ case 'number':
2632
+ case 'string':
2633
+ case 'undefined':
2634
+ return true;
2635
+ case 'boolean':
2636
+ return !propValue;
2637
+ case 'object':
2638
+ if (Array.isArray(propValue)) {
2639
+ return propValue.every(isNode);
2640
+ }
2641
+ if (propValue === null || isValidElement(propValue)) {
2642
+ return true;
2643
+ }
2644
+
2645
+ var iteratorFn = getIteratorFn(propValue);
2646
+ if (iteratorFn) {
2647
+ var iterator = iteratorFn.call(propValue);
2648
+ var step;
2649
+ if (iteratorFn !== propValue.entries) {
2650
+ while (!(step = iterator.next()).done) {
2651
+ if (!isNode(step.value)) {
2652
+ return false;
2653
+ }
2654
+ }
2655
+ } else {
2656
+ // Iterator will provide entry [k,v] tuples rather than values.
2657
+ while (!(step = iterator.next()).done) {
2658
+ var entry = step.value;
2659
+ if (entry) {
2660
+ if (!isNode(entry[1])) {
2661
+ return false;
2662
+ }
2663
+ }
2664
+ }
2665
+ }
2666
+ } else {
2667
+ return false;
2668
+ }
2669
+
2670
+ return true;
2671
+ default:
2672
+ return false;
2673
+ }
2674
+ }
2675
+
2676
+ function isSymbol(propType, propValue) {
2677
+ // Native Symbol.
2678
+ if (propType === 'symbol') {
2679
+ return true;
2680
+ }
2681
+
2682
+ // falsy value can't be a Symbol
2683
+ if (!propValue) {
2684
+ return false;
2685
+ }
2686
+
2687
+ // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
2688
+ if (propValue['@@toStringTag'] === 'Symbol') {
2689
+ return true;
2690
+ }
2691
+
2692
+ // Fallback for non-spec compliant Symbols which are polyfilled.
2693
+ if (typeof Symbol === 'function' && propValue instanceof Symbol) {
2694
+ return true;
2695
+ }
2696
+
2697
+ return false;
2698
+ }
2699
+
2700
+ // Equivalent of `typeof` but with special handling for array and regexp.
2701
+ function getPropType(propValue) {
2702
+ var propType = typeof propValue;
2703
+ if (Array.isArray(propValue)) {
2704
+ return 'array';
2705
+ }
2706
+ if (propValue instanceof RegExp) {
2707
+ // Old webkits (at least until Android 4.0) return 'function' rather than
2708
+ // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
2709
+ // passes PropTypes.object.
2710
+ return 'object';
2711
+ }
2712
+ if (isSymbol(propType, propValue)) {
2713
+ return 'symbol';
2714
+ }
2715
+ return propType;
2716
+ }
2717
+
2718
+ // This handles more types than `getPropType`. Only used for error messages.
2719
+ // See `createPrimitiveTypeChecker`.
2720
+ function getPreciseType(propValue) {
2721
+ if (typeof propValue === 'undefined' || propValue === null) {
2722
+ return '' + propValue;
2723
+ }
2724
+ var propType = getPropType(propValue);
2725
+ if (propType === 'object') {
2726
+ if (propValue instanceof Date) {
2727
+ return 'date';
2728
+ } else if (propValue instanceof RegExp) {
2729
+ return 'regexp';
2730
+ }
2731
+ }
2732
+ return propType;
2733
+ }
2734
+
2735
+ // Returns a string that is postfixed to a warning about an invalid type.
2736
+ // For example, "undefined" or "of type array"
2737
+ function getPostfixForTypeWarning(value) {
2738
+ var type = getPreciseType(value);
2739
+ switch (type) {
2740
+ case 'array':
2741
+ case 'object':
2742
+ return 'an ' + type;
2743
+ case 'boolean':
2744
+ case 'date':
2745
+ case 'regexp':
2746
+ return 'a ' + type;
2747
+ default:
2748
+ return type;
2749
+ }
2750
+ }
2751
+
2752
+ // Returns class name of the object, if any.
2753
+ function getClassName(propValue) {
2754
+ if (!propValue.constructor || !propValue.constructor.name) {
2755
+ return ANONYMOUS;
2756
+ }
2757
+ return propValue.constructor.name;
2758
+ }
2759
+
2760
+ ReactPropTypes.checkPropTypes = checkPropTypes;
2761
+ ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
2762
+ ReactPropTypes.PropTypes = ReactPropTypes;
2763
+
2764
+ return ReactPropTypes;
2765
+ };
2766
+ return factoryWithTypeCheckers;
2767
+ }
2768
+
2769
+ /**
2770
+ * Copyright (c) 2013-present, Facebook, Inc.
2771
+ *
2772
+ * This source code is licensed under the MIT license found in the
2773
+ * LICENSE file in the root directory of this source tree.
2774
+ */
2775
+
2776
+ var factoryWithThrowingShims;
2777
+ var hasRequiredFactoryWithThrowingShims;
2778
+
2779
+ function requireFactoryWithThrowingShims () {
2780
+ if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
2781
+ hasRequiredFactoryWithThrowingShims = 1;
2782
+
2783
+ var ReactPropTypesSecret = requireReactPropTypesSecret();
2784
+
2785
+ function emptyFunction() {}
2786
+ function emptyFunctionWithReset() {}
2787
+ emptyFunctionWithReset.resetWarningCache = emptyFunction;
2788
+
2789
+ factoryWithThrowingShims = function() {
2790
+ function shim(props, propName, componentName, location, propFullName, secret) {
2791
+ if (secret === ReactPropTypesSecret) {
2792
+ // It is still safe when called from React.
2793
+ return;
2794
+ }
2795
+ var err = new Error(
2796
+ 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
2797
+ 'Use PropTypes.checkPropTypes() to call them. ' +
2798
+ 'Read more at http://fb.me/use-check-prop-types'
2799
+ );
2800
+ err.name = 'Invariant Violation';
2801
+ throw err;
2802
+ } shim.isRequired = shim;
2803
+ function getShim() {
2804
+ return shim;
2805
+ } // Important!
2806
+ // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
2807
+ var ReactPropTypes = {
2808
+ array: shim,
2809
+ bigint: shim,
2810
+ bool: shim,
2811
+ func: shim,
2812
+ number: shim,
2813
+ object: shim,
2814
+ string: shim,
2815
+ symbol: shim,
2816
+
2817
+ any: shim,
2818
+ arrayOf: getShim,
2819
+ element: shim,
2820
+ elementType: shim,
2821
+ instanceOf: getShim,
2822
+ node: shim,
2823
+ objectOf: getShim,
2824
+ oneOf: getShim,
2825
+ oneOfType: getShim,
2826
+ shape: getShim,
2827
+ exact: getShim,
2828
+
2829
+ checkPropTypes: emptyFunctionWithReset,
2830
+ resetWarningCache: emptyFunction
2831
+ };
2832
+
2833
+ ReactPropTypes.PropTypes = ReactPropTypes;
2834
+
2835
+ return ReactPropTypes;
2836
+ };
2837
+ return factoryWithThrowingShims;
2838
+ }
2839
+
2840
+ /**
2841
+ * Copyright (c) 2013-present, Facebook, Inc.
2842
+ *
2843
+ * This source code is licensed under the MIT license found in the
2844
+ * LICENSE file in the root directory of this source tree.
2845
+ */
2846
+
2847
+ if (process.env.NODE_ENV !== 'production') {
2848
+ var ReactIs = requireReactIs();
2849
+
2850
+ // By explicitly using `prop-types` you are opting into new development behavior.
2851
+ // http://fb.me/prop-types-in-prod
2852
+ var throwOnDirectAccess = true;
2853
+ propTypes.exports = requireFactoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
2854
+ } else {
2855
+ // By explicitly using `prop-types` you are opting into new production behavior.
2856
+ // http://fb.me/prop-types-in-prod
2857
+ propTypes.exports = requireFactoryWithThrowingShims()();
2858
+ }
2859
+
2860
+ // Define the shape of the linter context object that is passed through the
2861
+ const linterContextProps = propTypes.exports.shape({
2862
+ contentType: propTypes.exports.string,
2863
+ highlightLint: propTypes.exports.bool,
2864
+ paths: propTypes.exports.arrayOf(propTypes.exports.string),
2865
+ stack: propTypes.exports.arrayOf(propTypes.exports.string)
2866
+ });
2867
+ const linterContextDefault = {
2868
+ contentType: "",
2869
+ highlightLint: false,
2870
+ paths: [],
2871
+ stack: []
2872
+ };
2873
+
2874
+ const allLintRules = AllRules.filter(r => r.severity < Rule.Severity.BULK_WARNING);
2875
+ // Run the Gorgon linter over the specified markdown parse tree,
2876
+ // with the specified context object, and
2877
+ // return a (possibly empty) array of lint warning objects. If the
2878
+ // highlight argument is true, this function also modifies the parse
2879
+ // tree to add "lint" nodes that can be visually rendered,
2880
+ // highlighting the problems for the user. The optional rules argument
2881
+ // is an array of Rule objects specifying which lint rules should be
2882
+ // applied to this parse tree. When omitted, a default set of rules is used.
2883
+ //
2884
+ // The context object may have additional properties that some lint
2885
+ // rules require:
2886
+ //
2887
+ // context.content is the source content string that was parsed to create
2888
+ // the parse tree.
2889
+ //
2890
+ // context.widgets is the widgets object associated
2891
+ // with the content string
2892
+ //
2893
+ // TODO: to make this even more general, allow the first argument to be
2894
+ // a string and run the parser over it in that case? (but ignore highlight
2895
+ // in that case). This would allow the one function to be used for both
2896
+ // online linting and batch linting.
2897
+ //
2898
+
2899
+ function runLinter(tree, context, highlight) {
2900
+ let rules = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : allLintRules;
2901
+ const warnings = [];
2902
+ const tt = new TreeTransformer(tree); // The markdown parser often outputs adjacent text nodes. We
2903
+ // coalesce them before linting for efficiency and accuracy.
2904
+
2905
+ tt.traverse((node, state, content) => {
2906
+ if (TreeTransformer.isTextNode(node)) {
2907
+ let next = state.nextSibling();
2908
+
2909
+ while (TreeTransformer.isTextNode(next)) {
2910
+ // $FlowFixMe[prop-missing]
2911
+ // $FlowFixMe[incompatible-use]
2912
+ node.content += next.content;
2913
+ state.removeNextSibling();
2914
+ next = state.nextSibling();
2915
+ }
2916
+ }
2917
+ }); // HTML tables are complicated, and the CSS we use in
2918
+ // ../components/lint.jsx to display lint does not work to
2919
+ // correctly position the lint indicators in the margin when the
2920
+ // lint is inside a table. So as a workaround we keep track of all
2921
+ // the lint that appears within a table and move it up to the
2922
+ // table element itself.
2923
+ //
2924
+ // It is not ideal to have to do this here,
2925
+ // but it is cleaner here than fixing up the lint during rendering
2926
+ // in perseus-markdown.jsx. If our lint display was simpler and
2927
+ // did not require indicators in the margin, this wouldn't be a
2928
+ // problem. Or, if we modified the lint display stuff so that
2929
+ // indicator positioning and tooltip display were both handled
2930
+ // with JavaScript (instead of pure CSS), then we could avoid this
2931
+ // issue too. But using JavaScript has its own downsides: there is
2932
+ // risk that the linter JavaScript would interfere with
2933
+ // widget-related Javascript.
2934
+
2935
+ let tableWarnings = [];
2936
+ let insideTable = false; // Traverse through the nodes of the parse tree. At each node, loop
2937
+ // through the array of lint rules and check whether there is a
2938
+ // lint violation at that node.
2939
+
2940
+ tt.traverse((node, state, content) => {
2941
+ const nodeWarnings = []; // If our rule is only designed to be tested against a particular
2942
+ // content type and we're not in that content type, we don't need to
2943
+ // consider that rule.
2944
+
2945
+ const applicableRules = rules.filter(r => r.applies(context)); // Generate a stack so we can identify our position in the tree in
2946
+ // lint rules
2947
+
2948
+ const stack = [...context.stack];
2949
+ stack.push(node.type);
2950
+ const nodeContext = { ...context,
2951
+ stack: stack.join(".")
2952
+ };
2953
+ applicableRules.forEach(rule => {
2954
+ const warning = rule.check(node, state, content, nodeContext);
2955
+
2956
+ if (warning) {
2957
+ // The start and end locations are relative to this
2958
+ // particular node, and so are not generally very useful.
2959
+ // TODO: When the markdown parser saves the node
2960
+ // locations in the source string then we can add
2961
+ // these numbers to that one and get and absolute
2962
+ // character range that will be useful
2963
+ if (warning.start || warning.end) {
2964
+ warning.target = content.substring(warning.start, warning.end);
2965
+ } // Add the warning to the list of all lint we've found
2966
+
2967
+
2968
+ warnings.push(warning); // If we're going to be highlighting lint, then we also
2969
+ // need to keep track of warnings specific to this node.
2970
+
2971
+ if (highlight) {
2972
+ nodeWarnings.push(warning);
2973
+ }
2974
+ }
2975
+ }); // If we're not highlighting lint in the tree, then we're done
2976
+ // traversing this node.
2977
+
2978
+ if (!highlight) {
2979
+ return;
2980
+ } // If the node we are currently at is a table, and there was lint
2981
+ // inside the table, then we want to add that lint here
2982
+
2983
+
2984
+ if (node.type === "table") {
2985
+ if (tableWarnings.length) {
2986
+ nodeWarnings.push(...tableWarnings);
2987
+ } // We're not in a table anymore, and don't have to remember
2988
+ // the warnings for the table
2989
+
2990
+
2991
+ insideTable = false;
2992
+ tableWarnings = [];
2993
+ } else if (!insideTable) {
2994
+ // Otherwise, if we are not already inside a table, check
2995
+ // to see if we've entered one. Because this is a post-order
2996
+ // traversal we'll see the table contents before the table itself.
2997
+ // Note that once we're inside the table, we don't have to
2998
+ // do this check each time... We can just wait until we ascend
2999
+ // up to the table, then we'll know we're out of it.
3000
+ insideTable = state.ancestors().some(n => n.type === "table");
3001
+ } // If we are inside a table and there were any warnings on
3002
+ // this node, then we need to save the warnings for display
3003
+ // on the table itself
3004
+
3005
+
3006
+ if (insideTable && nodeWarnings.length) {
3007
+ tableWarnings.push(...nodeWarnings);
3008
+ } // If there were any warnings on this node, and if we're highlighting
3009
+ // lint, then reparent the node so we can highlight it. Note that
3010
+ // a single node can have multiple warnings. If this happends we
3011
+ // concatenate the warnings and newline separate them. (The lint.jsx
3012
+ // component that displays the warnings may want to convert the
3013
+ // newlines into <br> tags.) We also provide a lint rule name
3014
+ // so that lint.jsx can link to a document that provides more details
3015
+ // on that particular lint rule. If there is more than one warning
3016
+ // we only link to the first rule, however.
3017
+ //
3018
+ // Note that even if we're inside a table, we still reparent the
3019
+ // linty node so that it can be highlighted. We just make a note
3020
+ // of whether this lint is inside a table or not.
3021
+
3022
+
3023
+ if (nodeWarnings.length) {
3024
+ nodeWarnings.sort((a, b) => {
3025
+ return a.severity - b.severity;
3026
+ });
3027
+
3028
+ if (node.type !== "text" || nodeWarnings.length > 1) {
3029
+ // If the linty node is not a text node, or if there is more
3030
+ // than one warning on a text node, then reparent the entire
3031
+ // node under a new lint node and put the warnings there.
3032
+ state.replace({
3033
+ type: "lint",
3034
+ content: node,
3035
+ message: nodeWarnings.map(w => w.message).join("\n\n"),
3036
+ ruleName: nodeWarnings[0].rule,
3037
+ blockHighlight: nodeContext.blockHighlight,
3038
+ insideTable: insideTable,
3039
+ severity: nodeWarnings[0].severity
3040
+ });
3041
+ } else {
3042
+ //
3043
+ // Otherwise, it is a single warning on a text node, and we
3044
+ // only want to highlight the actual linty part of that string
3045
+ // of text. So we want to replace the text node with (in the
3046
+ // general case) three nodes:
3047
+ //
3048
+ // 1) A new text node that holds the non-linty prefix
3049
+ //
3050
+ // 2) A lint node that is the parent of a new text node
3051
+ // that holds the linty part
3052
+ //
3053
+ // 3) A new text node that holds the non-linty suffix
3054
+ //
3055
+ // If the lint begins and/or ends at the boundaries of the
3056
+ // original text node, then nodes 1 and/or 3 won't exist, of
3057
+ // course.
3058
+ //
3059
+ // Note that we could generalize this to work with multple
3060
+ // warnings on a text node as long as the warnings are
3061
+ // non-overlapping. Hopefully, though, multiple warnings in a
3062
+ // single text node will be rare in practice. Also, we don't
3063
+ // have a good way to display multiple lint indicators on a
3064
+ // single line, so keeping them combined in that case might
3065
+ // be the best thing, anyway.
3066
+ //
3067
+ // $FlowFixMe[prop-missing]
3068
+ const content = node.content; // Text nodes have content
3069
+
3070
+ const warning = nodeWarnings[0]; // There is only one warning.
3071
+ // These are the lint boundaries within the content
3072
+
3073
+ const start = warning.start || 0;
3074
+ const end = warning.end || content.length;
3075
+ const prefix = content.substring(0, start);
3076
+ const lint = content.substring(start, end);
3077
+ const suffix = content.substring(end);
3078
+ const replacements = []; // What we'll replace the node with
3079
+ // The prefix text node, if there is one
3080
+
3081
+ if (prefix) {
3082
+ replacements.push({
3083
+ type: "text",
3084
+ content: prefix
3085
+ });
3086
+ } // The lint node wrapped around the linty text
3087
+
3088
+
3089
+ replacements.push({
3090
+ type: "lint",
3091
+ content: {
3092
+ type: "text",
3093
+ content: lint
3094
+ },
3095
+ message: warning.message,
3096
+ ruleName: warning.rule,
3097
+ insideTable: insideTable,
3098
+ severity: warning.severity
3099
+ }); // The suffix node, if there is one
3100
+
3101
+ if (suffix) {
3102
+ replacements.push({
3103
+ type: "text",
3104
+ content: suffix
3105
+ });
3106
+ } // Now replace the lint text node with the one to three
3107
+ // nodes in the replacement array
3108
+
3109
+
3110
+ state.replace(...replacements);
3111
+ }
3112
+ }
3113
+ });
3114
+ return warnings;
3115
+ }
3116
+ function pushContextStack(context, name) {
3117
+ const stack = context.stack || [];
3118
+ return { ...context,
3119
+ stack: stack.concat(name)
3120
+ };
3121
+ }
3122
+
3123
+ exports.Rule = Rule;
3124
+ exports.linterContextDefault = linterContextDefault;
3125
+ exports.linterContextProps = linterContextProps;
3126
+ exports.pushContextStack = pushContextStack;
3127
+ exports.rules = allLintRules;
3128
+ exports.runLinter = runLinter;
3129
+ //# sourceMappingURL=index.js.map