index.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. 'use strict'
  7. const { getScope } = require('./scope')
  8. /**
  9. * @typedef {import('eslint').Rule.RuleModule} RuleModule
  10. * @typedef {import('estree').Position} Position
  11. * @typedef {import('eslint').Rule.CodePath} CodePath
  12. * @typedef {import('eslint').Rule.CodePathSegment} CodePathSegment
  13. */
  14. /**
  15. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayProp} ComponentArrayProp
  16. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectProp} ComponentObjectProp
  17. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeProp} ComponentTypeProp
  18. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeProp} ComponentInferTypeProp
  19. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownProp} ComponentUnknownProp
  20. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentProp} ComponentProp
  21. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayEmit} ComponentArrayEmit
  22. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectEmit} ComponentObjectEmit
  23. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeEmit} ComponentTypeEmit
  24. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentInferTypeEmit} ComponentInferTypeEmit
  25. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownEmit} ComponentUnknownEmit
  26. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentEmit} ComponentEmit
  27. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentModelName} ComponentModelName
  28. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentModel} ComponentModel
  29. */
  30. /**
  31. * @typedef { {key: string | null, value: BlockStatement | null} } ComponentComputedProperty
  32. */
  33. /**
  34. * @typedef { 'props' | 'asyncData' | 'data' | 'computed' | 'setup' | 'watch' | 'methods' | 'provide' | 'inject' | 'expose' } GroupName
  35. * @typedef { { type: 'array', name: string, groupName: GroupName, node: Literal | TemplateLiteral } } ComponentArrayPropertyData
  36. * @typedef { { type: 'object', name: string, groupName: GroupName, node: Identifier | Literal | TemplateLiteral, property: Property } } ComponentObjectPropertyData
  37. * @typedef { ComponentArrayPropertyData | ComponentObjectPropertyData } ComponentPropertyData
  38. */
  39. /**
  40. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectType} VueObjectType
  41. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectData} VueObjectData
  42. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueVisitor} VueVisitor
  43. * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ScriptSetupVisitor} ScriptSetupVisitor
  44. */
  45. // ------------------------------------------------------------------------------
  46. // Helpers
  47. // ------------------------------------------------------------------------------
  48. const HTML_ELEMENT_NAMES = new Set(require('./html-elements.json'))
  49. const SVG_ELEMENT_NAMES = new Set(require('./svg-elements.json'))
  50. const MATH_ELEMENT_NAMES = new Set(require('./math-elements.json'))
  51. const VOID_ELEMENT_NAMES = new Set(require('./void-elements.json'))
  52. const VUE2_BUILTIN_COMPONENT_NAMES = new Set(
  53. require('./vue2-builtin-components')
  54. )
  55. const VUE3_BUILTIN_COMPONENT_NAMES = new Set(
  56. require('./vue3-builtin-components')
  57. )
  58. const VUE_BUILTIN_ELEMENT_NAMES = new Set(require('./vue-builtin-elements'))
  59. const path = require('path')
  60. const vueEslintParser = require('vue-eslint-parser')
  61. const { traverseNodes, getFallbackKeys, NS } = vueEslintParser.AST
  62. const {
  63. findVariable,
  64. ReferenceTracker
  65. } = require('@eslint-community/eslint-utils')
  66. const {
  67. getComponentPropsFromTypeDefine,
  68. getComponentEmitsFromTypeDefine,
  69. isTypeNode
  70. } = require('./ts-utils')
  71. /**
  72. * @type { WeakMap<RuleContext, Token[]> }
  73. */
  74. const componentComments = new WeakMap()
  75. /** @type { Map<string, RuleModule> | null } */
  76. let coreRuleMap = null
  77. /** @type { Map<string, RuleModule> } */
  78. const stylisticRuleMap = new Map()
  79. /**
  80. * Get the core rule implementation from the rule name
  81. * @param {string} name
  82. * @returns {RuleModule | null}
  83. */
  84. function getCoreRule(name) {
  85. const eslint = require('eslint')
  86. try {
  87. const map = coreRuleMap || (coreRuleMap = new eslint.Linter().getRules())
  88. return map.get(name) || null
  89. } catch {
  90. // getRules() is no longer available in flat config.
  91. }
  92. const { builtinRules } = require('eslint/use-at-your-own-risk')
  93. return /** @type {any} */ (builtinRules.get(name) || null)
  94. }
  95. /**
  96. * Get ESLint Stylistic rule implementation from the rule name
  97. * @param {string} name
  98. * @param {'@stylistic/eslint-plugin' | '@stylistic/eslint-plugin-ts' | '@stylistic/eslint-plugin-js'} [preferModule]
  99. * @returns {RuleModule | null}
  100. */
  101. function getStylisticRule(name, preferModule) {
  102. if (!preferModule) {
  103. const cached = stylisticRuleMap.get(name)
  104. if (cached) {
  105. return cached
  106. }
  107. }
  108. const stylisticPluginNames = [
  109. '@stylistic/eslint-plugin',
  110. '@stylistic/eslint-plugin-ts',
  111. '@stylistic/eslint-plugin-js'
  112. ]
  113. if (preferModule) {
  114. stylisticPluginNames.unshift(preferModule)
  115. }
  116. for (const stylisticPluginName of stylisticPluginNames) {
  117. try {
  118. const plugin = createRequire(`${process.cwd()}/__placeholder__.js`)(
  119. stylisticPluginName
  120. )
  121. const rule = plugin?.rules?.[name]
  122. if (!preferModule) stylisticRuleMap.set(name, rule)
  123. return rule
  124. } catch {
  125. // ignore
  126. }
  127. }
  128. return null
  129. }
  130. /**
  131. * @template {object} T
  132. * @param {T} target
  133. * @param {Partial<T>[]} propsArray
  134. * @returns {T}
  135. */
  136. function newProxy(target, ...propsArray) {
  137. const result = new Proxy(
  138. {},
  139. {
  140. get(_object, key) {
  141. for (const props of propsArray) {
  142. if (key in props) {
  143. // @ts-expect-error
  144. return props[key]
  145. }
  146. }
  147. // @ts-expect-error
  148. return target[key]
  149. },
  150. has(_object, key) {
  151. return key in target
  152. },
  153. ownKeys(_object) {
  154. return Reflect.ownKeys(target)
  155. },
  156. getPrototypeOf(_object) {
  157. return Reflect.getPrototypeOf(target)
  158. }
  159. }
  160. )
  161. return /** @type {T} */ (result)
  162. }
  163. /**
  164. * Wrap the rule context object to override methods which access to tokens (such as getTokenAfter).
  165. * @param {RuleContext} context The rule context object.
  166. * @param {ParserServices.TokenStore} tokenStore The token store object for template.
  167. * @param {Object} options The option of this rule.
  168. * @param {boolean} [options.applyDocument] If `true`, apply check to document fragment.
  169. * @returns {RuleContext}
  170. */
  171. function wrapContextToOverrideTokenMethods(context, tokenStore, options) {
  172. const eslintSourceCode = context.getSourceCode()
  173. const rootNode = options.applyDocument
  174. ? eslintSourceCode.parserServices.getDocumentFragment &&
  175. eslintSourceCode.parserServices.getDocumentFragment()
  176. : eslintSourceCode.ast.templateBody
  177. /** @type {Token[] | null} */
  178. let tokensAndComments = null
  179. function getTokensAndComments() {
  180. if (tokensAndComments) {
  181. return tokensAndComments
  182. }
  183. tokensAndComments = rootNode
  184. ? tokenStore.getTokens(rootNode, {
  185. includeComments: true
  186. })
  187. : []
  188. return tokensAndComments
  189. }
  190. /** @param {number} index */
  191. function getNodeByRangeIndex(index) {
  192. if (!rootNode) {
  193. return eslintSourceCode.ast
  194. }
  195. /** @type {ASTNode} */
  196. let result = eslintSourceCode.ast
  197. /** @type {ASTNode[]} */
  198. const skipNodes = []
  199. let breakFlag = false
  200. traverseNodes(rootNode, {
  201. enterNode(node, parent) {
  202. if (breakFlag) {
  203. return
  204. }
  205. if (skipNodes[0] === parent) {
  206. skipNodes.unshift(node)
  207. return
  208. }
  209. if (node.range[0] <= index && index < node.range[1]) {
  210. result = node
  211. } else {
  212. skipNodes.unshift(node)
  213. }
  214. },
  215. leaveNode(node) {
  216. if (breakFlag) {
  217. return
  218. }
  219. if (result === node) {
  220. breakFlag = true
  221. } else if (skipNodes[0] === node) {
  222. skipNodes.shift()
  223. }
  224. }
  225. })
  226. return result
  227. }
  228. const sourceCode = newProxy(
  229. eslintSourceCode,
  230. {
  231. get tokensAndComments() {
  232. return getTokensAndComments()
  233. },
  234. getNodeByRangeIndex,
  235. // @ts-expect-error -- Added in ESLint v8.38.0
  236. getDeclaredVariables
  237. },
  238. tokenStore
  239. )
  240. /** @type {WeakMap<ASTNode, import('eslint').Scope.ScopeManager>} */
  241. const containerScopes = new WeakMap()
  242. /**
  243. * @param {ASTNode} node
  244. * @returns {import('eslint').Scope.ScopeManager|null}
  245. */
  246. function getContainerScope(node) {
  247. const exprContainer = getVExpressionContainer(node)
  248. if (!exprContainer) {
  249. return null
  250. }
  251. const cache = containerScopes.get(exprContainer)
  252. if (cache) {
  253. return cache
  254. }
  255. const programNode = eslintSourceCode.ast
  256. const parserOptions =
  257. context.languageOptions?.parserOptions ?? context.parserOptions ?? {}
  258. const ecmaFeatures = parserOptions.ecmaFeatures || {}
  259. const ecmaVersion =
  260. context.languageOptions?.ecmaVersion ?? parserOptions.ecmaVersion ?? 2020
  261. const sourceType = programNode.sourceType
  262. try {
  263. const eslintScope = createRequire(require.resolve('eslint'))(
  264. 'eslint-scope'
  265. )
  266. const expStmt = newProxy(exprContainer, {
  267. // @ts-expect-error
  268. type: 'ExpressionStatement'
  269. })
  270. const scopeProgram = newProxy(programNode, {
  271. // @ts-expect-error
  272. body: [expStmt]
  273. })
  274. const scope = eslintScope.analyze(scopeProgram, {
  275. ignoreEval: true,
  276. nodejsScope: false,
  277. impliedStrict: ecmaFeatures.impliedStrict,
  278. ecmaVersion,
  279. sourceType,
  280. fallback: getFallbackKeys
  281. })
  282. containerScopes.set(exprContainer, scope)
  283. return scope
  284. } catch (error) {
  285. // ignore
  286. // console.log(error)
  287. }
  288. return null
  289. }
  290. return newProxy(context, {
  291. getSourceCode() {
  292. return sourceCode
  293. },
  294. get sourceCode() {
  295. return sourceCode
  296. },
  297. getDeclaredVariables
  298. })
  299. /**
  300. * @param {ESNode} node
  301. * @returns {Variable[]}
  302. */
  303. function getDeclaredVariables(node) {
  304. const scope = getContainerScope(node)
  305. return (
  306. scope?.getDeclaredVariables?.(node) ??
  307. context.getDeclaredVariables?.(node) ??
  308. []
  309. )
  310. }
  311. }
  312. /**
  313. * Wrap the rule context object to override report method to skip the dynamic argument.
  314. * @param {RuleContext} context The rule context object.
  315. * @returns {RuleContext}
  316. */
  317. function wrapContextToOverrideReportMethodToSkipDynamicArgument(context) {
  318. const sourceCode = context.getSourceCode()
  319. const templateBody = sourceCode.ast.templateBody
  320. if (!templateBody) {
  321. return context
  322. }
  323. /** @type {Range[]} */
  324. const directiveKeyRanges = []
  325. traverseNodes(templateBody, {
  326. enterNode(node, parent) {
  327. if (
  328. parent &&
  329. parent.type === 'VDirectiveKey' &&
  330. node.type === 'VExpressionContainer'
  331. ) {
  332. directiveKeyRanges.push(node.range)
  333. }
  334. },
  335. leaveNode() {}
  336. })
  337. return newProxy(context, {
  338. report(descriptor, ...args) {
  339. let range = null
  340. if (descriptor.loc) {
  341. const startLoc = descriptor.loc.start || descriptor.loc
  342. const endLoc = descriptor.loc.end || startLoc
  343. range = [
  344. sourceCode.getIndexFromLoc(startLoc),
  345. sourceCode.getIndexFromLoc(endLoc)
  346. ]
  347. } else if (descriptor.node) {
  348. range = descriptor.node.range
  349. }
  350. if (range) {
  351. for (const directiveKeyRange of directiveKeyRanges) {
  352. if (
  353. range[0] < directiveKeyRange[1] &&
  354. directiveKeyRange[0] < range[1]
  355. ) {
  356. return
  357. }
  358. }
  359. }
  360. context.report(descriptor, ...args)
  361. }
  362. })
  363. }
  364. /**
  365. * @callback WrapRuleCreate
  366. * @param {RuleContext} ruleContext
  367. * @param {WrapRuleCreateContext} wrapContext
  368. * @returns {TemplateListener}
  369. *
  370. * @typedef {object} WrapRuleCreateContext
  371. * @property {RuleListener} baseHandlers
  372. */
  373. /**
  374. * @callback WrapRulePreprocess
  375. * @param {RuleContext} ruleContext
  376. * @param {WrapRulePreprocessContext} wrapContext
  377. * @returns {void}
  378. *
  379. * @typedef {object} WrapRulePreprocessContext
  380. * @property { (override: Partial<RuleContext>) => RuleContext } wrapContextToOverrideProperties Wrap the rule context object to override
  381. * @property { (visitor: TemplateListener) => void } defineVisitor Define template body visitor
  382. */
  383. /**
  384. * @typedef {object} WrapRuleOptions
  385. * @property {string[]} [categories] The categories of this rule.
  386. * @property {boolean} [skipDynamicArguments] If `true`, skip validation within dynamic arguments.
  387. * @property {boolean} [skipDynamicArgumentsReport] If `true`, skip report within dynamic arguments.
  388. * @property {boolean} [applyDocument] If `true`, apply check to document fragment.
  389. * @property {boolean} [skipBaseHandlers] If `true`, skip base rule handlers.
  390. * @property {WrapRulePreprocess} [preprocess] Preprocess to calling create of base rule.
  391. * @property {WrapRuleCreate} [create] If define, extend base rule.
  392. */
  393. /**
  394. * Wrap a given core rule to apply it to Vue.js template.
  395. * @param {string} coreRuleName The name of the core rule implementation to wrap.
  396. * @param {WrapRuleOptions} [options] The option of this rule.
  397. * @returns {RuleModule} The wrapped rule implementation.
  398. */
  399. function wrapCoreRule(coreRuleName, options) {
  400. const coreRule = getCoreRule(coreRuleName)
  401. if (!coreRule) {
  402. return {
  403. meta: {
  404. type: 'problem',
  405. docs: {
  406. url: `https://eslint.vuejs.org/rules/${coreRuleName}.html`
  407. }
  408. },
  409. create(context) {
  410. return defineTemplateBodyVisitor(context, {
  411. "VElement[name='template'][parent.type='VDocumentFragment']"(node) {
  412. context.report({
  413. node,
  414. 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.`
  415. })
  416. }
  417. })
  418. }
  419. }
  420. }
  421. const rule = wrapRuleModule(coreRule, coreRuleName, options)
  422. const meta = {
  423. ...rule.meta,
  424. docs: {
  425. ...rule.meta.docs,
  426. extensionSource: {
  427. url: coreRule.meta.docs.url,
  428. name: 'ESLint core'
  429. }
  430. }
  431. }
  432. return {
  433. ...rule,
  434. meta
  435. }
  436. }
  437. /**
  438. * @typedef {object} RuleNames
  439. * @property {string} core The name of the core rule implementation to wrap.
  440. * @property {string} stylistic The name of ESLint Stylistic rule implementation to wrap.
  441. * @property {string} vue The name of the wrapped rule
  442. */
  443. /**
  444. * Wrap a core rule or ESLint Stylistic rule to apply it to Vue.js template.
  445. * @param {RuleNames|string} ruleNames The names of the rule implementation to wrap.
  446. * @param {WrapRuleOptions} [options] The option of this rule.
  447. * @returns {RuleModule} The wrapped rule implementation.
  448. */
  449. function wrapStylisticOrCoreRule(ruleNames, options) {
  450. const stylisticRuleName =
  451. typeof ruleNames === 'string' ? ruleNames : ruleNames.stylistic
  452. const coreRuleName =
  453. typeof ruleNames === 'string' ? ruleNames : ruleNames.core
  454. const vueRuleName = typeof ruleNames === 'string' ? ruleNames : ruleNames.vue
  455. const stylisticRule = getStylisticRule(stylisticRuleName)
  456. const baseRule = stylisticRule || getCoreRule(coreRuleName)
  457. if (!baseRule) {
  458. return {
  459. meta: {
  460. type: 'problem',
  461. docs: {
  462. url: `https://eslint.vuejs.org/rules/${vueRuleName}.html`
  463. }
  464. },
  465. create(context) {
  466. return defineTemplateBodyVisitor(context, {
  467. "VElement[name='template'][parent.type='VDocumentFragment']"(node) {
  468. context.report({
  469. node,
  470. 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.`
  471. })
  472. }
  473. })
  474. }
  475. }
  476. }
  477. const rule = wrapRuleModule(baseRule, vueRuleName, options)
  478. const jsRule = getStylisticRule(
  479. stylisticRuleName,
  480. '@stylistic/eslint-plugin-js'
  481. )
  482. const description = stylisticRule
  483. ? `${jsRule?.meta.docs.description} in \`<template>\``
  484. : rule.meta.docs.description
  485. const meta = {
  486. ...rule.meta,
  487. docs: {
  488. ...rule.meta.docs,
  489. description,
  490. extensionSource: {
  491. url: baseRule.meta.docs.url,
  492. name: stylisticRule ? 'ESLint Stylistic' : 'ESLint core'
  493. }
  494. },
  495. deprecated: undefined,
  496. replacedBy: undefined
  497. }
  498. return {
  499. ...rule,
  500. meta
  501. }
  502. }
  503. /**
  504. * Wrap a given rule to apply it to Vue.js template.
  505. * @param {RuleModule} baseRule The rule implementation to wrap.
  506. * @param {string} ruleName The name of the wrapped rule.
  507. * @param {WrapRuleOptions} [options] The option of this rule.
  508. * @returns {RuleModule} The wrapped rule implementation.
  509. */
  510. function wrapRuleModule(baseRule, ruleName, options) {
  511. let description = baseRule.meta.docs.description
  512. if (description) {
  513. description += ' in `<template>`'
  514. }
  515. const {
  516. categories,
  517. skipDynamicArguments,
  518. skipDynamicArgumentsReport,
  519. skipBaseHandlers,
  520. applyDocument,
  521. preprocess,
  522. create
  523. } = options || {}
  524. return {
  525. create(context) {
  526. const sourceCode = context.getSourceCode()
  527. const tokenStore =
  528. sourceCode.parserServices.getTemplateBodyTokenStore &&
  529. sourceCode.parserServices.getTemplateBodyTokenStore()
  530. // The `context.getSourceCode()` cannot access the tokens of templates.
  531. // So override the methods which access to tokens by the `tokenStore`.
  532. if (tokenStore) {
  533. context = wrapContextToOverrideTokenMethods(context, tokenStore, {
  534. applyDocument
  535. })
  536. }
  537. if (skipDynamicArgumentsReport) {
  538. context =
  539. wrapContextToOverrideReportMethodToSkipDynamicArgument(context)
  540. }
  541. /** @type {TemplateListener} */
  542. const handlers = {}
  543. if (preprocess) {
  544. preprocess(context, {
  545. wrapContextToOverrideProperties(override) {
  546. context = newProxy(context, override)
  547. return context
  548. },
  549. defineVisitor(visitor) {
  550. compositingVisitors(handlers, visitor)
  551. }
  552. })
  553. }
  554. const baseHandlers = baseRule.create(context)
  555. if (!skipBaseHandlers) {
  556. compositingVisitors(handlers, baseHandlers)
  557. }
  558. // Move `Program` handlers to `VElement[parent.type!='VElement']`
  559. if (handlers.Program) {
  560. handlers[
  561. applyDocument
  562. ? 'VDocumentFragment'
  563. : "VElement[parent.type!='VElement']"
  564. ] = /** @type {any} */ (handlers.Program)
  565. delete handlers.Program
  566. }
  567. if (handlers['Program:exit']) {
  568. handlers[
  569. applyDocument
  570. ? 'VDocumentFragment:exit'
  571. : "VElement[parent.type!='VElement']:exit"
  572. ] = /** @type {any} */ (handlers['Program:exit'])
  573. delete handlers['Program:exit']
  574. }
  575. if (skipDynamicArguments) {
  576. let withinDynamicArguments = false
  577. for (const name of Object.keys(handlers)) {
  578. const original = handlers[name]
  579. /** @param {any[]} args */
  580. handlers[name] = (...args) => {
  581. if (withinDynamicArguments) return
  582. // @ts-expect-error
  583. original(...args)
  584. }
  585. }
  586. handlers['VDirectiveKey > VExpressionContainer'] = () => {
  587. withinDynamicArguments = true
  588. }
  589. handlers['VDirectiveKey > VExpressionContainer:exit'] = () => {
  590. withinDynamicArguments = false
  591. }
  592. }
  593. if (create) {
  594. compositingVisitors(handlers, create(context, { baseHandlers }))
  595. }
  596. if (applyDocument) {
  597. // Apply the handlers to document.
  598. return defineDocumentVisitor(context, handlers)
  599. }
  600. // Apply the handlers to templates.
  601. return defineTemplateBodyVisitor(context, handlers)
  602. },
  603. meta: Object.assign({}, baseRule.meta, {
  604. docs: Object.assign({}, baseRule.meta.docs, {
  605. description,
  606. category: null,
  607. categories,
  608. url: `https://eslint.vuejs.org/rules/${ruleName}.html`
  609. })
  610. })
  611. }
  612. }
  613. // ------------------------------------------------------------------------------
  614. // Exports
  615. // ------------------------------------------------------------------------------
  616. module.exports = {
  617. /**
  618. * Register the given visitor to parser services.
  619. * If the parser service of `vue-eslint-parser` was not found,
  620. * this generates a warning.
  621. *
  622. * @param {RuleContext} context The rule context to use parser services.
  623. * @param {TemplateListener} templateBodyVisitor The visitor to traverse the template body.
  624. * @param {RuleListener} [scriptVisitor] The visitor to traverse the script.
  625. * @param { { templateBodyTriggerSelector: "Program" | "Program:exit" } } [options] The options.
  626. * @returns {RuleListener} The merged visitor.
  627. */
  628. defineTemplateBodyVisitor,
  629. /**
  630. * Register the given visitor to parser services.
  631. * If the parser service of `vue-eslint-parser` was not found,
  632. * this generates a warning.
  633. *
  634. * @param {RuleContext} context The rule context to use parser services.
  635. * @param {TemplateListener} documentVisitor The visitor to traverse the document.
  636. * @param { { triggerSelector: "Program" | "Program:exit" } } [options] The options.
  637. * @returns {RuleListener} The merged visitor.
  638. */
  639. defineDocumentVisitor,
  640. /**
  641. * Wrap a given core rule to apply it to Vue.js template.
  642. * @type {typeof wrapCoreRule}
  643. */
  644. wrapCoreRule,
  645. wrapStylisticOrCoreRule,
  646. getCoreRule,
  647. /**
  648. * Checks whether the given value is defined.
  649. * @template T
  650. * @param {T | null | undefined} v
  651. * @returns {v is T}
  652. */
  653. isDef,
  654. /**
  655. * Flattens arrays, objects and iterable objects.
  656. * @template T
  657. * @param {T | Iterable<T> | null | undefined} v
  658. * @returns {T[]}
  659. */
  660. flatten,
  661. /**
  662. * Get the previous sibling element of the given element.
  663. * @param {VElement} node The element node to get the previous sibling element.
  664. * @returns {VElement|null} The previous sibling element.
  665. */
  666. prevSibling(node) {
  667. let prevElement = null
  668. for (const siblingNode of (node.parent && node.parent.children) || []) {
  669. if (siblingNode === node) {
  670. return prevElement
  671. }
  672. if (siblingNode.type === 'VElement') {
  673. prevElement = siblingNode
  674. }
  675. }
  676. return null
  677. },
  678. /**
  679. * Check whether the given directive attribute has their empty value (`=""`).
  680. * @param {VDirective} node The directive attribute node to check.
  681. * @param {RuleContext} context The rule context to use parser services.
  682. * @returns {boolean} `true` if the directive attribute has their empty value (`=""`).
  683. */
  684. isEmptyValueDirective(node, context) {
  685. if (node.value == null) {
  686. return false
  687. }
  688. if (node.value.expression != null) {
  689. return false
  690. }
  691. let valueText = context.getSourceCode().getText(node.value)
  692. if (
  693. (valueText[0] === '"' || valueText[0] === "'") &&
  694. valueText[0] === valueText[valueText.length - 1]
  695. ) {
  696. // quoted
  697. valueText = valueText.slice(1, -1)
  698. }
  699. if (!valueText) {
  700. // empty
  701. return true
  702. }
  703. return false
  704. },
  705. /**
  706. * Check whether the given directive attribute has their empty expression value (e.g. `=" "`, `="/* &ast;/"`).
  707. * @param {VDirective} node The directive attribute node to check.
  708. * @param {RuleContext} context The rule context to use parser services.
  709. * @returns {boolean} `true` if the directive attribute has their empty expression value.
  710. */
  711. isEmptyExpressionValueDirective(node, context) {
  712. if (node.value == null) {
  713. return false
  714. }
  715. if (node.value.expression != null) {
  716. return false
  717. }
  718. const sourceCode = context.getSourceCode()
  719. const valueNode = node.value
  720. const tokenStore = sourceCode.parserServices.getTemplateBodyTokenStore()
  721. let quote1 = null
  722. let quote2 = null
  723. // `node.value` may be only comments, so cannot get the correct tokens with `tokenStore.getTokens(node.value)`.
  724. for (const token of tokenStore.getTokens(node)) {
  725. if (token.range[1] <= valueNode.range[0]) {
  726. continue
  727. }
  728. if (valueNode.range[1] <= token.range[0]) {
  729. // empty
  730. return true
  731. }
  732. if (
  733. !quote1 &&
  734. token.type === 'Punctuator' &&
  735. (token.value === '"' || token.value === "'")
  736. ) {
  737. quote1 = token
  738. continue
  739. }
  740. if (
  741. !quote2 &&
  742. quote1 &&
  743. token.type === 'Punctuator' &&
  744. token.value === quote1.value
  745. ) {
  746. quote2 = token
  747. continue
  748. }
  749. // not empty
  750. return false
  751. }
  752. // empty
  753. return true
  754. },
  755. /**
  756. * Get the attribute which has the given name.
  757. * @param {VElement} node The start tag node to check.
  758. * @param {string} name The attribute name to check.
  759. * @param {string} [value] The attribute value to check.
  760. * @returns {VAttribute | null} The found attribute.
  761. */
  762. getAttribute,
  763. /**
  764. * Check whether the given start tag has specific directive.
  765. * @param {VElement} node The start tag node to check.
  766. * @param {string} name The attribute name to check.
  767. * @param {string} [value] The attribute value to check.
  768. * @returns {boolean} `true` if the start tag has the attribute.
  769. */
  770. hasAttribute,
  771. /**
  772. * Get the directive list which has the given name.
  773. * @param {VElement | VStartTag} node The start tag node to check.
  774. * @param {string} name The directive name to check.
  775. * @returns {VDirective[]} The array of `v-slot` directives.
  776. */
  777. getDirectives,
  778. /**
  779. * Get the directive which has the given name.
  780. * @param {VElement} node The start tag node to check.
  781. * @param {string} name The directive name to check.
  782. * @param {string} [argument] The directive argument to check.
  783. * @returns {VDirective | null} The found directive.
  784. */
  785. getDirective,
  786. /**
  787. * Check whether the given start tag has specific directive.
  788. * @param {VElement} node The start tag node to check.
  789. * @param {string} name The directive name to check.
  790. * @param {string} [argument] The directive argument to check.
  791. * @returns {boolean} `true` if the start tag has the directive.
  792. */
  793. hasDirective,
  794. isVBindSameNameShorthand,
  795. /**
  796. * Returns the list of all registered components
  797. * @param {ObjectExpression} componentObject
  798. * @returns { { node: Property, name: string }[] } Array of ASTNodes
  799. */
  800. getRegisteredComponents(componentObject) {
  801. const componentsNode = componentObject.properties.find(
  802. /**
  803. * @param {ESNode} p
  804. * @returns {p is (Property & { key: Identifier & {name: 'components'}, value: ObjectExpression })}
  805. */
  806. (p) =>
  807. p.type === 'Property' &&
  808. getStaticPropertyName(p) === 'components' &&
  809. p.value.type === 'ObjectExpression'
  810. )
  811. if (!componentsNode) {
  812. return []
  813. }
  814. return componentsNode.value.properties
  815. .filter(isProperty)
  816. .map((node) => {
  817. const name = getStaticPropertyName(node)
  818. return name ? { node, name } : null
  819. })
  820. .filter(isDef)
  821. },
  822. /**
  823. * Check whether the previous sibling element has `if` or `else-if` directive.
  824. * @param {VElement} node The element node to check.
  825. * @returns {boolean} `true` if the previous sibling element has `if` or `else-if` directive.
  826. */
  827. prevElementHasIf(node) {
  828. const prev = this.prevSibling(node)
  829. return (
  830. prev != null &&
  831. prev.startTag.attributes.some(
  832. (a) =>
  833. a.directive &&
  834. (a.key.name.name === 'if' || a.key.name.name === 'else-if')
  835. )
  836. )
  837. },
  838. /**
  839. * Returns a generator with all child element v-if chains of the given element.
  840. * @param {VElement} node The element node to check.
  841. * @returns {IterableIterator<VElement[]>}
  842. */
  843. *iterateChildElementsChains(node) {
  844. let vIf = false
  845. /** @type {VElement[]} */
  846. let elementChain = []
  847. for (const childNode of node.children) {
  848. if (childNode.type === 'VElement') {
  849. let connected
  850. if (hasDirective(childNode, 'if')) {
  851. connected = false
  852. vIf = true
  853. } else if (hasDirective(childNode, 'else-if')) {
  854. connected = vIf
  855. vIf = true
  856. } else if (hasDirective(childNode, 'else')) {
  857. connected = vIf
  858. vIf = false
  859. } else {
  860. connected = false
  861. vIf = false
  862. }
  863. if (connected) {
  864. elementChain.push(childNode)
  865. } else {
  866. if (elementChain.length > 0) {
  867. yield elementChain
  868. }
  869. elementChain = [childNode]
  870. }
  871. } else if (childNode.type !== 'VText' || childNode.value.trim() !== '') {
  872. vIf = false
  873. }
  874. }
  875. if (elementChain.length > 0) {
  876. yield elementChain
  877. }
  878. },
  879. /**
  880. * @param {ASTNode} node
  881. * @returns {node is Literal | TemplateLiteral}
  882. */
  883. isStringLiteral(node) {
  884. return (
  885. (node.type === 'Literal' && typeof node.value === 'string') ||
  886. (node.type === 'TemplateLiteral' && node.expressions.length === 0)
  887. )
  888. },
  889. /**
  890. * Check whether the given node is a custom component or not.
  891. * @param {VElement} node The start tag node to check.
  892. * @returns {boolean} `true` if the node is a custom component.
  893. */
  894. isCustomComponent(node) {
  895. return (
  896. (this.isHtmlElementNode(node) &&
  897. !this.isHtmlWellKnownElementName(node.rawName)) ||
  898. (this.isSvgElementNode(node) &&
  899. !this.isSvgWellKnownElementName(node.rawName)) ||
  900. (this.isMathElementNode(node) &&
  901. !this.isMathWellKnownElementName(node.rawName)) ||
  902. hasAttribute(node, 'is') ||
  903. hasDirective(node, 'bind', 'is') ||
  904. hasDirective(node, 'is')
  905. )
  906. },
  907. /**
  908. * Check whether the given node is a HTML element or not.
  909. * @param {VElement} node The node to check.
  910. * @returns {boolean} `true` if the node is a HTML element.
  911. */
  912. isHtmlElementNode(node) {
  913. return node.namespace === NS.HTML
  914. },
  915. /**
  916. * Check whether the given node is a SVG element or not.
  917. * @param {VElement} node The node to check.
  918. * @returns {boolean} `true` if the name is a SVG element.
  919. */
  920. isSvgElementNode(node) {
  921. return node.namespace === NS.SVG
  922. },
  923. /**
  924. * Check whether the given name is a MathML element or not.
  925. * @param {VElement} node The node to check.
  926. * @returns {boolean} `true` if the node is a MathML element.
  927. */
  928. isMathElementNode(node) {
  929. return node.namespace === NS.MathML
  930. },
  931. /**
  932. * Check whether the given name is an well-known element or not.
  933. * @param {string} name The name to check.
  934. * @returns {boolean} `true` if the name is an well-known element name.
  935. */
  936. isHtmlWellKnownElementName(name) {
  937. return HTML_ELEMENT_NAMES.has(name)
  938. },
  939. /**
  940. * Check whether the given name is an well-known SVG element or not.
  941. * @param {string} name The name to check.
  942. * @returns {boolean} `true` if the name is an well-known SVG element name.
  943. */
  944. isSvgWellKnownElementName(name) {
  945. return SVG_ELEMENT_NAMES.has(name)
  946. },
  947. /**
  948. * Check whether the given name is a well-known MathML element or not.
  949. * @param {string} name The name to check.
  950. * @returns {boolean} `true` if the name is a well-known MathML element name.
  951. */
  952. isMathWellKnownElementName(name) {
  953. return MATH_ELEMENT_NAMES.has(name)
  954. },
  955. /**
  956. * Check whether the given name is a void element name or not.
  957. * @param {string} name The name to check.
  958. * @returns {boolean} `true` if the name is a void element name.
  959. */
  960. isHtmlVoidElementName(name) {
  961. return VOID_ELEMENT_NAMES.has(name)
  962. },
  963. /**
  964. * Check whether the given name is Vue builtin component name or not.
  965. * @param {string} name The name to check.
  966. * @returns {boolean} `true` if the name is a builtin component name
  967. */
  968. isBuiltInComponentName(name) {
  969. return (
  970. VUE3_BUILTIN_COMPONENT_NAMES.has(name) ||
  971. VUE2_BUILTIN_COMPONENT_NAMES.has(name)
  972. )
  973. },
  974. /**
  975. * Check whether the given name is Vue builtin element name or not.
  976. * @param {string} name The name to check.
  977. * @returns {boolean} `true` if the name is a builtin Vue element name
  978. */
  979. isVueBuiltInElementName(name) {
  980. return VUE_BUILTIN_ELEMENT_NAMES.has(name.toLowerCase())
  981. },
  982. /**
  983. * Check whether the given name is Vue builtin directive name or not.
  984. * @param {string} name The name to check.
  985. * @returns {boolean} `true` if the name is a builtin Directive name
  986. */
  987. isBuiltInDirectiveName(name) {
  988. return (
  989. name === 'bind' ||
  990. name === 'on' ||
  991. name === 'text' ||
  992. name === 'html' ||
  993. name === 'show' ||
  994. name === 'if' ||
  995. name === 'else' ||
  996. name === 'else-if' ||
  997. name === 'for' ||
  998. name === 'model' ||
  999. name === 'slot' ||
  1000. name === 'pre' ||
  1001. name === 'cloak' ||
  1002. name === 'once' ||
  1003. name === 'memo' ||
  1004. name === 'is'
  1005. )
  1006. },
  1007. /**
  1008. * Gets the property name of a given node.
  1009. * @param {Property|AssignmentProperty|MethodDefinition|MemberExpression} node - The node to get.
  1010. * @return {string|null} The property name if static. Otherwise, null.
  1011. */
  1012. getStaticPropertyName,
  1013. /**
  1014. * Gets the string of a given node.
  1015. * @param {Literal|TemplateLiteral} node - The node to get.
  1016. * @return {string|null} The string if static. Otherwise, null.
  1017. */
  1018. getStringLiteralValue,
  1019. /**
  1020. * Get all props by looking at all component's properties
  1021. * @param {ObjectExpression} componentObject Object with component definition
  1022. * @return {(ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp)[]} Array of component props
  1023. */
  1024. getComponentPropsFromOptions,
  1025. /**
  1026. * Get all emits by looking at all component's properties
  1027. * @param {ObjectExpression} componentObject Object with component definition
  1028. * @return {(ComponentArrayEmit | ComponentObjectEmit | ComponentUnknownEmit)[]} Array of component emits
  1029. */
  1030. getComponentEmitsFromOptions,
  1031. /**
  1032. * Get all computed properties by looking at all component's properties
  1033. * @param {ObjectExpression} componentObject Object with component definition
  1034. * @return {ComponentComputedProperty[]} Array of computed properties in format: [{key: String, value: ASTNode}]
  1035. */
  1036. getComputedProperties(componentObject) {
  1037. const computedPropertiesNode = componentObject.properties.find(
  1038. /**
  1039. * @param {ESNode} p
  1040. * @returns {p is (Property & { key: Identifier & {name: 'computed'}, value: ObjectExpression })}
  1041. */
  1042. (p) =>
  1043. p.type === 'Property' &&
  1044. getStaticPropertyName(p) === 'computed' &&
  1045. p.value.type === 'ObjectExpression'
  1046. )
  1047. if (!computedPropertiesNode) {
  1048. return []
  1049. }
  1050. return computedPropertiesNode.value.properties
  1051. .filter(isProperty)
  1052. .map((cp) => {
  1053. const key = getStaticPropertyName(cp)
  1054. /** @type {Expression} */
  1055. const propValue = skipTSAsExpression(cp.value)
  1056. /** @type {BlockStatement | null} */
  1057. let value = null
  1058. if (propValue.type === 'FunctionExpression') {
  1059. value = propValue.body
  1060. } else if (propValue.type === 'ObjectExpression') {
  1061. const get =
  1062. /** @type {(Property & { value: FunctionExpression }) | null} */ (
  1063. findProperty(
  1064. propValue,
  1065. 'get',
  1066. (p) => p.value.type === 'FunctionExpression'
  1067. )
  1068. )
  1069. value = get ? get.value.body : null
  1070. }
  1071. return { key, value }
  1072. })
  1073. },
  1074. /**
  1075. * Get getter body from computed function
  1076. * @param {CallExpression} callExpression call of computed function
  1077. * @return {FunctionExpression | ArrowFunctionExpression | null} getter function
  1078. */
  1079. getGetterBodyFromComputedFunction(callExpression) {
  1080. if (callExpression.arguments.length <= 0) {
  1081. return null
  1082. }
  1083. const arg = callExpression.arguments[0]
  1084. if (
  1085. arg.type === 'FunctionExpression' ||
  1086. arg.type === 'ArrowFunctionExpression'
  1087. ) {
  1088. return arg
  1089. }
  1090. if (arg.type === 'ObjectExpression') {
  1091. const getProperty =
  1092. /** @type {(Property & { value: FunctionExpression | ArrowFunctionExpression }) | null} */ (
  1093. findProperty(
  1094. arg,
  1095. 'get',
  1096. (p) =>
  1097. p.value.type === 'FunctionExpression' ||
  1098. p.value.type === 'ArrowFunctionExpression'
  1099. )
  1100. )
  1101. return getProperty ? getProperty.value : null
  1102. }
  1103. return null
  1104. },
  1105. isTypeScriptFile,
  1106. isVueFile,
  1107. /**
  1108. * Checks whether the current file is uses `<script setup>`
  1109. * @param {RuleContext} context The ESLint rule context object.
  1110. */
  1111. isScriptSetup,
  1112. /**
  1113. * Gets the element of `<script setup>`
  1114. * @param {RuleContext} context The ESLint rule context object.
  1115. * @returns {VElement | null} the element of `<script setup>`
  1116. */
  1117. getScriptSetupElement,
  1118. /**
  1119. * Check if current file is a Vue instance or component and call callback
  1120. * @param {RuleContext} context The ESLint rule context object.
  1121. * @param { (node: ObjectExpression, type: VueObjectType) => void } cb Callback function
  1122. */
  1123. executeOnVue(context, cb) {
  1124. return compositingVisitors(
  1125. this.executeOnVueComponent(context, cb),
  1126. this.executeOnVueInstance(context, cb)
  1127. )
  1128. },
  1129. /**
  1130. * Define handlers to traverse the Vue Objects.
  1131. * Some special events are available to visitor.
  1132. *
  1133. * - `onVueObjectEnter` ... Event when Vue Object is found.
  1134. * - `onVueObjectExit` ... Event when Vue Object visit ends.
  1135. * - `onSetupFunctionEnter` ... Event when setup function found.
  1136. * - `onRenderFunctionEnter` ... Event when render function found.
  1137. *
  1138. * @param {RuleContext} context The ESLint rule context object.
  1139. * @param {VueVisitor} visitor The visitor to traverse the Vue Objects.
  1140. */
  1141. defineVueVisitor(context, visitor) {
  1142. /** @type {VueObjectData | null} */
  1143. let vueStack = null
  1144. /**
  1145. * @param {string} key
  1146. * @param {ESNode} node
  1147. */
  1148. function callVisitor(key, node) {
  1149. if (visitor[key] && vueStack) {
  1150. // @ts-expect-error
  1151. visitor[key](node, vueStack)
  1152. }
  1153. }
  1154. /** @type {NodeListener} */
  1155. const vueVisitor = {}
  1156. for (const key in visitor) {
  1157. vueVisitor[key] = (node) => callVisitor(key, node)
  1158. }
  1159. /**
  1160. * @param {ObjectExpression} node
  1161. */
  1162. vueVisitor.ObjectExpression = (node) => {
  1163. const type = getVueObjectType(context, node)
  1164. if (type) {
  1165. vueStack = {
  1166. node,
  1167. type,
  1168. parent: vueStack,
  1169. get functional() {
  1170. const functional = node.properties.find(
  1171. /**
  1172. * @param {Property | SpreadElement} p
  1173. * @returns {p is Property}
  1174. */
  1175. (p) =>
  1176. p.type === 'Property' &&
  1177. getStaticPropertyName(p) === 'functional'
  1178. )
  1179. if (!functional) {
  1180. return false
  1181. }
  1182. if (
  1183. functional.value.type === 'Literal' &&
  1184. functional.value.value === false
  1185. ) {
  1186. return false
  1187. }
  1188. return true
  1189. }
  1190. }
  1191. callVisitor('onVueObjectEnter', node)
  1192. }
  1193. callVisitor('ObjectExpression', node)
  1194. }
  1195. vueVisitor['ObjectExpression:exit'] = (node) => {
  1196. callVisitor('ObjectExpression:exit', node)
  1197. if (vueStack && vueStack.node === node) {
  1198. callVisitor('onVueObjectExit', node)
  1199. vueStack = vueStack.parent
  1200. }
  1201. }
  1202. if (
  1203. visitor.onSetupFunctionEnter ||
  1204. visitor.onSetupFunctionExit ||
  1205. visitor.onRenderFunctionEnter
  1206. ) {
  1207. const setups = new Set()
  1208. /** @param { (FunctionExpression | ArrowFunctionExpression) & { parent: Property } } node */
  1209. vueVisitor[
  1210. 'Property[value.type=/^(Arrow)?FunctionExpression$/] > :function'
  1211. ] = (node) => {
  1212. /** @type {Property} */
  1213. const prop = node.parent
  1214. if (vueStack && prop.parent === vueStack.node && prop.value === node) {
  1215. const name = getStaticPropertyName(prop)
  1216. if (name === 'setup') {
  1217. callVisitor('onSetupFunctionEnter', node)
  1218. setups.add(node)
  1219. } else if (name === 'render') {
  1220. callVisitor('onRenderFunctionEnter', node)
  1221. }
  1222. }
  1223. callVisitor(
  1224. 'Property[value.type=/^(Arrow)?FunctionExpression$/] > :function',
  1225. node
  1226. )
  1227. }
  1228. if (visitor.onSetupFunctionExit) {
  1229. /** @param { (FunctionExpression | ArrowFunctionExpression) & { parent: Property } } node */
  1230. vueVisitor[
  1231. 'Property[value.type=/^(Arrow)?FunctionExpression$/] > :function:exit'
  1232. ] = (node) => {
  1233. if (setups.has(node)) {
  1234. callVisitor('onSetupFunctionExit', node)
  1235. setups.delete(node)
  1236. }
  1237. }
  1238. }
  1239. }
  1240. return vueVisitor
  1241. },
  1242. /**
  1243. * Define handlers to traverse the AST nodes in `<script setup>`.
  1244. * Some special events are available to visitor.
  1245. *
  1246. * - `onDefinePropsEnter` ... Event when defineProps is found.
  1247. * - `onDefinePropsExit` ... Event when defineProps visit ends.
  1248. * - `onDefineEmitsEnter` ... Event when defineEmits is found.
  1249. * - `onDefineEmitsExit` ... Event when defineEmits visit ends.
  1250. * - `onDefineOptionsEnter` ... Event when defineOptions is found.
  1251. * - `onDefineOptionsExit` ... Event when defineOptions visit ends.
  1252. * - `onDefineSlotsEnter` ... Event when defineSlots is found.
  1253. * - `onDefineSlotsExit` ... Event when defineSlots visit ends.
  1254. * - `onDefineExposeEnter` ... Event when defineExpose is found.
  1255. * - `onDefineExposeExit` ... Event when defineExpose visit ends.
  1256. * - `onDefineModelEnter` ... Event when defineModel is found.
  1257. * - `onDefineModelExit` ... Event when defineModel visit ends.
  1258. *
  1259. * @param {RuleContext} context The ESLint rule context object.
  1260. * @param {ScriptSetupVisitor} visitor The visitor to traverse the AST nodes.
  1261. */
  1262. defineScriptSetupVisitor(context, visitor) {
  1263. const scriptSetup = getScriptSetupElement(context)
  1264. if (scriptSetup == null) {
  1265. return {}
  1266. }
  1267. const scriptSetupRange = scriptSetup.range
  1268. /**
  1269. * @param {ESNode} node
  1270. */
  1271. function inScriptSetup(node) {
  1272. return (
  1273. scriptSetupRange[0] <= node.range[0] &&
  1274. node.range[1] <= scriptSetupRange[1]
  1275. )
  1276. }
  1277. /**
  1278. * @param {string} key
  1279. * @param {ESNode} node
  1280. * @param {any[]} args
  1281. */
  1282. function callVisitor(key, node, ...args) {
  1283. if (visitor[key] && inScriptSetup(node)) {
  1284. // @ts-expect-error
  1285. visitor[key](node, ...args)
  1286. }
  1287. }
  1288. /** @type {NodeListener} */
  1289. const scriptSetupVisitor = {}
  1290. for (const key in visitor) {
  1291. scriptSetupVisitor[key] = (node) => callVisitor(key, node)
  1292. }
  1293. class MacroListener {
  1294. /**
  1295. * @param {string} name
  1296. * @param {string} enterName
  1297. * @param {string} exitName
  1298. * @param {(candidateMacro: Expression | null, node: CallExpression) => boolean} isMacroNode
  1299. * @param {(context: RuleContext, node: CallExpression) => unknown} buildParam
  1300. */
  1301. constructor(name, enterName, exitName, isMacroNode, buildParam) {
  1302. this.name = name
  1303. this.enterName = enterName
  1304. this.exitName = exitName
  1305. this.isMacroNode = isMacroNode
  1306. this.buildParam = buildParam
  1307. this.hasListener = Boolean(
  1308. visitor[this.enterName] || visitor[this.exitName]
  1309. )
  1310. this.paramsMap = new Map()
  1311. }
  1312. }
  1313. const macroListenerList = [
  1314. new MacroListener(
  1315. 'defineProps',
  1316. 'onDefinePropsEnter',
  1317. 'onDefinePropsExit',
  1318. (candidateMacro, node) =>
  1319. candidateMacro === node || candidateMacro === getWithDefaults(node),
  1320. getComponentPropsFromDefineProps
  1321. ),
  1322. new MacroListener(
  1323. 'defineEmits',
  1324. 'onDefineEmitsEnter',
  1325. 'onDefineEmitsExit',
  1326. (candidateMacro, node) => candidateMacro === node,
  1327. getComponentEmitsFromDefineEmits
  1328. ),
  1329. new MacroListener(
  1330. 'defineOptions',
  1331. 'onDefineOptionsEnter',
  1332. 'onDefineOptionsExit',
  1333. (candidateMacro, node) => candidateMacro === node,
  1334. () => undefined
  1335. ),
  1336. new MacroListener(
  1337. 'defineSlots',
  1338. 'onDefineSlotsEnter',
  1339. 'onDefineSlotsExit',
  1340. (candidateMacro, node) => candidateMacro === node,
  1341. () => undefined
  1342. ),
  1343. new MacroListener(
  1344. 'defineExpose',
  1345. 'onDefineExposeEnter',
  1346. 'onDefineExposeExit',
  1347. (candidateMacro, node) => candidateMacro === node,
  1348. () => undefined
  1349. ),
  1350. new MacroListener(
  1351. 'defineModel',
  1352. 'onDefineModelEnter',
  1353. 'onDefineModelExit',
  1354. (candidateMacro, node) => candidateMacro === node,
  1355. getComponentModelFromDefineModel
  1356. )
  1357. ].filter((m) => m.hasListener)
  1358. if (macroListenerList.length > 0) {
  1359. /** @type {Expression | null} */
  1360. let candidateMacro = null
  1361. /** @param {VariableDeclarator|ExpressionStatement} node */
  1362. scriptSetupVisitor[
  1363. 'Program > VariableDeclaration > VariableDeclarator, Program > ExpressionStatement'
  1364. ] = (node) => {
  1365. if (!candidateMacro) {
  1366. candidateMacro =
  1367. node.type === 'VariableDeclarator' ? node.init : node.expression
  1368. }
  1369. }
  1370. /** @param {VariableDeclarator|ExpressionStatement} node */
  1371. scriptSetupVisitor[
  1372. 'Program > VariableDeclaration > VariableDeclarator, Program > ExpressionStatement:exit'
  1373. ] = (node) => {
  1374. if (
  1375. candidateMacro ===
  1376. (node.type === 'VariableDeclarator' ? node.init : node.expression)
  1377. ) {
  1378. candidateMacro = null
  1379. }
  1380. }
  1381. /**
  1382. * @param {CallExpression} node
  1383. */
  1384. scriptSetupVisitor.CallExpression = (node) => {
  1385. if (
  1386. candidateMacro &&
  1387. inScriptSetup(node) &&
  1388. node.callee.type === 'Identifier'
  1389. ) {
  1390. for (const macroListener of macroListenerList) {
  1391. if (
  1392. node.callee.name !== macroListener.name ||
  1393. !macroListener.isMacroNode(candidateMacro, node)
  1394. ) {
  1395. continue
  1396. }
  1397. const param = macroListener.buildParam(context, node)
  1398. callVisitor(macroListener.enterName, node, param)
  1399. macroListener.paramsMap.set(node, param)
  1400. break
  1401. }
  1402. }
  1403. callVisitor('CallExpression', node)
  1404. }
  1405. scriptSetupVisitor['CallExpression:exit'] = (node) => {
  1406. callVisitor('CallExpression:exit', node)
  1407. for (const macroListener of macroListenerList) {
  1408. if (macroListener.paramsMap.has(node)) {
  1409. callVisitor(
  1410. macroListener.exitName,
  1411. node,
  1412. macroListener.paramsMap.get(node)
  1413. )
  1414. macroListener.paramsMap.delete(node)
  1415. }
  1416. }
  1417. }
  1418. }
  1419. return scriptSetupVisitor
  1420. },
  1421. /**
  1422. * Checks whether given defineProps call node has withDefaults.
  1423. * @param {CallExpression} node The node of defineProps
  1424. * @returns {node is CallExpression & { parent: CallExpression }}
  1425. */
  1426. hasWithDefaults,
  1427. /**
  1428. * Gets a map of the expressions defined in withDefaults.
  1429. * @param {CallExpression} node The node of defineProps
  1430. * @returns { { [key: string]: Expression | undefined } }
  1431. */
  1432. getWithDefaultsPropExpressions(node) {
  1433. const map = getWithDefaultsProps(node)
  1434. /** @type {Record<string, Expression | undefined>} */
  1435. const result = {}
  1436. for (const key of Object.keys(map)) {
  1437. const prop = map[key]
  1438. result[key] = prop && prop.value
  1439. }
  1440. return result
  1441. },
  1442. /**
  1443. * Gets a map of the property nodes defined in withDefaults.
  1444. * @param {CallExpression} node The node of defineProps
  1445. * @returns { { [key: string]: Property | undefined } }
  1446. */
  1447. getWithDefaultsProps,
  1448. /**
  1449. * Gets the default definition nodes for defineProp
  1450. * using the props destructure with assignment pattern.
  1451. * @param {CallExpression} node The node of defineProps
  1452. * @returns { Record<string, {prop: AssignmentProperty , expression: Expression} | undefined> }
  1453. */
  1454. getDefaultPropExpressionsForPropsDestructure,
  1455. /**
  1456. * Checks whether the given defineProps node is using Props Destructure.
  1457. * @param {CallExpression} node The node of defineProps
  1458. * @returns {boolean}
  1459. */
  1460. isUsingPropsDestructure(node) {
  1461. const left = getLeftOfDefineProps(node)
  1462. return left?.type === 'ObjectPattern'
  1463. },
  1464. /**
  1465. * Gets the props destructure property nodes for defineProp.
  1466. * @param {CallExpression} node The node of defineProps
  1467. * @returns { Record<string, AssignmentProperty | undefined> }
  1468. */
  1469. getPropsDestructure,
  1470. getVueObjectType,
  1471. /**
  1472. * Get the Vue component definition type from given node
  1473. * Vue.component('xxx', {}) || component('xxx', {})
  1474. * @param {ObjectExpression} node Node to check
  1475. * @returns {'component' | 'mixin' | 'extend' | 'createApp' | 'defineComponent' | null}
  1476. */
  1477. getVueComponentDefinitionType,
  1478. /**
  1479. * Checks whether the given object is an SFC definition.
  1480. * @param {RuleContext} context The ESLint rule context object.
  1481. * @param {ObjectExpression} node Node to check
  1482. * @returns { boolean } `true`, the given object is an SFC definition.
  1483. */
  1484. isSFCObject,
  1485. compositingVisitors,
  1486. /**
  1487. * Check if current file is a Vue instance (new Vue) and call callback
  1488. * @param {RuleContext} context The ESLint rule context object.
  1489. * @param { (node: ObjectExpression, type: VueObjectType) => void } cb Callback function
  1490. */
  1491. executeOnVueInstance(context, cb) {
  1492. return {
  1493. /** @param {ObjectExpression} node */
  1494. 'ObjectExpression:exit'(node) {
  1495. const type = getVueObjectType(context, node)
  1496. if (!type || type !== 'instance') return
  1497. cb(node, type)
  1498. }
  1499. }
  1500. },
  1501. /**
  1502. * Check if current file is a Vue component and call callback
  1503. * @param {RuleContext} context The ESLint rule context object.
  1504. * @param { (node: ObjectExpression, type: VueObjectType) => void } cb Callback function
  1505. */
  1506. executeOnVueComponent(context, cb) {
  1507. return {
  1508. /** @param {ObjectExpression} node */
  1509. 'ObjectExpression:exit'(node) {
  1510. const type = getVueObjectType(context, node)
  1511. if (
  1512. !type ||
  1513. (type !== 'mark' && type !== 'export' && type !== 'definition')
  1514. )
  1515. return
  1516. cb(node, type)
  1517. }
  1518. }
  1519. },
  1520. /**
  1521. * Check call `Vue.component` and call callback.
  1522. * @param {RuleContext} _context The ESLint rule context object.
  1523. * @param { (node: CallExpression) => void } cb Callback function
  1524. */
  1525. executeOnCallVueComponent(_context, cb) {
  1526. return {
  1527. /** @param {Identifier & { parent: MemberExpression & { parent: CallExpression } } } node */
  1528. "CallExpression > MemberExpression > Identifier[name='component']": (
  1529. node
  1530. ) => {
  1531. const callExpr = node.parent.parent
  1532. const callee = callExpr.callee
  1533. if (callee.type === 'MemberExpression') {
  1534. const calleeObject = skipTSAsExpression(callee.object)
  1535. if (
  1536. calleeObject.type === 'Identifier' &&
  1537. // calleeObject.name === 'Vue' && // Any names can be used in Vue.js 3.x. e.g. app.component()
  1538. callee.property === node &&
  1539. callExpr.arguments.length > 0
  1540. ) {
  1541. cb(callExpr)
  1542. }
  1543. }
  1544. }
  1545. }
  1546. },
  1547. /**
  1548. * Return generator with all properties
  1549. * @param {ObjectExpression} node Node to check
  1550. * @param {Set<GroupName>} groups Name of parent group
  1551. * @returns {IterableIterator<ComponentPropertyData>}
  1552. */
  1553. *iterateProperties(node, groups) {
  1554. for (const item of node.properties) {
  1555. if (item.type !== 'Property') {
  1556. continue
  1557. }
  1558. const name = /** @type {GroupName | null} */ (getStaticPropertyName(item))
  1559. if (!name || !groups.has(name)) continue
  1560. switch (item.value.type) {
  1561. case 'ArrayExpression': {
  1562. yield* this.iterateArrayExpression(item.value, name)
  1563. break
  1564. }
  1565. case 'ObjectExpression': {
  1566. yield* this.iterateObjectExpression(item.value, name)
  1567. break
  1568. }
  1569. case 'FunctionExpression': {
  1570. yield* this.iterateFunctionExpression(item.value, name)
  1571. break
  1572. }
  1573. case 'ArrowFunctionExpression': {
  1574. yield* this.iterateArrowFunctionExpression(item.value, name)
  1575. break
  1576. }
  1577. }
  1578. }
  1579. },
  1580. /**
  1581. * Return generator with all elements inside ArrayExpression
  1582. * @param {ArrayExpression} node Node to check
  1583. * @param {GroupName} groupName Name of parent group
  1584. * @returns {IterableIterator<ComponentArrayPropertyData>}
  1585. */
  1586. *iterateArrayExpression(node, groupName) {
  1587. for (const item of node.elements) {
  1588. if (
  1589. item &&
  1590. (item.type === 'Literal' || item.type === 'TemplateLiteral')
  1591. ) {
  1592. const name = getStringLiteralValue(item)
  1593. if (name) {
  1594. yield { type: 'array', name, groupName, node: item }
  1595. }
  1596. }
  1597. }
  1598. },
  1599. /**
  1600. * Return generator with all elements inside ObjectExpression
  1601. * @param {ObjectExpression} node Node to check
  1602. * @param {GroupName} groupName Name of parent group
  1603. * @returns {IterableIterator<ComponentObjectPropertyData>}
  1604. */
  1605. *iterateObjectExpression(node, groupName) {
  1606. /** @type {Set<Property> | undefined} */
  1607. let usedGetter
  1608. for (const item of node.properties) {
  1609. if (item.type === 'Property') {
  1610. const key = item.key
  1611. if (
  1612. key.type === 'Identifier' ||
  1613. key.type === 'Literal' ||
  1614. key.type === 'TemplateLiteral'
  1615. ) {
  1616. const name = getStaticPropertyName(item)
  1617. if (name) {
  1618. // find getter pair
  1619. if (
  1620. item.kind === 'set' &&
  1621. node.properties.some((item2) => {
  1622. if (item2.type === 'Property' && item2.kind === 'get') {
  1623. if (!usedGetter) {
  1624. usedGetter = new Set()
  1625. }
  1626. if (usedGetter.has(item2)) {
  1627. return false
  1628. }
  1629. const getterName = getStaticPropertyName(item2)
  1630. if (getterName === name) {
  1631. usedGetter.add(item2)
  1632. return true
  1633. }
  1634. }
  1635. return false
  1636. })
  1637. ) {
  1638. // has getter pair
  1639. continue
  1640. }
  1641. yield {
  1642. type: 'object',
  1643. name,
  1644. groupName,
  1645. node: key,
  1646. property: item
  1647. }
  1648. }
  1649. }
  1650. }
  1651. }
  1652. },
  1653. /**
  1654. * Return generator with all elements inside FunctionExpression
  1655. * @param {FunctionExpression} node Node to check
  1656. * @param {GroupName} groupName Name of parent group
  1657. * @returns {IterableIterator<ComponentObjectPropertyData>}
  1658. */
  1659. *iterateFunctionExpression(node, groupName) {
  1660. if (node.body.type === 'BlockStatement') {
  1661. for (const item of node.body.body) {
  1662. if (
  1663. item.type === 'ReturnStatement' &&
  1664. item.argument &&
  1665. item.argument.type === 'ObjectExpression'
  1666. ) {
  1667. yield* this.iterateObjectExpression(item.argument, groupName)
  1668. }
  1669. }
  1670. }
  1671. },
  1672. /**
  1673. * Return generator with all elements inside ArrowFunctionExpression
  1674. * @param {ArrowFunctionExpression} node Node to check
  1675. * @param {GroupName} groupName Name of parent group
  1676. * @returns {IterableIterator<ComponentObjectPropertyData>}
  1677. */
  1678. *iterateArrowFunctionExpression(node, groupName) {
  1679. const body = node.body
  1680. if (body.type === 'BlockStatement') {
  1681. for (const item of body.body) {
  1682. if (
  1683. item.type === 'ReturnStatement' &&
  1684. item.argument &&
  1685. item.argument.type === 'ObjectExpression'
  1686. ) {
  1687. yield* this.iterateObjectExpression(item.argument, groupName)
  1688. }
  1689. }
  1690. } else if (body.type === 'ObjectExpression') {
  1691. yield* this.iterateObjectExpression(body, groupName)
  1692. }
  1693. },
  1694. /**
  1695. * Find all functions which do not always return values
  1696. * @param {boolean} treatUndefinedAsUnspecified
  1697. * @param { (node: ArrowFunctionExpression | FunctionExpression | FunctionDeclaration) => void } cb Callback function
  1698. * @returns {RuleListener}
  1699. */
  1700. executeOnFunctionsWithoutReturn(treatUndefinedAsUnspecified, cb) {
  1701. /**
  1702. * @typedef {object} FuncInfo
  1703. * @property {FuncInfo | null} funcInfo
  1704. * @property {CodePath} codePath
  1705. * @property {boolean} hasReturn
  1706. * @property {boolean} hasReturnValue
  1707. * @property {ArrowFunctionExpression | FunctionExpression | FunctionDeclaration} node
  1708. * @property {CodePathSegment[]} currentSegments
  1709. */
  1710. /** @type {FuncInfo | null} */
  1711. let funcInfo = null
  1712. function isValidReturn() {
  1713. if (!funcInfo) {
  1714. return true
  1715. }
  1716. if (funcInfo.currentSegments.some((segment) => segment.reachable)) {
  1717. return false
  1718. }
  1719. return !treatUndefinedAsUnspecified || funcInfo.hasReturnValue
  1720. }
  1721. return {
  1722. /**
  1723. * @param {CodePath} codePath
  1724. * @param {ESNode} node
  1725. */
  1726. onCodePathStart(codePath, node) {
  1727. if (
  1728. node.type === 'ArrowFunctionExpression' ||
  1729. node.type === 'FunctionExpression' ||
  1730. node.type === 'FunctionDeclaration'
  1731. ) {
  1732. funcInfo = {
  1733. codePath,
  1734. currentSegments: [],
  1735. funcInfo,
  1736. hasReturn: false,
  1737. hasReturnValue: false,
  1738. node
  1739. }
  1740. }
  1741. },
  1742. onCodePathSegmentStart(segment) {
  1743. funcInfo?.currentSegments.push(segment)
  1744. },
  1745. onCodePathSegmentEnd() {
  1746. funcInfo?.currentSegments.pop()
  1747. },
  1748. onCodePathEnd() {
  1749. funcInfo = funcInfo && funcInfo.funcInfo
  1750. },
  1751. /** @param {ReturnStatement} node */
  1752. ReturnStatement(node) {
  1753. if (funcInfo) {
  1754. funcInfo.hasReturn = true
  1755. funcInfo.hasReturnValue = Boolean(node.argument)
  1756. }
  1757. },
  1758. /** @param {ArrowFunctionExpression} node */
  1759. 'ArrowFunctionExpression:exit'(node) {
  1760. if (funcInfo && !isValidReturn() && !node.expression) {
  1761. cb(funcInfo.node)
  1762. }
  1763. },
  1764. 'FunctionExpression:exit'() {
  1765. if (funcInfo && !isValidReturn()) {
  1766. cb(funcInfo.node)
  1767. }
  1768. }
  1769. }
  1770. },
  1771. /**
  1772. * Check whether the component is declared in a single line or not.
  1773. * @param {ASTNode} node
  1774. * @returns {boolean}
  1775. */
  1776. isSingleLine(node) {
  1777. return node.loc.start.line === node.loc.end.line
  1778. },
  1779. /**
  1780. * Check whether the templateBody of the program has invalid EOF or not.
  1781. * @param {Program} node The program node to check.
  1782. * @returns {boolean} `true` if it has invalid EOF.
  1783. */
  1784. hasInvalidEOF(node) {
  1785. const body = node.templateBody
  1786. if (body == null || body.errors == null) {
  1787. return false
  1788. }
  1789. return body.errors.some(
  1790. (error) => typeof error.code === 'string' && error.code.startsWith('eof-')
  1791. )
  1792. },
  1793. /**
  1794. * Get the chaining nodes of MemberExpression.
  1795. *
  1796. * @param {ESNode} node The node to parse
  1797. * @return {[ESNode, ...MemberExpression[]]} The chaining nodes
  1798. */
  1799. getMemberChaining(node) {
  1800. /** @type {MemberExpression[]} */
  1801. const nodes = []
  1802. let n = skipChainExpression(node)
  1803. while (n.type === 'MemberExpression') {
  1804. nodes.push(n)
  1805. n = skipChainExpression(n.object)
  1806. }
  1807. return [n, ...nodes.reverse()]
  1808. },
  1809. /**
  1810. * return two string editdistance
  1811. * @param {string} a string a to compare
  1812. * @param {string} b string b to compare
  1813. * @returns {number}
  1814. */
  1815. editDistance(a, b) {
  1816. if (a === b) {
  1817. return 0
  1818. }
  1819. const alen = a.length
  1820. const blen = b.length
  1821. const dp = Array.from({ length: alen + 1 }).map((_) =>
  1822. Array.from({ length: blen + 1 }).fill(0)
  1823. )
  1824. for (let i = 0; i <= alen; i++) {
  1825. dp[i][0] = i
  1826. }
  1827. for (let j = 0; j <= blen; j++) {
  1828. dp[0][j] = j
  1829. }
  1830. for (let i = 1; i <= alen; i++) {
  1831. for (let j = 1; j <= blen; j++) {
  1832. dp[i][j] =
  1833. a[i - 1] === b[j - 1]
  1834. ? dp[i - 1][j - 1]
  1835. : Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1
  1836. }
  1837. }
  1838. return dp[alen][blen]
  1839. },
  1840. /**
  1841. * Checks whether the target node is within the given range.
  1842. * @param { [number, number] } range
  1843. * @param {ASTNode | Token} target
  1844. */
  1845. inRange(range, target) {
  1846. return range[0] <= target.range[0] && target.range[1] <= range[1]
  1847. },
  1848. /**
  1849. * Checks whether the given node is Property.
  1850. */
  1851. isProperty,
  1852. /**
  1853. * Checks whether the given node is AssignmentProperty.
  1854. */
  1855. isAssignmentProperty,
  1856. /**
  1857. * Checks whether the given node is VElement.
  1858. */
  1859. isVElement,
  1860. /**
  1861. * Finds the property with the given name from the given ObjectExpression node.
  1862. */
  1863. findProperty,
  1864. /**
  1865. * Finds the assignment property with the given name from the given ObjectPattern node.
  1866. */
  1867. findAssignmentProperty,
  1868. /**
  1869. * Checks if the given node is a property value.
  1870. * @param {Property} prop
  1871. * @param {Expression} node
  1872. */
  1873. isPropertyChain,
  1874. /**
  1875. * Retrieve `TSAsExpression#expression` value if the given node a `TSAsExpression` node. Otherwise, pass through it.
  1876. */
  1877. skipTSAsExpression,
  1878. /**
  1879. * Retrieve `AssignmentPattern#left` value if the given node a `AssignmentPattern` node. Otherwise, pass through it.
  1880. */
  1881. skipDefaultParamValue,
  1882. /**
  1883. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  1884. */
  1885. skipChainExpression,
  1886. /**
  1887. * Checks whether the given node is in a type annotation.
  1888. */
  1889. withinTypeNode,
  1890. findVariableByIdentifier,
  1891. getScope,
  1892. /**
  1893. * Marks a variable with the given name in the current scope as used. This affects the no-unused-vars rule.
  1894. */
  1895. markVariableAsUsed,
  1896. /**
  1897. * Checks whether the given node is in export default.
  1898. * @param {ASTNode} node
  1899. * @returns {boolean}
  1900. */
  1901. isInExportDefault,
  1902. /**
  1903. * Check whether the given node is `this` or variable that stores `this`.
  1904. * @param {ESNode} node The node to check
  1905. * @param {RuleContext} context The rule context to use parser services.
  1906. * @returns {boolean} `true` if the given node is `this`.
  1907. */
  1908. isThis(node, context) {
  1909. if (node.type === 'ThisExpression') {
  1910. return true
  1911. }
  1912. if (node.type !== 'Identifier') {
  1913. return false
  1914. }
  1915. const parent = node.parent
  1916. if (
  1917. (parent.type === 'MemberExpression' && parent.property === node) ||
  1918. (parent.type === 'Property' && parent.key === node && !parent.computed)
  1919. ) {
  1920. return false
  1921. }
  1922. const variable = findVariable(getScope(context, node), node)
  1923. if (variable != null && variable.defs.length === 1) {
  1924. const def = variable.defs[0]
  1925. if (
  1926. def.type === 'Variable' &&
  1927. def.parent.kind === 'const' &&
  1928. def.node.id.type === 'Identifier'
  1929. ) {
  1930. return Boolean(
  1931. def.node && def.node.init && def.node.init.type === 'ThisExpression'
  1932. )
  1933. }
  1934. }
  1935. return false
  1936. },
  1937. /**
  1938. * @param {MemberExpression|Identifier} props
  1939. * @returns { { kind: 'assignment' | 'update' | 'call' , node: ESNode, pathNodes: MemberExpression[] } | null }
  1940. */
  1941. findMutating(props) {
  1942. /** @type {MemberExpression[]} */
  1943. const pathNodes = []
  1944. /** @type {MemberExpression | Identifier | ChainExpression} */
  1945. let node = props
  1946. let target = node.parent
  1947. while (true) {
  1948. switch (target.type) {
  1949. case 'AssignmentExpression': {
  1950. if (target.left === node) {
  1951. // this.xxx <=|+=|-=>
  1952. return {
  1953. kind: 'assignment',
  1954. node: target,
  1955. pathNodes
  1956. }
  1957. }
  1958. break
  1959. }
  1960. case 'UpdateExpression': {
  1961. // this.xxx <++|-->
  1962. return {
  1963. kind: 'update',
  1964. node: target,
  1965. pathNodes
  1966. }
  1967. }
  1968. case 'UnaryExpression': {
  1969. if (target.operator === 'delete') {
  1970. return {
  1971. kind: 'update',
  1972. node: target,
  1973. pathNodes
  1974. }
  1975. }
  1976. break
  1977. }
  1978. case 'CallExpression': {
  1979. if (pathNodes.length > 0 && target.callee === node) {
  1980. const mem = pathNodes[pathNodes.length - 1]
  1981. const callName = getStaticPropertyName(mem)
  1982. if (
  1983. callName &&
  1984. /^(?:push|pop|shift|unshift|reverse|splice|sort|copyWithin|fill)$/u.test(
  1985. callName
  1986. )
  1987. ) {
  1988. // this.xxx.push()
  1989. pathNodes.pop()
  1990. return {
  1991. kind: 'call',
  1992. node: target,
  1993. pathNodes
  1994. }
  1995. }
  1996. }
  1997. break
  1998. }
  1999. case 'MemberExpression': {
  2000. if (target.object === node) {
  2001. pathNodes.push(target)
  2002. node = target
  2003. target = target.parent
  2004. continue // loop
  2005. }
  2006. break
  2007. }
  2008. case 'ChainExpression': {
  2009. node = target
  2010. target = target.parent
  2011. continue // loop
  2012. }
  2013. }
  2014. return null
  2015. }
  2016. },
  2017. /**
  2018. * Return generator with the all handler nodes defined in the given watcher property.
  2019. * @param {Property|Expression} property
  2020. * @returns {IterableIterator<Expression>}
  2021. */
  2022. iterateWatchHandlerValues,
  2023. /**
  2024. * Wraps composition API trace map in both 'vue' and '@vue/composition-api' imports, or '#imports' from unimport
  2025. * @param {import('@eslint-community/eslint-utils').TYPES.TraceMap} map
  2026. */
  2027. createCompositionApiTraceMap: (map) => ({
  2028. vue: map,
  2029. '@vue/composition-api': map,
  2030. '#imports': map
  2031. }),
  2032. /**
  2033. * Iterates all references in the given trace map.
  2034. * Take the third argument option to detect auto-imported references.
  2035. *
  2036. * @param {import('@eslint-community/eslint-utils').ReferenceTracker} tracker
  2037. * @param {import('@eslint-community/eslint-utils').TYPES.TraceMap} map
  2038. * @returns {ReturnType<import('@eslint-community/eslint-utils').ReferenceTracker['iterateEsmReferences']>}
  2039. */
  2040. *iterateReferencesTraceMap(tracker, map) {
  2041. const esmTraceMap = this.createCompositionApiTraceMap({
  2042. ...map,
  2043. [ReferenceTracker.ESM]: true
  2044. })
  2045. for (const ref of tracker.iterateEsmReferences(esmTraceMap)) {
  2046. yield ref
  2047. }
  2048. for (const ref of tracker.iterateGlobalReferences(map)) {
  2049. yield ref
  2050. }
  2051. },
  2052. /**
  2053. * Checks whether or not the tokens of two given nodes are same.
  2054. * @param {ASTNode} left A node 1 to compare.
  2055. * @param {ASTNode} right A node 2 to compare.
  2056. * @param {ParserServices.TokenStore | SourceCode} sourceCode The ESLint source code object.
  2057. * @returns {boolean} the source code for the given node.
  2058. */
  2059. equalTokens(left, right, sourceCode) {
  2060. const tokensL = sourceCode.getTokens(left)
  2061. const tokensR = sourceCode.getTokens(right)
  2062. if (tokensL.length !== tokensR.length) {
  2063. return false
  2064. }
  2065. return tokensL.every(
  2066. (token, i) =>
  2067. token.type === tokensR[i].type && token.value === tokensR[i].value
  2068. )
  2069. }
  2070. }
  2071. // ------------------------------------------------------------------------------
  2072. // Standard Helpers
  2073. // ------------------------------------------------------------------------------
  2074. /**
  2075. * Checks whether the given value is defined.
  2076. * @template T
  2077. * @param {T | null | undefined} v
  2078. * @returns {v is T}
  2079. */
  2080. function isDef(v) {
  2081. return v != null
  2082. }
  2083. /**
  2084. * Flattens arrays, objects and iterable objects.
  2085. * @template T
  2086. * @param {T | Iterable<T> | null | undefined} v
  2087. * @returns {T[]}
  2088. */
  2089. function flatten(v) {
  2090. /** @type {T[]} */
  2091. const result = []
  2092. if (v) {
  2093. if (isIterable(v)) {
  2094. result.push(...v)
  2095. } else {
  2096. result.push(v)
  2097. }
  2098. }
  2099. return result
  2100. }
  2101. /**
  2102. * @param {*} v
  2103. * @returns {v is Iterable<any>}
  2104. */
  2105. function isIterable(v) {
  2106. return v && Symbol.iterator in v
  2107. }
  2108. // ------------------------------------------------------------------------------
  2109. // Nodejs Helpers
  2110. // ------------------------------------------------------------------------------
  2111. /**
  2112. * @param {String} filename
  2113. */
  2114. function createRequire(filename) {
  2115. const Module = require('module')
  2116. const moduleCreateRequire =
  2117. // Added in v12.2.0
  2118. Module.createRequire ||
  2119. // Added in v10.12.0, but deprecated in v12.2.0.
  2120. Module.createRequireFromPath ||
  2121. // Polyfill - This is not executed on the tests on node@>=10.
  2122. /**
  2123. * @param {string} filename
  2124. */
  2125. function (filename) {
  2126. const mod = new Module(filename)
  2127. mod.filename = filename
  2128. // @ts-ignore
  2129. mod.paths = Module._nodeModulePaths(path.dirname(filename))
  2130. // @ts-ignore
  2131. mod._compile('module.exports = require;', filename)
  2132. return mod.exports
  2133. }
  2134. return moduleCreateRequire(filename)
  2135. }
  2136. // ------------------------------------------------------------------------------
  2137. // Rule Helpers
  2138. // ------------------------------------------------------------------------------
  2139. /**
  2140. * Register the given visitor to parser services.
  2141. * If the parser service of `vue-eslint-parser` was not found,
  2142. * this generates a warning.
  2143. *
  2144. * @param {RuleContext} context The rule context to use parser services.
  2145. * @param {TemplateListener} templateBodyVisitor The visitor to traverse the template body.
  2146. * @param {RuleListener} [scriptVisitor] The visitor to traverse the script.
  2147. * @param { { templateBodyTriggerSelector: "Program" | "Program:exit" } } [options] The options.
  2148. * @returns {RuleListener} The merged visitor.
  2149. */
  2150. function defineTemplateBodyVisitor(
  2151. context,
  2152. templateBodyVisitor,
  2153. scriptVisitor,
  2154. options
  2155. ) {
  2156. const sourceCode = context.getSourceCode()
  2157. if (sourceCode.parserServices.defineTemplateBodyVisitor == null) {
  2158. const filename = context.getFilename()
  2159. if (path.extname(filename) === '.vue') {
  2160. context.report({
  2161. loc: { line: 1, column: 0 },
  2162. message:
  2163. 'Use the latest vue-eslint-parser. See also https://eslint.vuejs.org/user-guide/#what-is-the-use-the-latest-vue-eslint-parser-error.'
  2164. })
  2165. }
  2166. return {}
  2167. }
  2168. return sourceCode.parserServices.defineTemplateBodyVisitor(
  2169. templateBodyVisitor,
  2170. scriptVisitor,
  2171. options
  2172. )
  2173. }
  2174. /**
  2175. * Register the given visitor to parser services.
  2176. * If the parser service of `vue-eslint-parser` was not found,
  2177. * this generates a warning.
  2178. *
  2179. * @param {RuleContext} context The rule context to use parser services.
  2180. * @param {TemplateListener} documentVisitor The visitor to traverse the document.
  2181. * @param { { triggerSelector: "Program" | "Program:exit" } } [options] The options.
  2182. * @returns {RuleListener} The merged visitor.
  2183. */
  2184. function defineDocumentVisitor(context, documentVisitor, options) {
  2185. const sourceCode = context.getSourceCode()
  2186. if (sourceCode.parserServices.defineDocumentVisitor == null) {
  2187. const filename = context.getFilename()
  2188. if (path.extname(filename) === '.vue') {
  2189. context.report({
  2190. loc: { line: 1, column: 0 },
  2191. message:
  2192. 'Use the latest vue-eslint-parser. See also https://eslint.vuejs.org/user-guide/#what-is-the-use-the-latest-vue-eslint-parser-error.'
  2193. })
  2194. }
  2195. return {}
  2196. }
  2197. return sourceCode.parserServices.defineDocumentVisitor(
  2198. documentVisitor,
  2199. options
  2200. )
  2201. }
  2202. /**
  2203. * @template T
  2204. * @param {T} visitor
  2205. * @param {...(TemplateListener | RuleListener | NodeListener)} visitors
  2206. * @returns {T}
  2207. */
  2208. function compositingVisitors(visitor, ...visitors) {
  2209. for (const v of visitors) {
  2210. for (const key in v) {
  2211. // @ts-expect-error
  2212. if (visitor[key]) {
  2213. // @ts-expect-error
  2214. const o = visitor[key]
  2215. // @ts-expect-error
  2216. visitor[key] = (...args) => {
  2217. o(...args)
  2218. // @ts-expect-error
  2219. v[key](...args)
  2220. }
  2221. } else {
  2222. // @ts-expect-error
  2223. visitor[key] = v[key]
  2224. }
  2225. }
  2226. }
  2227. return visitor
  2228. }
  2229. // ------------------------------------------------------------------------------
  2230. // AST Helpers
  2231. // ------------------------------------------------------------------------------
  2232. /**
  2233. * Find the variable of a given identifier.
  2234. * @param {RuleContext} context The rule context
  2235. * @param {Identifier} node The variable name to find.
  2236. * @returns {Variable|null} The found variable or null.
  2237. */
  2238. function findVariableByIdentifier(context, node) {
  2239. return findVariable(getScope(context, node), node)
  2240. }
  2241. /**
  2242. * Finds the property with the given name from the given ObjectExpression node.
  2243. * @param {ObjectExpression} node
  2244. * @param {string} name
  2245. * @param { (p: Property) => boolean } [filter]
  2246. * @returns { (Property) | null}
  2247. */
  2248. function findProperty(node, name, filter) {
  2249. const predicate = filter
  2250. ? /**
  2251. * @param {Property | SpreadElement} prop
  2252. * @returns {prop is Property}
  2253. */
  2254. (prop) =>
  2255. isProperty(prop) && getStaticPropertyName(prop) === name && filter(prop)
  2256. : /**
  2257. * @param {Property | SpreadElement} prop
  2258. * @returns {prop is Property}
  2259. */
  2260. (prop) => isProperty(prop) && getStaticPropertyName(prop) === name
  2261. return node.properties.find(predicate) || null
  2262. }
  2263. /**
  2264. * Finds the assignment property with the given name from the given ObjectPattern node.
  2265. * @param {ObjectPattern} node
  2266. * @param {string} name
  2267. * @param { (p: AssignmentProperty) => boolean } [filter]
  2268. * @returns { (AssignmentProperty) | null}
  2269. */
  2270. function findAssignmentProperty(node, name, filter) {
  2271. const predicate = filter
  2272. ? /**
  2273. * @param {AssignmentProperty | RestElement} prop
  2274. * @returns {prop is AssignmentProperty}
  2275. */
  2276. (prop) =>
  2277. isAssignmentProperty(prop) &&
  2278. getStaticPropertyName(prop) === name &&
  2279. filter(prop)
  2280. : /**
  2281. * @param {AssignmentProperty | RestElement} prop
  2282. * @returns {prop is AssignmentProperty}
  2283. */
  2284. (prop) =>
  2285. isAssignmentProperty(prop) && getStaticPropertyName(prop) === name
  2286. return node.properties.find(predicate) || null
  2287. }
  2288. /**
  2289. * Checks whether the given node is Property.
  2290. * @param {Property | SpreadElement | AssignmentProperty} node
  2291. * @returns {node is Property}
  2292. */
  2293. function isProperty(node) {
  2294. if (node.type !== 'Property') {
  2295. return false
  2296. }
  2297. return !node.parent || node.parent.type === 'ObjectExpression'
  2298. }
  2299. /**
  2300. * Checks whether the given node is AssignmentProperty.
  2301. * @param {AssignmentProperty | RestElement} node
  2302. * @returns {node is AssignmentProperty}
  2303. */
  2304. function isAssignmentProperty(node) {
  2305. return node.type === 'Property'
  2306. }
  2307. /**
  2308. * Checks whether the given node is VElement.
  2309. * @param {VElement | VExpressionContainer | VText} node
  2310. * @returns {node is VElement}
  2311. */
  2312. function isVElement(node) {
  2313. return node.type === 'VElement'
  2314. }
  2315. /**
  2316. * Checks whether the given node is in export default.
  2317. * @param {ASTNode} node
  2318. * @returns {boolean}
  2319. */
  2320. function isInExportDefault(node) {
  2321. /** @type {ASTNode | null} */
  2322. let parent = node.parent
  2323. while (parent) {
  2324. if (parent.type === 'ExportDefaultDeclaration') {
  2325. return true
  2326. }
  2327. parent = parent.parent
  2328. }
  2329. return false
  2330. }
  2331. /**
  2332. * Retrieve `TSAsExpression#expression` value if the given node a `TSAsExpression` node. Otherwise, pass through it.
  2333. * @template T Node type
  2334. * @param {T | TSAsExpression} node The node to address.
  2335. * @returns {T} The `TSAsExpression#expression` value if the node is a `TSAsExpression` node. Otherwise, the node.
  2336. */
  2337. function skipTSAsExpression(node) {
  2338. if (!node) {
  2339. return node
  2340. }
  2341. // @ts-expect-error
  2342. if (node.type === 'TSAsExpression') {
  2343. // @ts-expect-error
  2344. return skipTSAsExpression(node.expression)
  2345. }
  2346. // @ts-expect-error
  2347. return node
  2348. }
  2349. /**
  2350. * Gets the parent node of the given node. This method returns a value ignoring `X as F`.
  2351. * @param {Expression} node
  2352. * @returns {ASTNode}
  2353. */
  2354. function getParent(node) {
  2355. let parent = node.parent
  2356. while (parent.type === 'TSAsExpression') {
  2357. parent = parent.parent
  2358. }
  2359. return parent
  2360. }
  2361. /**
  2362. * Checks if the given node is a property value.
  2363. * @param {Property} prop
  2364. * @param {Expression} node
  2365. */
  2366. function isPropertyChain(prop, node) {
  2367. let value = node
  2368. while (value.parent.type === 'TSAsExpression') {
  2369. value = value.parent
  2370. }
  2371. return prop === value.parent && prop.value === value
  2372. }
  2373. /**
  2374. * Retrieve `AssignmentPattern#left` value if the given node a `AssignmentPattern` node. Otherwise, pass through it.
  2375. * @template T Node type
  2376. * @param {T | AssignmentPattern} node The node to address.
  2377. * @return {T} The `AssignmentPattern#left` value if the node is a `AssignmentPattern` node. Otherwise, the node.
  2378. */
  2379. function skipDefaultParamValue(node) {
  2380. if (!node) {
  2381. return node
  2382. }
  2383. // @ts-expect-error
  2384. if (node.type === 'AssignmentPattern') {
  2385. // @ts-expect-error
  2386. return skipDefaultParamValue(node.left)
  2387. }
  2388. // @ts-expect-error
  2389. return node
  2390. }
  2391. /**
  2392. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  2393. * @template T Node type
  2394. * @param {T | ChainExpression} node The node to address.
  2395. * @returns {T} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node.
  2396. */
  2397. function skipChainExpression(node) {
  2398. if (!node) {
  2399. return node
  2400. }
  2401. // @ts-expect-error
  2402. if (node.type === 'ChainExpression') {
  2403. // @ts-expect-error
  2404. return skipChainExpression(node.expression)
  2405. }
  2406. // @ts-expect-error
  2407. return node
  2408. }
  2409. /**
  2410. * Checks whether the given node is in a type annotation.
  2411. * @param {ESNode} node
  2412. * @returns {boolean}
  2413. */
  2414. function withinTypeNode(node) {
  2415. /** @type {ASTNode | null} */
  2416. let target = node
  2417. while (target) {
  2418. if (isTypeNode(target)) {
  2419. return true
  2420. }
  2421. target = target.parent
  2422. }
  2423. return false
  2424. }
  2425. /**
  2426. * Gets the property name of a given node.
  2427. * @param {Property|AssignmentProperty|MethodDefinition|MemberExpression} node - The node to get.
  2428. * @return {string|null} The property name if static. Otherwise, null.
  2429. */
  2430. function getStaticPropertyName(node) {
  2431. if (node.type === 'Property' || node.type === 'MethodDefinition') {
  2432. if (!node.computed) {
  2433. const key = node.key
  2434. if (key.type === 'Identifier') {
  2435. return key.name
  2436. }
  2437. }
  2438. const key = node.key
  2439. // @ts-expect-error
  2440. return getStringLiteralValue(key)
  2441. } else if (node.type === 'MemberExpression') {
  2442. if (!node.computed) {
  2443. const property = node.property
  2444. if (property.type === 'Identifier') {
  2445. return property.name
  2446. }
  2447. return null
  2448. }
  2449. const property = node.property
  2450. // @ts-expect-error
  2451. return getStringLiteralValue(property)
  2452. }
  2453. return null
  2454. }
  2455. /**
  2456. * Gets the string of a given node.
  2457. * @param {Literal|TemplateLiteral} node - The node to get.
  2458. * @param {boolean} [stringOnly]
  2459. * @return {string|null} The string if static. Otherwise, null.
  2460. */
  2461. function getStringLiteralValue(node, stringOnly) {
  2462. if (node.type === 'Literal') {
  2463. if (node.value == null) {
  2464. if (!stringOnly && node.bigint != null) {
  2465. return node.bigint
  2466. }
  2467. return null
  2468. }
  2469. if (typeof node.value === 'string') {
  2470. return node.value
  2471. }
  2472. if (!stringOnly) {
  2473. return String(node.value)
  2474. }
  2475. return null
  2476. }
  2477. if (
  2478. node.type === 'TemplateLiteral' &&
  2479. node.expressions.length === 0 &&
  2480. node.quasis.length === 1
  2481. ) {
  2482. return node.quasis[0].value.cooked
  2483. }
  2484. return null
  2485. }
  2486. /**
  2487. * Gets the VExpressionContainer of a given node.
  2488. * @param {ASTNode} node - The node to get.
  2489. * @return {VExpressionContainer|null}
  2490. */
  2491. function getVExpressionContainer(node) {
  2492. /** @type {ASTNode | null} */
  2493. let n = node
  2494. while (n && n.type !== 'VExpressionContainer') {
  2495. n = n.parent
  2496. }
  2497. return n
  2498. }
  2499. /**
  2500. * @param {string} path
  2501. */
  2502. function isTypeScriptFile(path) {
  2503. return path.endsWith('.ts') || path.endsWith('.tsx') || path.endsWith('.mts')
  2504. }
  2505. // ------------------------------------------------------------------------------
  2506. // ESLint Helpers
  2507. // ------------------------------------------------------------------------------
  2508. /**
  2509. * Marks a variable with the given name in the current scope as used. This affects the no-unused-vars rule.
  2510. * @param {RuleContext} context
  2511. * @param {string} name
  2512. * @param {ASTNode} node The node to get the current scope.
  2513. */
  2514. function markVariableAsUsed(context, name, node) {
  2515. const sourceCode = context.getSourceCode()
  2516. if (sourceCode.markVariableAsUsed) {
  2517. sourceCode.markVariableAsUsed(name, node)
  2518. } else {
  2519. // This function does not use the given node, but the currently visited node.
  2520. // If we need to determine the scope of a given node, we need to implement it yourself.
  2521. context.markVariableAsUsed?.(name)
  2522. }
  2523. }
  2524. // ------------------------------------------------------------------------------
  2525. // Vue Helpers
  2526. // ------------------------------------------------------------------------------
  2527. /**
  2528. * @param {string} path
  2529. */
  2530. function isVueFile(path) {
  2531. return path.endsWith('.vue') || path.endsWith('.jsx') || path.endsWith('.tsx')
  2532. }
  2533. /**
  2534. * Checks whether the current file is uses `<script setup>`
  2535. * @param {RuleContext} context The ESLint rule context object.
  2536. */
  2537. function isScriptSetup(context) {
  2538. return Boolean(getScriptSetupElement(context))
  2539. }
  2540. /**
  2541. * Gets the element of `<script setup>`
  2542. * @param {RuleContext} context The ESLint rule context object.
  2543. * @returns {VElement | null} the element of `<script setup>`
  2544. */
  2545. function getScriptSetupElement(context) {
  2546. const sourceCode = context.getSourceCode()
  2547. const df =
  2548. sourceCode.parserServices.getDocumentFragment &&
  2549. sourceCode.parserServices.getDocumentFragment()
  2550. if (!df) {
  2551. return null
  2552. }
  2553. const scripts = df.children.filter(
  2554. /** @returns {e is VElement} */
  2555. (e) => isVElement(e) && e.name === 'script'
  2556. )
  2557. if (scripts.length === 2) {
  2558. return scripts.find((e) => hasAttribute(e, 'setup')) || null
  2559. } else {
  2560. const script = scripts[0]
  2561. if (script && hasAttribute(script, 'setup')) {
  2562. return script
  2563. }
  2564. }
  2565. return null
  2566. }
  2567. /**
  2568. * Check whether the given node is a Vue component based
  2569. * on the filename and default export type
  2570. * export default {} in .vue || .jsx
  2571. * @param {ESNode} node Node to check
  2572. * @param {string} path File name with extension
  2573. * @returns {boolean}
  2574. */
  2575. function isVueComponentFile(node, path) {
  2576. return (
  2577. isVueFile(path) &&
  2578. node.type === 'ExportDefaultDeclaration' &&
  2579. node.declaration.type === 'ObjectExpression'
  2580. )
  2581. }
  2582. /**
  2583. * Get the Vue component definition type from given node
  2584. * Vue.component('xxx', {}) || component('xxx', {})
  2585. * @param {ObjectExpression} node Node to check
  2586. * @returns {'component' | 'mixin' | 'extend' | 'createApp' | 'defineComponent' | null}
  2587. */
  2588. function getVueComponentDefinitionType(node) {
  2589. const parent = getParent(node)
  2590. if (parent.type === 'CallExpression') {
  2591. const callee = parent.callee
  2592. if (callee.type === 'MemberExpression') {
  2593. const calleeObject = skipTSAsExpression(callee.object)
  2594. if (calleeObject.type === 'Identifier') {
  2595. const propName = getStaticPropertyName(callee)
  2596. if (calleeObject.name === 'Vue') {
  2597. // for Vue.js 2.x
  2598. // Vue.component('xxx', {}) || Vue.mixin({}) || Vue.extend('xxx', {})
  2599. const maybeFullVueComponentForVue2 =
  2600. propName && isObjectArgument(parent)
  2601. return maybeFullVueComponentForVue2 &&
  2602. (propName === 'component' ||
  2603. propName === 'mixin' ||
  2604. propName === 'extend')
  2605. ? propName
  2606. : null
  2607. }
  2608. // for Vue.js 3.x
  2609. // app.component('xxx', {}) || app.mixin({})
  2610. const maybeFullVueComponent = propName && isObjectArgument(parent)
  2611. return maybeFullVueComponent &&
  2612. (propName === 'component' || propName === 'mixin')
  2613. ? propName
  2614. : null
  2615. }
  2616. }
  2617. if (callee.type === 'Identifier') {
  2618. if (callee.name === 'component') {
  2619. // for Vue.js 2.x
  2620. // component('xxx', {})
  2621. const isDestructedVueComponent = isObjectArgument(parent)
  2622. return isDestructedVueComponent ? 'component' : null
  2623. }
  2624. if (callee.name === 'createApp') {
  2625. // for Vue.js 3.x
  2626. // createApp({})
  2627. const isAppVueComponent = isObjectArgument(parent)
  2628. return isAppVueComponent ? 'createApp' : null
  2629. }
  2630. if (callee.name === 'defineComponent') {
  2631. // for Vue.js 3.x
  2632. // defineComponent({})
  2633. const isDestructedVueComponent = isObjectArgument(parent)
  2634. return isDestructedVueComponent ? 'defineComponent' : null
  2635. }
  2636. }
  2637. }
  2638. return null
  2639. }
  2640. /** @param {CallExpression} node */
  2641. function isObjectArgument(node) {
  2642. return (
  2643. node.arguments.length > 0 &&
  2644. skipTSAsExpression(node.arguments.slice(-1)[0]).type === 'ObjectExpression'
  2645. )
  2646. }
  2647. /**
  2648. * Check whether given node is new Vue instance
  2649. * new Vue({})
  2650. * @param {NewExpression} node Node to check
  2651. * @returns {boolean}
  2652. */
  2653. function isVueInstance(node) {
  2654. const callee = node.callee
  2655. return Boolean(
  2656. node.type === 'NewExpression' &&
  2657. callee.type === 'Identifier' &&
  2658. callee.name === 'Vue' &&
  2659. node.arguments.length > 0 &&
  2660. skipTSAsExpression(node.arguments[0]).type === 'ObjectExpression'
  2661. )
  2662. }
  2663. /**
  2664. * If the given object is a Vue component or instance, returns the Vue definition type.
  2665. * @param {RuleContext} context The ESLint rule context object.
  2666. * @param {ObjectExpression} node Node to check
  2667. * @returns { VueObjectType | null } The Vue definition type.
  2668. */
  2669. function getVueObjectType(context, node) {
  2670. if (node.type !== 'ObjectExpression') {
  2671. return null
  2672. }
  2673. const parent = getParent(node)
  2674. switch (parent.type) {
  2675. case 'ExportDefaultDeclaration': {
  2676. // export default {} in .vue || .jsx
  2677. const filePath = context.getFilename()
  2678. if (
  2679. isVueComponentFile(parent, filePath) &&
  2680. skipTSAsExpression(parent.declaration) === node
  2681. ) {
  2682. const scriptSetup = getScriptSetupElement(context)
  2683. if (
  2684. scriptSetup &&
  2685. scriptSetup.range[0] <= parent.range[0] &&
  2686. parent.range[1] <= scriptSetup.range[1]
  2687. ) {
  2688. // `export default` in `<script setup>`
  2689. return null
  2690. }
  2691. return 'export'
  2692. }
  2693. break
  2694. }
  2695. case 'CallExpression': {
  2696. // Vue.component('xxx', {}) || component('xxx', {})
  2697. if (
  2698. getVueComponentDefinitionType(node) != null &&
  2699. skipTSAsExpression(parent.arguments.slice(-1)[0]) === node
  2700. ) {
  2701. return 'definition'
  2702. }
  2703. break
  2704. }
  2705. case 'NewExpression': {
  2706. // new Vue({})
  2707. if (
  2708. isVueInstance(parent) &&
  2709. skipTSAsExpression(parent.arguments[0]) === node
  2710. ) {
  2711. return 'instance'
  2712. }
  2713. break
  2714. }
  2715. // No default
  2716. }
  2717. if (
  2718. getComponentComments(context).some(
  2719. (el) => el.loc.end.line === node.loc.start.line - 1
  2720. )
  2721. ) {
  2722. return 'mark'
  2723. }
  2724. return null
  2725. }
  2726. /**
  2727. * Checks whether the given object is an SFC definition.
  2728. * @param {RuleContext} context The ESLint rule context object.
  2729. * @param {ObjectExpression} node Node to check
  2730. * @returns { boolean } `true`, the given object is an SFC definition.
  2731. */
  2732. function isSFCObject(context, node) {
  2733. if (node.type !== 'ObjectExpression') {
  2734. return false
  2735. }
  2736. const filePath = context.getFilename()
  2737. const ext = path.extname(filePath)
  2738. if (ext !== '.vue' && ext) {
  2739. return false
  2740. }
  2741. return isSFC(node)
  2742. /**
  2743. * @param {Expression} node
  2744. * @returns {boolean}
  2745. */
  2746. function isSFC(node) {
  2747. const parent = getParent(node)
  2748. switch (parent.type) {
  2749. case 'ExportDefaultDeclaration': {
  2750. // export default {}
  2751. if (skipTSAsExpression(parent.declaration) !== node) {
  2752. return false
  2753. }
  2754. const scriptSetup = getScriptSetupElement(context)
  2755. if (
  2756. scriptSetup &&
  2757. scriptSetup.range[0] <= parent.range[0] &&
  2758. parent.range[1] <= scriptSetup.range[1]
  2759. ) {
  2760. // `export default` in `<script setup>`
  2761. return false
  2762. }
  2763. return true
  2764. }
  2765. case 'CallExpression': {
  2766. if (parent.arguments.every((arg) => skipTSAsExpression(arg) !== node)) {
  2767. return false
  2768. }
  2769. const { callee } = parent
  2770. if (
  2771. (callee.type === 'Identifier' && callee.name === 'defineComponent') ||
  2772. (callee.type === 'MemberExpression' &&
  2773. callee.object.type === 'Identifier' &&
  2774. callee.object.name === 'Vue' &&
  2775. callee.property.type === 'Identifier' &&
  2776. callee.property.name === 'extend')
  2777. ) {
  2778. return isSFC(parent)
  2779. }
  2780. return false
  2781. }
  2782. case 'VariableDeclarator': {
  2783. if (
  2784. skipTSAsExpression(parent.init) !== node ||
  2785. parent.id.type !== 'Identifier'
  2786. ) {
  2787. return false
  2788. }
  2789. const variable = findVariable(getScope(context, node), parent.id)
  2790. if (!variable) {
  2791. return false
  2792. }
  2793. return variable.references.some((ref) => isSFC(ref.identifier))
  2794. }
  2795. // No default
  2796. }
  2797. return false
  2798. }
  2799. }
  2800. /**
  2801. * Gets the component comments of a given context.
  2802. * @param {RuleContext} context The ESLint rule context object.
  2803. * @return {Token[]} The the component comments.
  2804. */
  2805. function getComponentComments(context) {
  2806. let tokens = componentComments.get(context)
  2807. if (tokens) {
  2808. return tokens
  2809. }
  2810. const sourceCode = context.getSourceCode()
  2811. tokens = sourceCode
  2812. .getAllComments()
  2813. .filter((comment) => /@vue\/component/g.test(comment.value))
  2814. componentComments.set(context, tokens)
  2815. return tokens
  2816. }
  2817. /**
  2818. * Return generator with the all handler nodes defined in the given watcher property.
  2819. * @param {Property|Expression} property
  2820. * @returns {IterableIterator<Expression>}
  2821. */
  2822. function* iterateWatchHandlerValues(property) {
  2823. const value = property.type === 'Property' ? property.value : property
  2824. if (value.type === 'ObjectExpression') {
  2825. const handler = findProperty(value, 'handler')
  2826. if (handler) {
  2827. yield handler.value
  2828. }
  2829. } else if (value.type === 'ArrayExpression') {
  2830. for (const element of value.elements.filter(isDef)) {
  2831. if (element.type !== 'SpreadElement') {
  2832. yield* iterateWatchHandlerValues(element)
  2833. }
  2834. }
  2835. } else {
  2836. yield value
  2837. }
  2838. }
  2839. /**
  2840. * Get the attribute which has the given name.
  2841. * @param {VElement} node The start tag node to check.
  2842. * @param {string} name The attribute name to check.
  2843. * @param {string} [value] The attribute value to check.
  2844. * @returns {VAttribute | null} The found attribute.
  2845. */
  2846. function getAttribute(node, name, value) {
  2847. return (
  2848. node.startTag.attributes.find(
  2849. /**
  2850. * @param {VAttribute | VDirective} node
  2851. * @returns {node is VAttribute}
  2852. */
  2853. (node) =>
  2854. !node.directive &&
  2855. node.key.name === name &&
  2856. (value === undefined ||
  2857. (node.value != null && node.value.value === value))
  2858. ) || null
  2859. )
  2860. }
  2861. /**
  2862. * Get the directive list which has the given name.
  2863. * @param {VElement | VStartTag} node The start tag node to check.
  2864. * @param {string} name The directive name to check.
  2865. * @returns {VDirective[]} The array of `v-slot` directives.
  2866. */
  2867. function getDirectives(node, name) {
  2868. const attributes =
  2869. node.type === 'VElement' ? node.startTag.attributes : node.attributes
  2870. return attributes.filter(
  2871. /**
  2872. * @param {VAttribute | VDirective} node
  2873. * @returns {node is VDirective}
  2874. */
  2875. (node) => node.directive && node.key.name.name === name
  2876. )
  2877. }
  2878. /**
  2879. * Get the directive which has the given name.
  2880. * @param {VElement} node The start tag node to check.
  2881. * @param {string} name The directive name to check.
  2882. * @param {string} [argument] The directive argument to check.
  2883. * @returns {VDirective | null} The found directive.
  2884. */
  2885. function getDirective(node, name, argument) {
  2886. return (
  2887. node.startTag.attributes.find(
  2888. /**
  2889. * @param {VAttribute | VDirective} node
  2890. * @returns {node is VDirective}
  2891. */
  2892. (node) =>
  2893. node.directive &&
  2894. node.key.name.name === name &&
  2895. (argument === undefined ||
  2896. (node.key.argument &&
  2897. node.key.argument.type === 'VIdentifier' &&
  2898. node.key.argument.name) === argument)
  2899. ) || null
  2900. )
  2901. }
  2902. /**
  2903. * Check whether the given start tag has specific directive.
  2904. * @param {VElement} node The start tag node to check.
  2905. * @param {string} name The attribute name to check.
  2906. * @param {string} [value] The attribute value to check.
  2907. * @returns {boolean} `true` if the start tag has the attribute.
  2908. */
  2909. function hasAttribute(node, name, value) {
  2910. return Boolean(getAttribute(node, name, value))
  2911. }
  2912. /**
  2913. * Check whether the given start tag has specific directive.
  2914. * @param {VElement} node The start tag node to check.
  2915. * @param {string} name The directive name to check.
  2916. * @param {string} [argument] The directive argument to check.
  2917. * @returns {boolean} `true` if the start tag has the directive.
  2918. */
  2919. function hasDirective(node, name, argument) {
  2920. return Boolean(getDirective(node, name, argument))
  2921. }
  2922. /**
  2923. * Check whether the given directive node is v-bind same-name shorthand.
  2924. * @param {VAttribute | VDirective} node The directive node to check.
  2925. * @returns {node is VDirective & { value: VExpressionContainer & { expression: Identifier } }} `true` if the directive node is v-bind same-name shorthand.
  2926. */
  2927. function isVBindSameNameShorthand(node) {
  2928. return (
  2929. node.directive &&
  2930. node.key.name.name === 'bind' &&
  2931. node.value?.expression?.type === 'Identifier' &&
  2932. node.key.range[0] <= node.value.range[0] &&
  2933. node.value.range[1] <= node.key.range[1]
  2934. )
  2935. }
  2936. /**
  2937. * Checks whether given defineProps call node has withDefaults.
  2938. * @param {CallExpression} node The node of defineProps
  2939. * @returns {node is CallExpression & { parent: CallExpression }}
  2940. */
  2941. function hasWithDefaults(node) {
  2942. return (
  2943. node.parent &&
  2944. node.parent.type === 'CallExpression' &&
  2945. node.parent.arguments[0] === node &&
  2946. node.parent.callee.type === 'Identifier' &&
  2947. node.parent.callee.name === 'withDefaults'
  2948. )
  2949. }
  2950. /**
  2951. * Get the withDefaults call node from given defineProps call node.
  2952. * @param {CallExpression} node The node of defineProps
  2953. * @returns {CallExpression | null}
  2954. */
  2955. function getWithDefaults(node) {
  2956. return hasWithDefaults(node) ? node.parent : null
  2957. }
  2958. /**
  2959. * Gets a map of the property nodes defined in withDefaults.
  2960. * @param {CallExpression} node The node of defineProps
  2961. * @returns { { [key: string]: Property | undefined } }
  2962. */
  2963. function getWithDefaultsProps(node) {
  2964. if (!hasWithDefaults(node)) {
  2965. return {}
  2966. }
  2967. const param = node.parent.arguments[1]
  2968. if (!param || param.type !== 'ObjectExpression') {
  2969. return {}
  2970. }
  2971. /** @type {Record<string, Property>} */
  2972. const result = {}
  2973. for (const prop of param.properties) {
  2974. if (prop.type !== 'Property') {
  2975. continue
  2976. }
  2977. const name = getStaticPropertyName(prop)
  2978. if (name != null) {
  2979. result[name] = prop
  2980. }
  2981. }
  2982. return result
  2983. }
  2984. /**
  2985. * Gets the props destructure property nodes for defineProp.
  2986. * @param {CallExpression} node The node of defineProps
  2987. * @returns { Record<string, AssignmentProperty | undefined> }
  2988. */
  2989. function getPropsDestructure(node) {
  2990. /** @type {ReturnType<typeof getPropsDestructure>} */
  2991. const result = Object.create(null)
  2992. const left = getLeftOfDefineProps(node)
  2993. if (!left || left.type !== 'ObjectPattern') {
  2994. return result
  2995. }
  2996. for (const prop of left.properties) {
  2997. if (prop.type !== 'Property') continue
  2998. const name = getStaticPropertyName(prop)
  2999. if (name != null) {
  3000. result[name] = prop
  3001. }
  3002. }
  3003. return result
  3004. }
  3005. /**
  3006. * Gets the default definition nodes for defineProp
  3007. * using the props destructure with assignment pattern.
  3008. * @param {CallExpression} node The node of defineProps
  3009. * @returns { Record<string, {prop: AssignmentProperty , expression: Expression} | undefined> }
  3010. */
  3011. function getDefaultPropExpressionsForPropsDestructure(node) {
  3012. /** @type {ReturnType<typeof getDefaultPropExpressionsForPropsDestructure>} */
  3013. const result = Object.create(null)
  3014. for (const [name, prop] of Object.entries(getPropsDestructure(node))) {
  3015. if (!prop) continue
  3016. const value = prop.value
  3017. if (value.type !== 'AssignmentPattern') continue
  3018. result[name] = { prop, expression: value.right }
  3019. }
  3020. return result
  3021. }
  3022. /**
  3023. * Gets the pattern of the left operand of defineProps.
  3024. * @param {CallExpression} node The node of defineProps
  3025. * @returns {Pattern | null} The pattern of the left operand of defineProps
  3026. */
  3027. function getLeftOfDefineProps(node) {
  3028. let target = node
  3029. if (hasWithDefaults(target)) {
  3030. target = target.parent
  3031. }
  3032. if (!target.parent) {
  3033. return null
  3034. }
  3035. if (
  3036. target.parent.type === 'VariableDeclarator' &&
  3037. target.parent.init === target
  3038. ) {
  3039. return target.parent.id
  3040. }
  3041. return null
  3042. }
  3043. /**
  3044. * Get all props from component options object.
  3045. * @param {ObjectExpression} componentObject Object with component definition
  3046. * @return {(ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp)[]} Array of component props
  3047. */
  3048. function getComponentPropsFromOptions(componentObject) {
  3049. const propsNode = componentObject.properties.find(
  3050. /**
  3051. * @param {ESNode} p
  3052. * @returns {p is (Property & { key: Identifier & {name: 'props'} })}
  3053. */
  3054. (p) => p.type === 'Property' && getStaticPropertyName(p) === 'props'
  3055. )
  3056. if (!propsNode) {
  3057. return []
  3058. }
  3059. if (
  3060. propsNode.value.type !== 'ObjectExpression' &&
  3061. propsNode.value.type !== 'ArrayExpression'
  3062. ) {
  3063. return [
  3064. {
  3065. type: 'unknown',
  3066. propName: null,
  3067. node: propsNode.value
  3068. }
  3069. ]
  3070. }
  3071. return getComponentPropsFromDefine(propsNode.value)
  3072. }
  3073. /**
  3074. * Get all emits from component options object.
  3075. * @param {ObjectExpression} componentObject Object with component definition
  3076. * @return {(ComponentArrayEmit | ComponentObjectEmit | ComponentUnknownEmit)[]} Array of component emits
  3077. */
  3078. function getComponentEmitsFromOptions(componentObject) {
  3079. const emitsNode = componentObject.properties.find(
  3080. /**
  3081. * @param {ESNode} p
  3082. * @returns {p is (Property & { key: Identifier & {name: 'emits'} })}
  3083. */
  3084. (p) => p.type === 'Property' && getStaticPropertyName(p) === 'emits'
  3085. )
  3086. if (!emitsNode) {
  3087. return []
  3088. }
  3089. if (
  3090. emitsNode.value.type !== 'ObjectExpression' &&
  3091. emitsNode.value.type !== 'ArrayExpression'
  3092. ) {
  3093. return [
  3094. {
  3095. type: 'unknown',
  3096. emitName: null,
  3097. node: emitsNode.value
  3098. }
  3099. ]
  3100. }
  3101. return getComponentEmitsFromDefine(emitsNode.value)
  3102. }
  3103. /**
  3104. * Get all props from `defineProps` call expression.
  3105. * @param {RuleContext} context The rule context object.
  3106. * @param {CallExpression} node `defineProps` call expression
  3107. * @return {ComponentProp[]} Array of component props
  3108. */
  3109. function getComponentPropsFromDefineProps(context, node) {
  3110. if (node.arguments.length > 0) {
  3111. const defNode = getObjectOrArray(context, node.arguments[0])
  3112. if (defNode) {
  3113. return getComponentPropsFromDefine(defNode)
  3114. }
  3115. return [
  3116. {
  3117. type: 'unknown',
  3118. propName: null,
  3119. node: node.arguments[0]
  3120. }
  3121. ]
  3122. }
  3123. const typeArguments =
  3124. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3125. if (typeArguments && typeArguments.params.length > 0) {
  3126. return getComponentPropsFromTypeDefine(context, typeArguments.params[0])
  3127. }
  3128. return [
  3129. {
  3130. type: 'unknown',
  3131. propName: null,
  3132. node: null
  3133. }
  3134. ]
  3135. }
  3136. /**
  3137. * Get all emits from `defineEmits` call expression.
  3138. * @param {RuleContext} context The rule context object.
  3139. * @param {CallExpression} node `defineEmits` call expression
  3140. * @return {ComponentEmit[]} Array of component emits
  3141. */
  3142. function getComponentEmitsFromDefineEmits(context, node) {
  3143. if (node.arguments.length > 0) {
  3144. const defNode = getObjectOrArray(context, node.arguments[0])
  3145. if (defNode) {
  3146. return getComponentEmitsFromDefine(defNode)
  3147. }
  3148. return [
  3149. {
  3150. type: 'unknown',
  3151. emitName: null,
  3152. node: node.arguments[0]
  3153. }
  3154. ]
  3155. }
  3156. const typeArguments =
  3157. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3158. if (typeArguments && typeArguments.params.length > 0) {
  3159. return getComponentEmitsFromTypeDefine(context, typeArguments.params[0])
  3160. }
  3161. return [
  3162. {
  3163. type: 'unknown',
  3164. emitName: null,
  3165. node: null
  3166. }
  3167. ]
  3168. }
  3169. /**
  3170. * Get model info from `defineModel` call expression.
  3171. * @param {RuleContext} _context The rule context object.
  3172. * @param {CallExpression} node `defineModel` call expression
  3173. * @return {ComponentModel} Object of component model
  3174. */
  3175. function getComponentModelFromDefineModel(_context, node) {
  3176. /** @type {ComponentModelName} */
  3177. let name = {
  3178. modelName: 'modelValue',
  3179. node: null
  3180. }
  3181. /** @type {Expression|null} */
  3182. let options =
  3183. node.arguments[0]?.type === 'SpreadElement' ? null : node.arguments[0]
  3184. if (node.arguments.length > 0) {
  3185. const nameNodeCandidate = skipTSAsExpression(node.arguments[0])
  3186. if (nameNodeCandidate.type === 'Literal') {
  3187. name = {
  3188. modelName: String(nameNodeCandidate.value),
  3189. node: nameNodeCandidate
  3190. }
  3191. options =
  3192. node.arguments[1]?.type === 'SpreadElement' ? null : node.arguments[1]
  3193. }
  3194. }
  3195. const typeArguments =
  3196. 'typeArguments' in node ? node.typeArguments : node.typeParameters
  3197. if (typeArguments && typeArguments.params.length > 0) {
  3198. return {
  3199. name,
  3200. options,
  3201. typeNode: typeArguments.params[0]
  3202. }
  3203. }
  3204. return {
  3205. name,
  3206. options,
  3207. typeNode: null
  3208. }
  3209. }
  3210. /**
  3211. * Get all props by looking at all component's properties
  3212. * @param {ObjectExpression|ArrayExpression} propsNode Object with props definition
  3213. * @return {(ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp)[]} Array of component props
  3214. */
  3215. function getComponentPropsFromDefine(propsNode) {
  3216. if (propsNode.type === 'ObjectExpression') {
  3217. return propsNode.properties.map(
  3218. /** @returns {ComponentArrayProp | ComponentObjectProp | ComponentUnknownProp} */
  3219. (prop) => {
  3220. if (!isProperty(prop)) {
  3221. return {
  3222. type: 'unknown',
  3223. propName: null,
  3224. node: prop
  3225. }
  3226. }
  3227. const propName = getStaticPropertyName(prop)
  3228. if (propName != null) {
  3229. return {
  3230. type: 'object',
  3231. key: prop.key,
  3232. propName,
  3233. value: skipTSAsExpression(prop.value),
  3234. node: prop
  3235. }
  3236. }
  3237. return {
  3238. type: 'object',
  3239. key: null,
  3240. propName: null,
  3241. value: skipTSAsExpression(prop.value),
  3242. node: prop
  3243. }
  3244. }
  3245. )
  3246. }
  3247. return propsNode.elements.filter(isDef).map((prop) => {
  3248. if (prop.type === 'Literal' || prop.type === 'TemplateLiteral') {
  3249. const propName = getStringLiteralValue(prop)
  3250. if (propName != null) {
  3251. return {
  3252. type: 'array',
  3253. key: prop,
  3254. propName,
  3255. value: null,
  3256. node: prop
  3257. }
  3258. }
  3259. }
  3260. return {
  3261. type: 'array',
  3262. key: null,
  3263. propName: null,
  3264. value: null,
  3265. node: prop
  3266. }
  3267. })
  3268. }
  3269. /**
  3270. * Get all emits by looking at all component's properties
  3271. * @param {ObjectExpression|ArrayExpression} emitsNode Object with emits definition
  3272. * @return {(ComponentArrayEmit | ComponentObjectEmit | ComponentUnknownEmit)[]} Array of component emits.
  3273. */
  3274. function getComponentEmitsFromDefine(emitsNode) {
  3275. if (emitsNode.type === 'ObjectExpression') {
  3276. return emitsNode.properties.map((prop) => {
  3277. if (!isProperty(prop)) {
  3278. return {
  3279. type: 'unknown',
  3280. key: null,
  3281. emitName: null,
  3282. value: null,
  3283. node: prop
  3284. }
  3285. }
  3286. const emitName = getStaticPropertyName(prop)
  3287. if (emitName != null) {
  3288. return {
  3289. type: 'object',
  3290. key: prop.key,
  3291. emitName,
  3292. value: skipTSAsExpression(prop.value),
  3293. node: prop
  3294. }
  3295. }
  3296. return {
  3297. type: 'object',
  3298. key: null,
  3299. emitName: null,
  3300. value: skipTSAsExpression(prop.value),
  3301. node: prop
  3302. }
  3303. })
  3304. }
  3305. return emitsNode.elements.filter(isDef).map((emit) => {
  3306. if (emit.type === 'Literal' || emit.type === 'TemplateLiteral') {
  3307. const emitName = getStringLiteralValue(emit)
  3308. if (emitName != null) {
  3309. return {
  3310. type: 'array',
  3311. key: emit,
  3312. emitName,
  3313. value: null,
  3314. node: emit
  3315. }
  3316. }
  3317. }
  3318. return {
  3319. type: 'array',
  3320. key: null,
  3321. emitName: null,
  3322. value: null,
  3323. node: emit
  3324. }
  3325. })
  3326. }
  3327. /**
  3328. * @param {RuleContext} context The rule context object.
  3329. * @param {ESNode} node
  3330. * @returns {ObjectExpression | ArrayExpression | null}
  3331. */
  3332. function getObjectOrArray(context, node) {
  3333. if (node.type === 'ObjectExpression') {
  3334. return node
  3335. }
  3336. if (node.type === 'ArrayExpression') {
  3337. return node
  3338. }
  3339. if (node.type === 'Identifier') {
  3340. const variable = findVariable(getScope(context, node), node)
  3341. if (variable != null && variable.defs.length === 1) {
  3342. const def = variable.defs[0]
  3343. if (
  3344. def.type === 'Variable' &&
  3345. def.parent.kind === 'const' &&
  3346. def.node.id.type === 'Identifier' &&
  3347. def.node.init
  3348. ) {
  3349. return getObjectOrArray(context, def.node.init)
  3350. }
  3351. }
  3352. }
  3353. return null
  3354. }