-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
2899 lines (2861 loc) · 112 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @author [email protected]
* See LICENSE file in root directory for full license.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function addDisableRule(disableRuleKeys, rule, key) {
let keys = disableRuleKeys.get(rule);
if (keys) {
keys.push(key);
}
else {
keys = [key];
disableRuleKeys.set(rule, keys);
}
}
function messageToKey(message) {
return `line:${message.line},column${message.column - 1}`;
}
function compareLocations(itemA, itemB) {
return itemA.line - itemB.line || itemA.column - itemB.column;
}
var swanParser = {
preprocess(code) {
return [code];
},
postprocess(messages) {
const state = {
block: {
disableAllKeys: new Set(),
disableRuleKeys: new Map(),
},
line: {
disableAllKeys: new Set(),
disableRuleKeys: new Map(),
},
};
const usedDisableDirectiveKeys = [];
const unusedDisableDirectiveReports = new Map();
const filteredMessages = messages[0].filter(message => {
var _a;
if ((_a = message === null || message === void 0 ? void 0 : message.ruleId) === null || _a === void 0 ? void 0 : _a.endsWith('swan/comment-directive')) {
const directiveType = message.messageId;
const data = message.message.split(' ');
switch (directiveType) {
case 'disableBlock':
state.block.disableAllKeys.add(data[1]);
break;
case 'disableLine':
state.line.disableAllKeys.add(data[1]);
break;
case 'enableBlock':
state.block.disableAllKeys.clear();
break;
case 'enableLine':
state.line.disableAllKeys.clear();
break;
case 'disableBlockRule':
addDisableRule(state.block.disableRuleKeys, data[1], data[2]);
break;
case 'disableLineRule':
addDisableRule(state.line.disableRuleKeys, data[1], data[2]);
break;
case 'enableBlockRule':
state.block.disableRuleKeys.delete(data[1]);
break;
case 'enableLineRule':
state.line.disableRuleKeys.delete(data[1]);
break;
case 'clear':
state.block.disableAllKeys.clear();
state.block.disableRuleKeys.clear();
state.line.disableAllKeys.clear();
state.line.disableRuleKeys.clear();
break;
default:
unusedDisableDirectiveReports.set(messageToKey(message), message);
break;
}
return false;
}
const disableDirectiveKeys = [];
if (state.block.disableAllKeys.size) {
disableDirectiveKeys.push(...state.block.disableAllKeys);
}
if (state.line.disableAllKeys.size) {
disableDirectiveKeys.push(...state.line.disableAllKeys);
}
if (message.ruleId) {
const block = state.block.disableRuleKeys.get(message.ruleId);
if (block) {
disableDirectiveKeys.push(...block);
}
const line = state.line.disableRuleKeys.get(message.ruleId);
if (line) {
disableDirectiveKeys.push(...line);
}
}
if (disableDirectiveKeys.length) {
usedDisableDirectiveKeys.push(...disableDirectiveKeys);
return false;
}
return true;
});
if (unusedDisableDirectiveReports.size) {
for (const key of usedDisableDirectiveKeys) {
unusedDisableDirectiveReports.delete(key);
}
filteredMessages.push(...unusedDisableDirectiveReports.values());
filteredMessages.sort(compareLocations);
}
return filteredMessages;
},
supportsAutofix: true,
};
const globals = {
App: true,
Page: true,
Component: true,
swan: true,
getApp: true,
getCurrentPages: true,
};
var base = {
overrides: [
{
files: ['*.swan'],
plugins: ['@swanide/eslint-plugin-swan'],
parser: require.resolve('@swanide/swan-eslint-parser'),
env: {
'browser': true,
'es6': true,
'@swanide/swan/globals': true,
},
rules: {
'indent': 0,
'no-multi-spaces': 0,
'import/unambiguous': 0,
'babel/new-cap': 0,
'@babel/new-cap': 0,
'import/no-commonjs': 0,
'max-len': 0,
'spaced-comment': 0,
'no-empty-character-class': 0,
'no-redeclare': 0,
'no-unused-vars': 0,
'no-var': 0,
'object-shorthand': 0,
'prefer-template': 0,
'prefer-destructuring': 0,
'prefer-spread': 0,
'prefer-arrow-callback': 0,
'prefer-const': 0,
'no-magic-numbers': 0,
'eol-last': 0,
'@swanide/swan/comment-directive': 2,
'@swanide/swan/no-parsing-error': 2,
'@swanide/swan/no-duplicate-attributes': 2,
'@swanide/swan/no-useless-mustache': 2,
'@swanide/swan/no-unary-operator': 2,
'@swanide/swan/valid-for': [2, { ignoreDuplicateForItem: true }],
'@swanide/swan/valid-if': 2,
'@swanide/swan/valid-elif': 2,
'@swanide/swan/valid-else': 2,
'@swanide/swan/no-confusing-for-if': 2,
'@swanide/swan/html-end-tag': 2,
'@swanide/swan/valid-bind': 2,
'@swanide/swan/template-name': 2,
'@swanide/swan/filter-name': 2,
},
},
],
globals,
};
var __rest$1 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
const _a$1 = base.overrides[0], { rules: baseRules } = _a$1, baseOverwritesSwan = __rest$1(_a$1, ["rules"]);
var recommended = Object.assign(Object.assign({}, base), { overrides: [
Object.assign(Object.assign({}, baseOverwritesSwan), { rules: Object.assign(Object.assign({}, baseRules), { 'max-len': [1, 200], '@swanide/swan/xml-indent': [
1,
4,
{ baseIndent: 1, scriptBaseIndent: 0, alignAttributesVertically: false },
], '@swanide/swan/no-multi-spaces': 1, '@swanide/swan/valid-component-nesting': [1, { allowEmptyBlock: true, ignoreEmptyBlock: ['view'] }], '@swanide/swan/arrow-spacing': 2, '@swanide/swan/dot-location': [2, 'property'], '@swanide/swan/array-bracket-spacing': 1, '@swanide/swan/dot-notation': 1, '@swanide/swan/key-spacing': 1, '@swanide/swan/keyword-spacing': 1, '@swanide/swan/no-useless-concat': 2 }) }),
] });
var __rest = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
const _a = recommended.overrides[0], { rules: recommendedRules } = _a, recommendedOverwritesSwan = __rest(_a, ["rules"]);
var strict = Object.assign(Object.assign({}, recommended), { overrides: [
Object.assign(Object.assign({}, recommendedOverwritesSwan), { rules: Object.assign(Object.assign({}, recommendedRules), { 'max-len': [2, 200], '@swanide/swan/xml-indent': [
2,
4,
{ baseIndent: 1, scriptBaseIndent: 0, alignAttributesVertically: false },
], '@swanide/swan/valid-for': [2, { ignoreDuplicateForItem: false }], '@swanide/swan/valid-component-nesting': [1, { allowEmptyBlock: false, ignoreEmptyBlock: ['view'] }], '@swanide/swan/no-multi-spaces': 1, '@swanide/swan/mustache-interpolation-spacing': [1, 'never'], '@swanide/swan/eqeqeq': 2, '@swanide/swan/func-call-spacing': 1 }) }),
] });
const emptyTextReg = /^\s*$/;
const isSwanFile = (filename) => filename.endsWith('.swan');
const getRuleUrl = (name) => `${process.env.SWAN_LINT_RULE_URL || 'https://smartprogram.baidu.com/docs/develop/lint'}/rules/${name}.md`;
let ruleMap = null;
function getCoreRule(name) {
let eslintModule = null;
if (process.env.ESLINT_MODULE_PATH) {
eslintModule = require(process.env.ESLINT_MODULE_PATH);
}
else {
eslintModule = require('eslint');
}
const map = ruleMap || (ruleMap = new (eslintModule.Linter)().getRules());
return map.get(name);
}
function wrapContextToOverrideTokenMethods(context, tokenStore) {
const eslintSourceCode = context.getSourceCode();
let tokensAndComments = null;
function getTokensAndComments() {
if (tokensAndComments) {
return tokensAndComments;
}
const { templateBody } = eslintSourceCode.ast;
tokensAndComments = templateBody
? tokenStore.getTokens(templateBody, {
includeComments: true,
})
: [];
return tokensAndComments;
}
const sourceCode = new Proxy((Object.assign({}, eslintSourceCode)), {
get(_object, key) {
if (key === 'tokensAndComments') {
return getTokensAndComments();
}
return key in tokenStore ? tokenStore[key] : eslintSourceCode[key];
},
});
return {
__proto__: context,
getSourceCode() {
return sourceCode;
},
};
}
function defineTemplateBodyVisitor(context, templateBodyVisitor, scriptVisitor) {
if (context.parserServices.defineTemplateBodyVisitor == null) {
if (isSwanFile(context.getFilename())) {
context.report({
loc: { line: 1, column: 0 },
message: 'Use the latest @swanide/swan-eslint-parser.',
});
}
return {};
}
return context.parserServices.defineTemplateBodyVisitor(templateBodyVisitor, scriptVisitor);
}
function getPrevNode(node) {
const { children } = node.parent;
if (!children || !children.length) {
return null;
}
let index = children.indexOf(node);
if (index <= 0) {
return null;
}
let prevNode = null;
while ((prevNode = children[--index])) {
if (prevNode.type !== 'XText'
|| prevNode.type === 'XText' && !emptyTextReg.test(prevNode.value)) {
break;
}
}
return prevNode;
}
function getAttribute(node, name) {
return (node.startTag.attributes.find(node => (node.type === 'XDirective' && node.key.name === name)) || null);
}
function hasAttribute(node, name) {
return Boolean(getAttribute(node, name));
}
function getDirective(node, name) {
return (node.startTag.attributes.find(node => (node.type === 'XDirective' && node.key.name === name)) || null);
}
function hasDirective(node, name) {
return Boolean(getDirective(node, name));
}
function isValidSingleMustacheOrExpression(values) {
var _a;
if ((values === null || values === void 0 ? void 0 : values.length) !== 1) {
return false;
}
const [value] = values;
if (value.type === 'XExpression' && value.expression != null) {
return true;
}
if (value.type === 'XMustache' && ((_a = value.value) === null || _a === void 0 ? void 0 : _a.expression) != null) {
return true;
}
return false;
}
function isValidSingleMustache(values) {
var _a;
if ((values === null || values === void 0 ? void 0 : values.length) !== 1) {
return false;
}
const [value] = values;
if (value.type === 'XMustache' && ((_a = value.value) === null || _a === void 0 ? void 0 : _a.expression) != null) {
return true;
}
return false;
}
function isIdentifierExpression(values) {
var _a;
if ((values === null || values === void 0 ? void 0 : values.length) !== 1) {
return false;
}
const [value] = values;
return value.type === 'XExpression' && ((_a = value.expression) === null || _a === void 0 ? void 0 : _a.type) === 'Identifier';
}
function getValueType(node) {
if (node.value == null || !node.value.length) {
return 'none';
}
if (node.value.every(v => v.type === 'XLiteral')) {
return 'literal';
}
if (node.value.every(v => v.type === 'XMustache')) {
return 'mustache';
}
if (node.value.every(v => v.type === 'XExpression')) {
return 'expression';
}
return 'mixed';
}
function wrapCoreRule(coreRuleName) {
const coreRule = getCoreRule(coreRuleName);
return {
create(context) {
const tokenStore = context.parserServices.getTemplateBodyTokenStore
&& context.parserServices.getTemplateBodyTokenStore();
if (tokenStore) {
context = wrapContextToOverrideTokenMethods(context, tokenStore);
}
const coreHandlers = coreRule.create(context);
const handlers = Object.assign({}, coreHandlers);
for (const [key, handler] of Object.entries(handlers)) {
let newKey = null;
if (key === 'Program' || key === 'Program:exit') {
newKey = key.replace(/\bProgram\b/g, 'XExpression');
}
else {
newKey = key.replace(/^|(?<=,)/g, 'XExpression ');
}
handlers[newKey] = handler;
delete handlers[key];
}
return context.parserServices.defineTemplateBodyVisitor(handlers);
},
meta: Object.assign(Object.assign({}, coreRule.meta), { docs: Object.assign(Object.assign({}, coreRule.meta.docs), { category: '', categories: ['essential'], url: getRuleUrl(coreRuleName), extensionRule: true, coreRuleUrl: coreRule.meta.docs.url }) }),
};
}
var arrayBracketSpacing = wrapCoreRule('array-bracket-spacing');
var arrowSpacing = wrapCoreRule('arrow-spacing');
const COMMENT_DIRECTIVE_B = /^\s*(eslint-(?:en|dis)able)(?:\s+|$)/;
const COMMENT_DIRECTIVE_L = /^\s*(eslint-disable(?:-next)?-line)(?:\s+|$)/;
function stripDirectiveComment(value) {
return value.split(/\s-{2,}\s/u)[0];
}
function parse(pattern, comment) {
const text = stripDirectiveComment(comment);
const match = pattern.exec(text);
if (match == null) {
return null;
}
const type = match[1];
const rules = [];
const rulesRe = /([^,\s]+)[,\s]*/g;
let startIndex = match[0].length;
rulesRe.lastIndex = startIndex;
let res = null;
while ((res = rulesRe.exec(text))) {
const ruleId = res[1].trim();
rules.push({
ruleId,
index: startIndex,
});
startIndex = rulesRe.lastIndex;
}
return { type, rules };
}
function enable(context, loc, group, rule) {
if (!rule) {
context.report({
loc,
messageId: group === 'block' ? 'enableBlock' : 'enableLine',
});
}
else {
context.report({
loc,
messageId: group === 'block' ? 'enableBlockRule' : 'enableLineRule',
data: { rule },
});
}
}
function disable(context, loc, group, rule, key) {
if (!rule) {
context.report({
loc,
messageId: group === 'block' ? 'disableBlock' : 'disableLine',
data: { key },
});
}
else {
context.report({
loc,
messageId: group === 'block' ? 'disableBlockRule' : 'disableLineRule',
data: { rule, key },
});
}
}
function locToKey(location) {
return `line:${location.line},column${location.column}`;
}
function reportUnused(context, comment, kind) {
const { loc } = comment;
context.report({
loc,
messageId: 'unused',
data: { kind },
});
return locToKey(loc.start);
}
function reportUnusedRules(context, comment, kind, rules) {
const sourceCode = context.getSourceCode();
const commentStart = comment.range[0] + 4;
return rules.map(rule => {
const start = sourceCode.getLocFromIndex(commentStart + rule.index);
const end = sourceCode.getLocFromIndex(commentStart + rule.index + rule.ruleId.length);
context.report({
loc: { start, end },
messageId: 'unusedRule',
data: { rule: rule.ruleId, kind },
});
return {
ruleId: rule.ruleId,
key: locToKey(start),
};
});
}
function processBlock(context, comment, reportUnusedDisableDirectives) {
const parsed = parse(COMMENT_DIRECTIVE_B, comment.value);
if (parsed != null) {
if (parsed.type === 'eslint-disable') {
if (parsed.rules.length) {
const rules = reportUnusedDisableDirectives
? reportUnusedRules(context, comment, parsed.type, parsed.rules)
: parsed.rules;
for (const rule of rules) {
disable(context, comment.loc.start, 'block', rule.ruleId, rule.key || '*');
}
}
else {
const key = reportUnusedDisableDirectives
? reportUnused(context, comment, parsed.type)
: '';
disable(context, comment.loc.start, 'block', null, key);
}
}
else if (parsed.rules.length) {
for (const rule of parsed.rules) {
enable(context, comment.loc.start, 'block', rule.ruleId);
}
}
else {
enable(context, comment.loc.start, 'block', null);
}
}
}
function processLine(context, comment, reportUnusedDisableDirectives) {
const parsed = parse(COMMENT_DIRECTIVE_L, comment.value);
if (parsed != null && comment.loc.start.line === comment.loc.end.line) {
const line = +comment.loc.start.line + (parsed.type === 'eslint-disable-line' ? 0 : 1);
const column = -1;
if (parsed.rules.length) {
const rules = reportUnusedDisableDirectives
? reportUnusedRules(context, comment, parsed.type, parsed.rules)
: parsed.rules;
for (const rule of rules) {
disable(context, { line, column }, 'line', rule.ruleId, rule.key || '');
enable(context, { line: line + 1, column }, 'line', rule.ruleId);
}
}
else {
const key = reportUnusedDisableDirectives
? reportUnused(context, comment, parsed.type)
: '';
disable(context, { line, column }, 'line', null, key);
enable(context, { line: line + 1, column }, 'line', null);
}
}
}
function extractTopLevelHTMLElements(documentFragment) {
return documentFragment.children.filter(node => node.type === 'XElement');
}
function extractTopLevelDocumentFragmentComments(documentFragment) {
const elements = extractTopLevelHTMLElements(documentFragment);
return documentFragment.comments.filter(comment => elements.every(element => comment.range[1] <= element.range[0]
|| element.range[1] <= comment.range[0]));
}
var commentDirective = {
meta: {
type: 'problem',
docs: {
description: 'support comment-directives',
categories: ['base'],
url: getRuleUrl('comment-directive'),
},
schema: [
{
type: 'object',
properties: {
reportUnusedDisableDirectives: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
messages: {
disableBlock: '--block {{key}}',
enableBlock: '++block',
disableLine: '--line {{key}}',
enableLine: '++line',
disableBlockRule: '-block {{rule}} {{key}}',
enableBlockRule: '+block {{rule}}',
disableLineRule: '-line {{rule}} {{key}}',
enableLineRule: '+line {{rule}}',
clear: 'clear',
unused: 'Unused {{kind}} directive (no problems were reported).',
unusedRule: 'Unused {{kind}} directive (no problems were reported from \'{{rule}}\').',
},
},
create(context) {
const options = context.options[0] || {};
const { reportUnusedDisableDirectives } = options;
const documentFragment = context.parserServices.getDocumentFragment
&& context.parserServices.getDocumentFragment();
return {
Program(node) {
if (node.templateBody) {
for (const comment of node.templateBody.comments) {
processBlock(context, comment, reportUnusedDisableDirectives);
processLine(context, comment, reportUnusedDisableDirectives);
}
context.report({
loc: node.templateBody.loc.end,
messageId: 'clear',
});
}
if (documentFragment) {
for (const comment of extractTopLevelDocumentFragmentComments(documentFragment)) {
processBlock(context, comment, reportUnusedDisableDirectives);
processLine(context, comment, reportUnusedDisableDirectives);
}
for (const element of extractTopLevelHTMLElements(documentFragment)) {
context.report({
loc: element.loc.end,
messageId: 'clear',
});
}
}
},
};
},
};
var dotLocation = wrapCoreRule('dot-location');
var dotNotation = wrapCoreRule('dot-notation');
var eqeqeq = wrapCoreRule('eqeqeq');
const filterNameReg = /^[a-zA-Z][a-zA-Z0-9_]*$/;
var filterName = {
meta: {
type: 'problem',
docs: {
description: 'validate filter/sjs name',
categories: ['essential'],
url: getRuleUrl('sjs-name'),
},
fixable: null,
schema: [],
},
create(context) {
return defineTemplateBodyVisitor(context, {
'XElement'(node) {
if (node.name !== 'filter' && node.name !== 'import-sjs') {
return;
}
const attr = node.startTag.attributes.find(a => a.key.name === 'module');
if (!attr) {
context.report({
node: node,
loc: node.loc,
message: `${node.name} 需要设置 module 模块名,并且符合 \'a-zA-Z0-9_\'`,
});
return;
}
if (attr.key.name === 'module'
&& (getValueType(attr) !== 'literal'
|| !filterNameReg.test(attr.value[0].value))) {
context.report({
node: attr,
loc: attr.loc,
message: `${node.name} module 模块名必须为字符串,并且符合 \'a-zA-Z0-9_\'`,
});
}
},
});
},
};
var funcCallSpacing = wrapCoreRule('func-call-spacing');
var htmlEndTag = {
meta: {
docs: {
description: 'enforce end tag style',
categories: ['essential'],
url: getRuleUrl('html-end-tag'),
},
fixable: 'code',
messages: {
unexpected: '没有结束标签',
},
schema: [],
},
create(context) {
return defineTemplateBodyVisitor(context, {
'XElement'(node) {
const { name } = node;
const isSelfClosing = node.startTag.selfClosing;
const hasEndTag = node.endTag != null;
if (!hasEndTag && !isSelfClosing) {
context.report({
node: node.startTag,
loc: node.startTag.loc,
message: '\'<{{name}}>\' 没有结束标签',
data: { name },
});
}
},
});
},
};
var keySpacing = wrapCoreRule('key-spacing');
var keywordSpacing = wrapCoreRule('keyword-spacing');
var mustacheInterpolationSpacing = {
meta: {
type: 'layout',
docs: {
description: 'enforce unified spacing in mustache interpolations',
categories: ['essential'],
url: getRuleUrl('mustache-interpolation-spacing'),
},
fixable: 'whitespace',
schema: [
{
enum: ['always', 'never'],
},
],
},
create(context) {
const options = context.options[0] || 'always';
const tokenStore = context.parserServices.getTemplateBodyTokenStore
&& context.parserServices.getTemplateBodyTokenStore();
return defineTemplateBodyVisitor(context, {
'XMustache[value!=null]'(node) {
const openBrace = tokenStore.getFirstToken(node);
const closeBrace = tokenStore.getLastToken(node);
if (!openBrace
|| !closeBrace
|| openBrace.type !== 'XMustacheStart'
|| closeBrace.type !== 'XMustacheEnd'
|| openBrace.value === '{') {
return;
}
const firstToken = tokenStore.getTokenAfter(openBrace, {
includeComments: true,
});
const lastToken = tokenStore.getTokenBefore(closeBrace, {
includeComments: true,
});
if (options === 'always') {
if (openBrace.range[1] === firstToken.range[0]) {
context.report({
node: openBrace,
message: '\'{{\' 后面需要一个空格',
fix: fixer => fixer.insertTextAfter(openBrace, ' '),
});
}
if (closeBrace.range[0] === lastToken.range[1]) {
context.report({
node: closeBrace,
message: '\'}}\' 前面需要一个空格',
fix: fixer => fixer.insertTextBefore(closeBrace, ' '),
});
}
}
else {
if (openBrace.range[1] !== firstToken.range[0]) {
context.report({
loc: {
start: openBrace.loc.start,
end: firstToken.loc.start,
},
message: '\'{{\' 后面不允许空格',
fix: fixer => fixer.removeRange([openBrace.range[1], firstToken.range[0]]),
});
}
if (closeBrace.range[0] !== lastToken.range[1]) {
context.report({
loc: {
start: lastToken.loc.end,
end: closeBrace.loc.end,
},
message: '\'}}\' 前面不允许空格',
fix: fixer => fixer.removeRange([lastToken.range[1], closeBrace.range[0]]),
});
}
}
},
});
},
};
function getRefs(node) {
return node
? node.value
.filter(i => { var _a; return i.type === 'XMustache' && ((_a = i.value) === null || _a === void 0 ? void 0 : _a.references) || i.type === 'XExpression' && i.references; })
.reduce((references, node) => references.concat(node.type === 'XMustache'
? node.value.references
: node.references), [])
: [];
}
function getLiteralRefs(node) {
return node
? node.value
.filter(i => i.type === 'XLiteral')
.reduce((references, node) => references.concat(node.value), [])
: [];
}
var noConfusingForIf = {
meta: {
type: 'problem',
docs: {
description: 'disallow confusing `for` and `if` directive on the same element',
categories: ['essential'],
url: getRuleUrl('no-confusing-for-if'),
},
fixable: null,
schema: [],
},
create(context) {
return defineTemplateBodyVisitor(context, {
'XDirective[key.name=\'if\']'(node) {
const element = node.parent.parent;
const prefix = node.key.prefix;
if (hasDirective(element, 'for')) {
const forItemNode = getDirective(element, 'for-item');
const ifRefs = getRefs(node);
const forRefs = forItemNode
? getLiteralRefs(forItemNode)
: ['item'];
const isRefMatches = ifRefs.some(ref => forRefs.some(variable => variable === ref.id.name));
if (isRefMatches) {
context.report({
node,
loc: node.loc,
message: `'${prefix}if' 不允许和 '${prefix}for' 在一个标签中定义`,
});
}
}
},
});
},
};
var noDuplicateAttributes = {
meta: {
type: 'problem',
docs: {
description: 'disallow duplication of attributes',
categories: ['essential'],
url: getRuleUrl('no-duplicate-attributes'),
},
fixable: null,
schema: [],
},
create(context) {
const directiveNames = new Set();
return defineTemplateBodyVisitor(context, {
XStartTag() {
directiveNames.clear();
},
XDirective(node) {
if (node.key.name == null) {
return;
}
const name = `${node.key.prefix}${node.key.name}`;
if (directiveNames.has(name)) {
context.report({
node,
loc: node.loc,
message: '\'{{name}}\' 属性名重复',
data: { name },
});
}
directiveNames.add(name);
},
});
},
};
const isProperty = (context, node) => {
const sourceCode = context.getSourceCode();
return node.type === 'Punctuator' && sourceCode.getText(node) === ':';
};
var noMultiSpaces = {
meta: {
type: 'layout',
docs: {
description: 'disallow multiple spaces',
categories: ['essential'],
url: getRuleUrl('no-multi-spaces'),
},
fixable: 'whitespace',
schema: [
{
type: 'object',
properties: {
ignoreProperties: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
},
create(context) {
const options = context.options[0] || {};
const ignoreProperties = options.ignoreProperties === true;
const sourceCode = context.getSourceCode();
const tokenStore = context.parserServices.getTemplateBodyTokenStore();
if (!sourceCode.ast || !sourceCode.ast.templateBody) {
return {};
}
const tokens = tokenStore.getTokens(sourceCode.ast.templateBody, {
includeComments: true,
}) || [];
let prevToken = tokens.shift();
for (const token of tokens) {
const spaces = token.range[0] - prevToken.range[1];
const shouldIgnore = ignoreProperties
&& (isProperty(context, token) || isProperty(context, prevToken));
if (spaces > 1
&& token.loc.start.line === prevToken.loc.start.line
&& !shouldIgnore) {
context.report({
node: token,
loc: {
start: prevToken.loc.end,
end: token.loc.start,
},
message: `${sourceCode.getText(token)} 前有多个空格,只允许 1 个空格`,
fix: fixer => fixer.replaceTextRange([prevToken.range[1], token.range[0]], ' '),
});
}
prevToken = token;
}
return {};
},
};
const parserErrorCode = {
'abrupt-closing-of-empty-comment': true,
'control-character-in-input-stream': true,
'eof-before-tag-name': true,
'eof-in-comment': true,
'eof-in-tag': true,
'incorrectly-closed-comment': true,
'incorrectly-opened-comment': true,
'invalid-first-character-of-tag-name': true,
'missing-attribute-value': true,
'missing-end-tag-name': true,
'missing-whitespace-between-attributes': true,
'nested-comment': true,
'noncharacter-in-input-stream': true,
'surrogate-in-input-stream': true,
'unexpected-character-in-attribute-name': true,
'unexpected-character-in-unquoted-attribute-value': true,
'unexpected-equals-sign-before-attribute-name': true,
'unexpected-null-character': true,
'unexpected-question-mark-instead-of-tag-name': true,
'unexpected-solidus-in-tag': true,
'end-tag-with-attributes': true,
'duplicate-attribute': true,
'non-void-html-element-start-tag-with-trailing-solidus': true,
'attribute-value-invalid-unquoted': true,
'unexpected-line-break': true,
'missing-expression-end-tag': true,
'missing-end-tag': true,
'x-invalid-end-tag': true,
'x-invalid-directive': true,
'x-expression-error': true,
};
const DEFAULT_OPTIONS = Object.freeze(Object.assign({}, parserErrorCode));
const messageZH = {
'abrupt-closing-of-empty-comment': '注释闭合错误',
'control-character-in-input-stream': '页面不允许控制字符',
'eof-before-tag-name': '标签未正常结束',
'eof-in-comment': '注释未正常结束',
'eof-in-tag': '标签未正常结束',
'incorrectly-closed-comment': '注释闭合错误',
'incorrectly-opened-comment': '注释闭合错误',
'invalid-first-character-of-tag-name': '标签首字符不合法',
'missing-attribute-value': '未正确设置属性值',
'missing-end-tag-name': '缺少结束标签',
'missing-whitespace-between-attributes': '属性之间没有空格',
'nested-comment': '不允许注释嵌套',
'noncharacter-in-input-stream': '页面中不允许空字符',
'surrogate-in-input-stream': '页面中不允许使用私有字符 0xD800 ~ 0xDFFF',
'unexpected-character-in-attribute-name': '属性名称不合法',
'unexpected-character-in-unquoted-attribute-value': '属性值包含非法字符',
'unexpected-equals-sign-before-attribute-name': '非法的 \'=\' 字符',
'unexpected-null-character': '非法的空字符',
'unexpected-question-mark-instead-of-tag-name': '属性名中包含非法的 \'?\' 字符',
'unexpected-solidus-in-tag': '非法的 \'/\' 字符',
'end-tag-with-attributes': '结束标签不应该包含属性',
'duplicate-attribute': '重复的属性定义',
'non-void-html-element-start-tag-with-trailing-solidus': '非自闭合标签',
'attribute-value-invalid-unquoted': '属性值需要使用 \'\'\' 或 \'"\'包裹',
'unexpected-line-break': '非预期的换行',
'missing-expression-end-tag': '缺少 mustache 结束标签',
'missing-end-tag': '缺少结束标签',
'x-invalid-end-tag': '标签错误',
'x-invalid-directive': '错误的指令名称',
'x-expression-error': '错误的表达式',
};
var noParsingError = {
meta: {
type: 'problem',
docs: {
description: 'disallow parsing errors',
categories: ['base'],
url: getRuleUrl('no-parsing-error'),
},
fixable: null,
schema: [
{
type: 'object',
properties: Object.keys(DEFAULT_OPTIONS).reduce((ret, code) => {
ret[code] = { type: 'boolean' };
return ret;
}, ({})),
additionalProperties: false,
},
],
},
create(context) {
const options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), context.options[0] || {});
return {
Program(program) {