-
-
Notifications
You must be signed in to change notification settings - Fork 675
/
Copy pathindex.js
3431 lines (3237 loc) · 100 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 Toru Nagashima <https://github.com/mysticatea>
* @copyright 2017 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
'use strict'
const { getScope } = require('./scope')
/**
* @typedef {import('eslint').Rule.RuleModule} RuleModule
* @typedef {import('estree').Position} Position
* @typedef {import('eslint').Rule.CodePath} CodePath
* @typedef {import('eslint').Rule.CodePathSegment} CodePathSegment
*/
/**
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayProp} ComponentArrayProp
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectProp} ComponentObjectProp
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeProp} ComponentTypeProp
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeProp} ComponentInferTypeProp
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownProp} ComponentUnknownProp
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentProp} ComponentProp
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayEmit} ComponentArrayEmit
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectEmit} ComponentObjectEmit
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeEmit} ComponentTypeEmit
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeEmit} ComponentInferTypeEmit
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownEmit} ComponentUnknownEmit
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentEmit} ComponentEmit
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentModelName} ComponentModelName
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentModel} ComponentModel
*/
/**
* @typedef { {key: string | null, value: BlockStatement | null} } ComponentComputedProperty
*/
/**
* @typedef { 'props' | 'asyncData' | 'data' | 'computed' | 'setup' | 'watch' | 'methods' | 'provide' | 'inject' | 'expose' } GroupName
* @typedef { { type: 'array', name: string, groupName: GroupName, node: Literal | TemplateLiteral } } ComponentArrayPropertyData
* @typedef { { type: 'object', name: string, groupName: GroupName, node: Identifier | Literal | TemplateLiteral, property: Property } } ComponentObjectPropertyData
* @typedef { ComponentArrayPropertyData | ComponentObjectPropertyData } ComponentPropertyData
*/
/**
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectType} VueObjectType
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectData} VueObjectData
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueVisitor} VueVisitor
* @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ScriptSetupVisitor} ScriptSetupVisitor
*/
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
const HTML_ELEMENT_NAMES = new Set(require('./html-elements.json'))
const SVG_ELEMENT_NAMES = new Set(require('./svg-elements.json'))
const VOID_ELEMENT_NAMES = new Set(require('./void-elements.json'))
const VUE2_BUILTIN_COMPONENT_NAMES = new Set(
require('./vue2-builtin-components')
)
const VUE3_BUILTIN_COMPONENT_NAMES = new Set(
require('./vue3-builtin-components')
)
const VUE_BUILTIN_ELEMENT_NAMES = new Set(require('./vue-builtin-elements'))
const path = require('path')
const vueEslintParser = require('vue-eslint-parser')
const { traverseNodes, getFallbackKeys, NS } = vueEslintParser.AST
const { findVariable } = require('@eslint-community/eslint-utils')
const {
getComponentPropsFromTypeDefine,
getComponentEmitsFromTypeDefine,
isTypeNode
} = require('./ts-utils')
/**
* @type { WeakMap<RuleContext, Token[]> }
*/
const componentComments = new WeakMap()
/** @type { Map<string, RuleModule> | null } */
let coreRuleMap = null
/** @type { Map<string, RuleModule> } */
const stylisticRuleMap = new Map()
/**
* Get the core rule implementation from the rule name
* @param {string} name
* @returns {RuleModule | null}
*/
function getCoreRule(name) {
const eslint = require('eslint')
try {
const map = coreRuleMap || (coreRuleMap = new eslint.Linter().getRules())
return map.get(name) || null
} catch {
// getRules() is no longer available in flat config.
}
const { builtinRules } = require('eslint/use-at-your-own-risk')
return /** @type {any} */ (builtinRules.get(name) || null)
}
/**
* Get ESLint Stylistic rule implementation from the rule name
* @param {string} name
* @param {'@stylistic/eslint-plugin' | '@stylistic/eslint-plugin-ts' | '@stylistic/eslint-plugin-js'} [preferModule]
* @returns {RuleModule | null}
*/
function getStylisticRule(name, preferModule) {
if (!preferModule) {
const cached = stylisticRuleMap.get(name)
if (cached) {
return cached
}
}
const stylisticPluginNames = [
'@stylistic/eslint-plugin',
'@stylistic/eslint-plugin-ts',
'@stylistic/eslint-plugin-js'
]
if (preferModule) {
stylisticPluginNames.unshift(preferModule)
}
for (const stylisticPluginName of stylisticPluginNames) {
try {
const plugin = createRequire(`${process.cwd()}/__placeholder__.js`)(
stylisticPluginName
)
const rule = plugin?.rules?.[name]
if (!preferModule) stylisticRuleMap.set(name, rule)
return rule
} catch {
// ignore
}
}
return null
}
/**
* @template {object} T
* @param {T} target
* @param {Partial<T>[]} propsArray
* @returns {T}
*/
function newProxy(target, ...propsArray) {
const result = new Proxy(
{},
{
get(_object, key) {
for (const props of propsArray) {
if (key in props) {
// @ts-expect-error
return props[key]
}
}
// @ts-expect-error
return target[key]
},
has(_object, key) {
return key in target
},
ownKeys(_object) {
return Reflect.ownKeys(target)
},
getPrototypeOf(_object) {
return Reflect.getPrototypeOf(target)
}
}
)
return /** @type {T} */ (result)
}
/**
* Wrap the rule context object to override methods which access to tokens (such as getTokenAfter).
* @param {RuleContext} context The rule context object.
* @param {ParserServices.TokenStore} tokenStore The token store object for template.
* @param {Object} options The option of this rule.
* @param {boolean} [options.applyDocument] If `true`, apply check to document fragment.
* @returns {RuleContext}
*/
function wrapContextToOverrideTokenMethods(context, tokenStore, options) {
const eslintSourceCode = context.getSourceCode()
const rootNode = options.applyDocument
? eslintSourceCode.parserServices.getDocumentFragment &&
eslintSourceCode.parserServices.getDocumentFragment()
: eslintSourceCode.ast.templateBody
/** @type {Token[] | null} */
let tokensAndComments = null
function getTokensAndComments() {
if (tokensAndComments) {
return tokensAndComments
}
tokensAndComments = rootNode
? tokenStore.getTokens(rootNode, {
includeComments: true
})
: []
return tokensAndComments
}
/** @param {number} index */
function getNodeByRangeIndex(index) {
if (!rootNode) {
return eslintSourceCode.ast
}
/** @type {ASTNode} */
let result = eslintSourceCode.ast
/** @type {ASTNode[]} */
const skipNodes = []
let breakFlag = false
traverseNodes(rootNode, {
enterNode(node, parent) {
if (breakFlag) {
return
}
if (skipNodes[0] === parent) {
skipNodes.unshift(node)
return
}
if (node.range[0] <= index && index < node.range[1]) {
result = node
} else {
skipNodes.unshift(node)
}
},
leaveNode(node) {
if (breakFlag) {
return
}
if (result === node) {
breakFlag = true
} else if (skipNodes[0] === node) {
skipNodes.shift()
}
}
})
return result
}
const sourceCode = newProxy(
eslintSourceCode,
{
get tokensAndComments() {
return getTokensAndComments()
},
getNodeByRangeIndex,
// @ts-expect-error -- Added in ESLint v8.38.0
getDeclaredVariables
},
tokenStore
)
/** @type {WeakMap<ASTNode, import('eslint').Scope.ScopeManager>} */
const containerScopes = new WeakMap()
/**
* @param {ASTNode} node
* @returns {import('eslint').Scope.ScopeManager|null}
*/
function getContainerScope(node) {
const exprContainer = getVExpressionContainer(node)
if (!exprContainer) {
return null
}
const cache = containerScopes.get(exprContainer)
if (cache) {
return cache
}
const programNode = eslintSourceCode.ast
const parserOptions =
context.languageOptions?.parserOptions ?? context.parserOptions ?? {}
const ecmaFeatures = parserOptions.ecmaFeatures || {}
const ecmaVersion =
context.languageOptions?.ecmaVersion ?? parserOptions.ecmaVersion ?? 2020
const sourceType = programNode.sourceType
try {
const eslintScope = createRequire(require.resolve('eslint'))(
'eslint-scope'
)
const expStmt = newProxy(exprContainer, {
// @ts-expect-error
type: 'ExpressionStatement'
})
const scopeProgram = newProxy(programNode, {
// @ts-expect-error
body: [expStmt]
})
const scope = eslintScope.analyze(scopeProgram, {
ignoreEval: true,
nodejsScope: false,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion,
sourceType,
fallback: getFallbackKeys
})
containerScopes.set(exprContainer, scope)
return scope
} catch (error) {
// ignore
// console.log(error)
}
return null
}
return newProxy(context, {
getSourceCode() {
return sourceCode
},
get sourceCode() {
return sourceCode
},
getDeclaredVariables
})
/**
* @param {ESNode} node
* @returns {Variable[]}
*/
function getDeclaredVariables(node) {
const scope = getContainerScope(node)
return (
scope?.getDeclaredVariables?.(node) ??
context.getDeclaredVariables?.(node) ??
[]
)
}
}
/**
* Wrap the rule context object to override report method to skip the dynamic argument.
* @param {RuleContext} context The rule context object.
* @returns {RuleContext}
*/
function wrapContextToOverrideReportMethodToSkipDynamicArgument(context) {
const sourceCode = context.getSourceCode()
const templateBody = sourceCode.ast.templateBody
if (!templateBody) {
return context
}
/** @type {Range[]} */
const directiveKeyRanges = []
traverseNodes(templateBody, {
enterNode(node, parent) {
if (
parent &&
parent.type === 'VDirectiveKey' &&
node.type === 'VExpressionContainer'
) {
directiveKeyRanges.push(node.range)
}
},
leaveNode() {}
})
return newProxy(context, {
report(descriptor, ...args) {
let range = null
if (descriptor.loc) {
const startLoc = descriptor.loc.start || descriptor.loc
const endLoc = descriptor.loc.end || startLoc
range = [
sourceCode.getIndexFromLoc(startLoc),
sourceCode.getIndexFromLoc(endLoc)
]
} else if (descriptor.node) {
range = descriptor.node.range
}
if (range) {
for (const directiveKeyRange of directiveKeyRanges) {
if (
range[0] < directiveKeyRange[1] &&
directiveKeyRange[0] < range[1]
) {
return
}
}
}
context.report(descriptor, ...args)
}
})
}
/**
* @callback WrapRuleCreate
* @param {RuleContext} ruleContext
* @param {WrapRuleCreateContext} wrapContext
* @returns {TemplateListener}
*
* @typedef {object} WrapRuleCreateContext
* @property {RuleListener} baseHandlers
*/
/**
* @callback WrapRulePreprocess
* @param {RuleContext} ruleContext
* @param {WrapRulePreprocessContext} wrapContext
* @returns {void}
*
* @typedef {object} WrapRulePreprocessContext
* @property { (override: Partial<RuleContext>) => RuleContext } wrapContextToOverrideProperties Wrap the rule context object to override
* @property { (visitor: TemplateListener) => void } defineVisitor Define template body visitor
*/
/**
* @typedef {object} WrapRuleOptions
* @property {string[]} [categories] The categories of this rule.
* @property {boolean} [skipDynamicArguments] If `true`, skip validation within dynamic arguments.
* @property {boolean} [skipDynamicArgumentsReport] If `true`, skip report within dynamic arguments.
* @property {boolean} [applyDocument] If `true`, apply check to document fragment.
* @property {boolean} [skipBaseHandlers] If `true`, skip base rule handlers.
* @property {WrapRulePreprocess} [preprocess] Preprocess to calling create of base rule.
* @property {WrapRuleCreate} [create] If define, extend base rule.
*/
/**
* Wrap a given core rule to apply it to Vue.js template.
* @param {string} coreRuleName The name of the core rule implementation to wrap.
* @param {WrapRuleOptions} [options] The option of this rule.
* @returns {RuleModule} The wrapped rule implementation.
*/
function wrapCoreRule(coreRuleName, options) {
const coreRule = getCoreRule(coreRuleName)
if (!coreRule) {
return {
meta: {
type: 'problem',
docs: {
url: `https://eslint.vuejs.org/rules/${coreRuleName}.html`
}
},
create(context) {
return defineTemplateBodyVisitor(context, {
"VElement[name='template'][parent.type='VDocumentFragment']"(node) {
context.report({
node,
message: `Failed to extend ESLint core rule "${coreRuleName}". You may be able to use this rule by upgrading the version of ESLint. If you cannot upgrade it, turn off this rule.`
})
}
})
}
}
}
const rule = wrapRuleModule(coreRule, coreRuleName, options)
const meta = {
...rule.meta,
docs: {
...rule.meta.docs,
extensionSource: {
url: coreRule.meta.docs.url,
name: 'ESLint core'
}
}
}
return {
...rule,
meta
}
}
/**
* @typedef {object} RuleNames
* @property {string} core The name of the core rule implementation to wrap.
* @property {string} stylistic The name of ESLint Stylistic rule implementation to wrap.
* @property {string} vue The name of the wrapped rule
*/
/**
* Wrap a core rule or ESLint Stylistic rule to apply it to Vue.js template.
* @param {RuleNames|string} ruleNames The names of the rule implementation to wrap.
* @param {WrapRuleOptions} [options] The option of this rule.
* @returns {RuleModule} The wrapped rule implementation.
*/
function wrapStylisticOrCoreRule(ruleNames, options) {
const stylisticRuleName =
typeof ruleNames === 'string' ? ruleNames : ruleNames.stylistic
const coreRuleName =
typeof ruleNames === 'string' ? ruleNames : ruleNames.core
const vueRuleName = typeof ruleNames === 'string' ? ruleNames : ruleNames.vue
const stylisticRule = getStylisticRule(stylisticRuleName)
const baseRule = stylisticRule || getCoreRule(coreRuleName)
if (!baseRule) {
return {
meta: {
type: 'problem',
docs: {
url: `https://eslint.vuejs.org/rules/${vueRuleName}.html`
}
},
create(context) {
return defineTemplateBodyVisitor(context, {
"VElement[name='template'][parent.type='VDocumentFragment']"(node) {
context.report({
node,
message: `Failed to extend ESLint Stylistic rule "${stylisticRule}". You may be able to use this rule by installing ESLint Stylistic plugin (https://eslint.style/). If you cannot install it, turn off this rule.`
})
}
})
}
}
}
const rule = wrapRuleModule(baseRule, vueRuleName, options)
const jsRule = getStylisticRule(
stylisticRuleName,
'@stylistic/eslint-plugin-js'
)
const description = stylisticRule
? `${jsRule?.meta.docs.description} in \`<template>\``
: rule.meta.docs.description
const meta = {
...rule.meta,
docs: {
...rule.meta.docs,
description,
extensionSource: {
url: baseRule.meta.docs.url,
name: stylisticRule ? 'ESLint Stylistic' : 'ESLint core'
}
},
deprecated: undefined,
replacedBy: undefined
}
return {
...rule,
meta
}
}
/**
* Wrap a given rule to apply it to Vue.js template.
* @param {RuleModule} baseRule The rule implementation to wrap.
* @param {string} ruleName The name of the wrapped rule.
* @param {WrapRuleOptions} [options] The option of this rule.
* @returns {RuleModule} The wrapped rule implementation.
*/
function wrapRuleModule(baseRule, ruleName, options) {
let description = baseRule.meta.docs.description
if (description) {
description += ' in `<template>`'
}
const {
categories,
skipDynamicArguments,
skipDynamicArgumentsReport,
skipBaseHandlers,
applyDocument,
preprocess,
create
} = options || {}
return {
create(context) {
const sourceCode = context.getSourceCode()
const tokenStore =
sourceCode.parserServices.getTemplateBodyTokenStore &&
sourceCode.parserServices.getTemplateBodyTokenStore()
// The `context.getSourceCode()` cannot access the tokens of templates.
// So override the methods which access to tokens by the `tokenStore`.
if (tokenStore) {
context = wrapContextToOverrideTokenMethods(context, tokenStore, {
applyDocument
})
}
if (skipDynamicArgumentsReport) {
context =
wrapContextToOverrideReportMethodToSkipDynamicArgument(context)
}
/** @type {TemplateListener} */
const handlers = {}
if (preprocess) {
preprocess(context, {
wrapContextToOverrideProperties(override) {
context = newProxy(context, override)
return context
},
defineVisitor(visitor) {
compositingVisitors(handlers, visitor)
}
})
}
const baseHandlers = baseRule.create(context)
if (!skipBaseHandlers) {
compositingVisitors(handlers, baseHandlers)
}
// Move `Program` handlers to `VElement[parent.type!='VElement']`
if (handlers.Program) {
handlers[
applyDocument
? 'VDocumentFragment'
: "VElement[parent.type!='VElement']"
] = /** @type {any} */ (handlers.Program)
delete handlers.Program
}
if (handlers['Program:exit']) {
handlers[
applyDocument
? 'VDocumentFragment:exit'
: "VElement[parent.type!='VElement']:exit"
] = /** @type {any} */ (handlers['Program:exit'])
delete handlers['Program:exit']
}
if (skipDynamicArguments) {
let withinDynamicArguments = false
for (const name of Object.keys(handlers)) {
const original = handlers[name]
/** @param {any[]} args */
handlers[name] = (...args) => {
if (withinDynamicArguments) return
// @ts-expect-error
original(...args)
}
}
handlers['VDirectiveKey > VExpressionContainer'] = () => {
withinDynamicArguments = true
}
handlers['VDirectiveKey > VExpressionContainer:exit'] = () => {
withinDynamicArguments = false
}
}
if (create) {
compositingVisitors(handlers, create(context, { baseHandlers }))
}
if (applyDocument) {
// Apply the handlers to document.
return defineDocumentVisitor(context, handlers)
}
// Apply the handlers to templates.
return defineTemplateBodyVisitor(context, handlers)
},
meta: Object.assign({}, baseRule.meta, {
docs: Object.assign({}, baseRule.meta.docs, {
description,
category: null,
categories,
url: `https://eslint.vuejs.org/rules/${ruleName}.html`
})
})
}
}
// ------------------------------------------------------------------------------
// Exports
// ------------------------------------------------------------------------------
module.exports = {
/**
* Register the given visitor to parser services.
* If the parser service of `vue-eslint-parser` was not found,
* this generates a warning.
*
* @param {RuleContext} context The rule context to use parser services.
* @param {TemplateListener} templateBodyVisitor The visitor to traverse the template body.
* @param {RuleListener} [scriptVisitor] The visitor to traverse the script.
* @param { { templateBodyTriggerSelector: "Program" | "Program:exit" } } [options] The options.
* @returns {RuleListener} The merged visitor.
*/
defineTemplateBodyVisitor,
/**
* Register the given visitor to parser services.
* If the parser service of `vue-eslint-parser` was not found,
* this generates a warning.
*
* @param {RuleContext} context The rule context to use parser services.
* @param {TemplateListener} documentVisitor The visitor to traverse the document.
* @param { { triggerSelector: "Program" | "Program:exit" } } [options] The options.
* @returns {RuleListener} The merged visitor.
*/
defineDocumentVisitor,
/**
* Wrap a given core rule to apply it to Vue.js template.
* @type {typeof wrapCoreRule}
*/
wrapCoreRule,
wrapStylisticOrCoreRule,
getCoreRule,
/**
* Checks whether the given value is defined.
* @template T
* @param {T | null | undefined} v
* @returns {v is T}
*/
isDef,
/**
* Flattens arrays, objects and iterable objects.
* @template T
* @param {T | Iterable<T> | null | undefined} v
* @returns {T[]}
*/
flatten,
/**
* Get the previous sibling element of the given element.
* @param {VElement} node The element node to get the previous sibling element.
* @returns {VElement|null} The previous sibling element.
*/
prevSibling(node) {
let prevElement = null
for (const siblingNode of (node.parent && node.parent.children) || []) {
if (siblingNode === node) {
return prevElement
}
if (siblingNode.type === 'VElement') {
prevElement = siblingNode
}
}
return null
},
/**
* Check whether the given directive attribute has their empty value (`=""`).
* @param {VDirective} node The directive attribute node to check.
* @param {RuleContext} context The rule context to use parser services.
* @returns {boolean} `true` if the directive attribute has their empty value (`=""`).
*/
isEmptyValueDirective(node, context) {
if (node.value == null) {
return false
}
if (node.value.expression != null) {
return false
}
let valueText = context.getSourceCode().getText(node.value)
if (
(valueText[0] === '"' || valueText[0] === "'") &&
valueText[0] === valueText[valueText.length - 1]
) {
// quoted
valueText = valueText.slice(1, -1)
}
if (!valueText) {
// empty
return true
}
return false
},
/**
* Check whether the given directive attribute has their empty expression value (e.g. `=" "`, `="/* */"`).
* @param {VDirective} node The directive attribute node to check.
* @param {RuleContext} context The rule context to use parser services.
* @returns {boolean} `true` if the directive attribute has their empty expression value.
*/
isEmptyExpressionValueDirective(node, context) {
if (node.value == null) {
return false
}
if (node.value.expression != null) {
return false
}
const sourceCode = context.getSourceCode()
const valueNode = node.value
const tokenStore = sourceCode.parserServices.getTemplateBodyTokenStore()
let quote1 = null
let quote2 = null
// `node.value` may be only comments, so cannot get the correct tokens with `tokenStore.getTokens(node.value)`.
for (const token of tokenStore.getTokens(node)) {
if (token.range[1] <= valueNode.range[0]) {
continue
}
if (valueNode.range[1] <= token.range[0]) {
// empty
return true
}
if (
!quote1 &&
token.type === 'Punctuator' &&
(token.value === '"' || token.value === "'")
) {
quote1 = token
continue
}
if (
!quote2 &&
quote1 &&
token.type === 'Punctuator' &&
token.value === quote1.value
) {
quote2 = token
continue
}
// not empty
return false
}
// empty
return true
},
/**
* Get the attribute which has the given name.
* @param {VElement} node The start tag node to check.
* @param {string} name The attribute name to check.
* @param {string} [value] The attribute value to check.
* @returns {VAttribute | null} The found attribute.
*/
getAttribute,
/**
* Check whether the given start tag has specific directive.
* @param {VElement} node The start tag node to check.
* @param {string} name The attribute name to check.
* @param {string} [value] The attribute value to check.
* @returns {boolean} `true` if the start tag has the attribute.
*/
hasAttribute,
/**
* Get the directive list which has the given name.
* @param {VElement | VStartTag} node The start tag node to check.
* @param {string} name The directive name to check.
* @returns {VDirective[]} The array of `v-slot` directives.
*/
getDirectives,
/**
* Get the directive which has the given name.
* @param {VElement} node The start tag node to check.
* @param {string} name The directive name to check.
* @param {string} [argument] The directive argument to check.
* @returns {VDirective | null} The found directive.
*/
getDirective,
/**
* Check whether the given start tag has specific directive.
* @param {VElement} node The start tag node to check.
* @param {string} name The directive name to check.
* @param {string} [argument] The directive argument to check.
* @returns {boolean} `true` if the start tag has the directive.
*/
hasDirective,
isVBindSameNameShorthand,
/**
* Returns the list of all registered components
* @param {ObjectExpression} componentObject
* @returns { { node: Property, name: string }[] } Array of ASTNodes
*/
getRegisteredComponents(componentObject) {
const componentsNode = componentObject.properties.find(
/**
* @param {ESNode} p
* @returns {p is (Property & { key: Identifier & {name: 'components'}, value: ObjectExpression })}
*/
(p) =>
p.type === 'Property' &&
getStaticPropertyName(p) === 'components' &&
p.value.type === 'ObjectExpression'
)
if (!componentsNode) {
return []
}
return componentsNode.value.properties
.filter(isProperty)
.map((node) => {
const name = getStaticPropertyName(node)
return name ? { node, name } : null
})
.filter(isDef)
},
/**
* Check whether the previous sibling element has `if` or `else-if` directive.
* @param {VElement} node The element node to check.
* @returns {boolean} `true` if the previous sibling element has `if` or `else-if` directive.
*/
prevElementHasIf(node) {
const prev = this.prevSibling(node)
return (
prev != null &&
prev.startTag.attributes.some(
(a) =>
a.directive &&
(a.key.name.name === 'if' || a.key.name.name === 'else-if')
)
)
},
/**
* Returns a generator with all child element v-if chains of the given element.
* @param {VElement} node The element node to check.
* @returns {IterableIterator<VElement[]>}
*/
*iterateChildElementsChains(node) {
let vIf = false
/** @type {VElement[]} */
let elementChain = []
for (const childNode of node.children) {
if (childNode.type === 'VElement') {
let connected
if (hasDirective(childNode, 'if')) {
connected = false
vIf = true
} else if (hasDirective(childNode, 'else-if')) {
connected = vIf
vIf = true
} else if (hasDirective(childNode, 'else')) {
connected = vIf
vIf = false
} else {
connected = false
vIf = false
}
if (connected) {
elementChain.push(childNode)
} else {
if (elementChain.length > 0) {
yield elementChain
}
elementChain = [childNode]
}
} else if (childNode.type !== 'VText' || childNode.value.trim() !== '') {
vIf = false
}
}
if (elementChain.length > 0) {
yield elementChain
}
},
/**
* @param {ASTNode} node
* @returns {node is Literal | TemplateLiteral}
*/
isStringLiteral(node) {
return (
(node.type === 'Literal' && typeof node.value === 'string') ||
(node.type === 'TemplateLiteral' && node.expressions.length === 0)
)
},
/**
* Check whether the given node is a custom component or not.
* @param {VElement} node The start tag node to check.
* @returns {boolean} `true` if the node is a custom component.
*/
isCustomComponent(node) {
return (
(this.isHtmlElementNode(node) &&
!this.isHtmlWellKnownElementName(node.rawName)) ||
(this.isSvgElementNode(node) &&
!this.isSvgWellKnownElementName(node.rawName)) ||
hasAttribute(node, 'is') ||
hasDirective(node, 'bind', 'is') ||
hasDirective(node, 'is')
)
},
/**
* Check whether the given node is a HTML element or not.
* @param {VElement} node The node to check.
* @returns {boolean} `true` if the node is a HTML element.
*/
isHtmlElementNode(node) {
return node.namespace === NS.HTML
},
/**
* Check whether the given node is a SVG element or not.
* @param {VElement} node The node to check.
* @returns {boolean} `true` if the name is a SVG element.
*/
isSvgElementNode(node) {
return node.namespace === NS.SVG
},
/**
* Check whether the given name is a MathML element or not.
* @param {VElement} node The node to check.
* @returns {boolean} `true` if the node is a MathML element.
*/
isMathMLElementNode(node) {
return node.namespace === NS.MathML
},
/**
* Check whether the given name is an well-known element or not.
* @param {string} name The name to check.
* @returns {boolean} `true` if the name is an well-known element name.
*/
isHtmlWellKnownElementName(name) {
return HTML_ELEMENT_NAMES.has(name)
},
/**
* Check whether the given name is an well-known SVG element or not.
* @param {string} name The name to check.
* @returns {boolean} `true` if the name is an well-known SVG element name.
*/
isSvgWellKnownElementName(name) {
return SVG_ELEMENT_NAMES.has(name)
},
/**
* Check whether the given name is a void element name or not.