no-mutating-props.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /**
  2. * @fileoverview disallow mutation component props
  3. * @author 2018 Armano
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const { findVariable } = require('eslint-utils')
  8. // ------------------------------------------------------------------------------
  9. // Rule Definition
  10. // ------------------------------------------------------------------------------
  11. // https://github.com/vuejs/vue-next/blob/7c11c58faf8840ab97b6449c98da0296a60dddd8/packages/shared/src/globalsWhitelist.ts
  12. const GLOBALS_WHITE_LISTED = new Set([
  13. 'Infinity',
  14. 'undefined',
  15. 'NaN',
  16. 'isFinite',
  17. 'isNaN',
  18. 'parseFloat',
  19. 'parseInt',
  20. 'decodeURI',
  21. 'decodeURIComponent',
  22. 'encodeURI',
  23. 'encodeURIComponent',
  24. 'Math',
  25. 'Number',
  26. 'Date',
  27. 'Array',
  28. 'Object',
  29. 'Boolean',
  30. 'String',
  31. 'RegExp',
  32. 'Map',
  33. 'Set',
  34. 'JSON',
  35. 'Intl',
  36. 'BigInt'
  37. ])
  38. module.exports = {
  39. meta: {
  40. type: 'suggestion',
  41. docs: {
  42. description: 'disallow mutation of component props',
  43. categories: ['vue3-essential', 'essential'],
  44. url: 'https://eslint.vuejs.org/rules/no-mutating-props.html'
  45. },
  46. fixable: null, // or "code" or "whitespace"
  47. schema: [
  48. // fill in your schema
  49. ]
  50. },
  51. /** @param {RuleContext} context */
  52. create(context) {
  53. /** @type {Map<ObjectExpression|CallExpression, Set<string>>} */
  54. const propsMap = new Map()
  55. /** @type { { type: 'export' | 'mark' | 'definition', object: ObjectExpression } | { type: 'setup', object: CallExpression } | null } */
  56. let vueObjectData = null
  57. /**
  58. * @param {ASTNode} node
  59. * @param {string} name
  60. */
  61. function report(node, name) {
  62. context.report({
  63. node,
  64. message: 'Unexpected mutation of "{{key}}" prop.',
  65. data: {
  66. key: name
  67. }
  68. })
  69. }
  70. /**
  71. * @param {ASTNode} node
  72. * @returns {VExpressionContainer}
  73. */
  74. function getVExpressionContainer(node) {
  75. let n = node
  76. while (n.type !== 'VExpressionContainer') {
  77. n = /** @type {ASTNode} */ (n.parent)
  78. }
  79. return n
  80. }
  81. /**
  82. * @param {MemberExpression|AssignmentProperty} node
  83. * @returns {string}
  84. */
  85. function getPropertyNameText(node) {
  86. const name = utils.getStaticPropertyName(node)
  87. if (name) {
  88. return name
  89. }
  90. if (node.computed) {
  91. const expr = node.type === 'Property' ? node.key : node.property
  92. const str = context.getSourceCode().getText(expr)
  93. return `[${str}]`
  94. }
  95. return '?unknown?'
  96. }
  97. /**
  98. * @param {ASTNode} node
  99. * @returns {node is Identifier}
  100. */
  101. function isVmReference(node) {
  102. if (node.type !== 'Identifier') {
  103. return false
  104. }
  105. const parent = node.parent
  106. if (parent.type === 'MemberExpression') {
  107. if (parent.property === node) {
  108. // foo.id
  109. return false
  110. }
  111. } else if (parent.type === 'Property') {
  112. // {id: foo}
  113. if (parent.key === node && !parent.computed) {
  114. return false
  115. }
  116. }
  117. const exprContainer = getVExpressionContainer(node)
  118. for (const reference of exprContainer.references) {
  119. if (reference.variable != null) {
  120. // Not vm reference
  121. continue
  122. }
  123. if (reference.id === node) {
  124. return true
  125. }
  126. }
  127. return false
  128. }
  129. /**
  130. * @param {MemberExpression|Identifier} props
  131. * @param {string} name
  132. */
  133. function verifyMutating(props, name) {
  134. const invalid = utils.findMutating(props)
  135. if (invalid) {
  136. report(invalid.node, name)
  137. }
  138. }
  139. /**
  140. * @param {Pattern} param
  141. * @param {string[]} path
  142. * @returns {Generator<{ node: Identifier, path: string[] }>}
  143. */
  144. function* iteratePatternProperties(param, path) {
  145. if (!param) {
  146. return
  147. }
  148. if (param.type === 'Identifier') {
  149. yield {
  150. node: param,
  151. path
  152. }
  153. } else if (param.type === 'RestElement') {
  154. yield* iteratePatternProperties(param.argument, path)
  155. } else if (param.type === 'AssignmentPattern') {
  156. yield* iteratePatternProperties(param.left, path)
  157. } else if (param.type === 'ObjectPattern') {
  158. for (const prop of param.properties) {
  159. if (prop.type === 'Property') {
  160. const name = getPropertyNameText(prop)
  161. yield* iteratePatternProperties(prop.value, [...path, name])
  162. } else if (prop.type === 'RestElement') {
  163. yield* iteratePatternProperties(prop.argument, path)
  164. }
  165. }
  166. } else if (param.type === 'ArrayPattern') {
  167. for (let index = 0; index < param.elements.length; index++) {
  168. const element = param.elements[index]
  169. yield* iteratePatternProperties(element, [...path, `${index}`])
  170. }
  171. }
  172. }
  173. /**
  174. * @param {Identifier} prop
  175. * @param {string[]} path
  176. */
  177. function verifyPropVariable(prop, path) {
  178. const variable = findVariable(context.getScope(), prop)
  179. if (!variable) {
  180. return
  181. }
  182. for (const reference of variable.references) {
  183. if (!reference.isRead()) {
  184. continue
  185. }
  186. const id = reference.identifier
  187. const invalid = utils.findMutating(id)
  188. if (!invalid) {
  189. continue
  190. }
  191. let name
  192. if (path.length === 0) {
  193. if (invalid.pathNodes.length === 0) {
  194. continue
  195. }
  196. const mem = invalid.pathNodes[0]
  197. name = getPropertyNameText(mem)
  198. } else {
  199. if (invalid.pathNodes.length === 0 && invalid.kind !== 'call') {
  200. continue
  201. }
  202. name = path[0]
  203. }
  204. report(invalid.node, name)
  205. }
  206. }
  207. function* extractDefineVariableNames() {
  208. const globalScope = context.getSourceCode().scopeManager.globalScope
  209. if (globalScope) {
  210. for (const variable of globalScope.variables) {
  211. if (variable.defs.length) {
  212. yield variable.name
  213. }
  214. }
  215. const moduleScope = globalScope.childScopes.find(
  216. (scope) => scope.type === 'module'
  217. )
  218. for (const variable of (moduleScope && moduleScope.variables) || []) {
  219. if (variable.defs.length) {
  220. yield variable.name
  221. }
  222. }
  223. }
  224. }
  225. return utils.compositingVisitors(
  226. {},
  227. utils.defineScriptSetupVisitor(context, {
  228. onDefinePropsEnter(node, props) {
  229. const defineVariableNames = new Set(extractDefineVariableNames())
  230. const propsSet = new Set(
  231. props
  232. .map((p) => p.propName)
  233. .filter(
  234. /**
  235. * @returns {propName is string}
  236. */
  237. (propName) =>
  238. utils.isDef(propName) &&
  239. !GLOBALS_WHITE_LISTED.has(propName) &&
  240. !defineVariableNames.has(propName)
  241. )
  242. )
  243. propsMap.set(node, propsSet)
  244. vueObjectData = {
  245. type: 'setup',
  246. object: node
  247. }
  248. let target = node
  249. if (
  250. target.parent &&
  251. target.parent.type === 'CallExpression' &&
  252. target.parent.arguments[0] === target &&
  253. target.parent.callee.type === 'Identifier' &&
  254. target.parent.callee.name === 'withDefaults'
  255. ) {
  256. target = target.parent
  257. }
  258. if (
  259. !target.parent ||
  260. target.parent.type !== 'VariableDeclarator' ||
  261. target.parent.init !== target
  262. ) {
  263. return
  264. }
  265. for (const { node: prop, path } of iteratePatternProperties(
  266. target.parent.id,
  267. []
  268. )) {
  269. verifyPropVariable(prop, path)
  270. propsSet.add(prop.name)
  271. }
  272. }
  273. }),
  274. utils.defineVueVisitor(context, {
  275. onVueObjectEnter(node) {
  276. propsMap.set(
  277. node,
  278. new Set(
  279. utils
  280. .getComponentPropsFromOptions(node)
  281. .map((p) => p.propName)
  282. .filter(utils.isDef)
  283. )
  284. )
  285. },
  286. onVueObjectExit(node, { type }) {
  287. if (
  288. (!vueObjectData ||
  289. (vueObjectData.type !== 'export' &&
  290. vueObjectData.type !== 'setup')) &&
  291. type !== 'instance'
  292. ) {
  293. vueObjectData = {
  294. type,
  295. object: node
  296. }
  297. }
  298. },
  299. onSetupFunctionEnter(node) {
  300. const propsParam = node.params[0]
  301. if (!propsParam) {
  302. // no arguments
  303. return
  304. }
  305. if (
  306. propsParam.type === 'RestElement' ||
  307. propsParam.type === 'ArrayPattern'
  308. ) {
  309. // cannot check
  310. return
  311. }
  312. for (const { node: prop, path } of iteratePatternProperties(
  313. propsParam,
  314. []
  315. )) {
  316. verifyPropVariable(prop, path)
  317. }
  318. },
  319. /** @param {(Identifier | ThisExpression) & { parent: MemberExpression } } node */
  320. 'MemberExpression > :matches(Identifier, ThisExpression)'(
  321. node,
  322. { node: vueNode }
  323. ) {
  324. if (!utils.isThis(node, context)) {
  325. return
  326. }
  327. const mem = node.parent
  328. if (mem.object !== node) {
  329. return
  330. }
  331. const name = utils.getStaticPropertyName(mem)
  332. if (
  333. name &&
  334. /** @type {Set<string>} */ (propsMap.get(vueNode)).has(name)
  335. ) {
  336. verifyMutating(mem, name)
  337. }
  338. }
  339. }),
  340. utils.defineTemplateBodyVisitor(context, {
  341. /** @param {ThisExpression & { parent: MemberExpression } } node */
  342. 'VExpressionContainer MemberExpression > ThisExpression'(node) {
  343. if (!vueObjectData) {
  344. return
  345. }
  346. const mem = node.parent
  347. if (mem.object !== node) {
  348. return
  349. }
  350. const name = utils.getStaticPropertyName(mem)
  351. if (
  352. name &&
  353. /** @type {Set<string>} */ (propsMap.get(vueObjectData.object)).has(
  354. name
  355. )
  356. ) {
  357. verifyMutating(mem, name)
  358. }
  359. },
  360. /** @param {Identifier } node */
  361. 'VExpressionContainer Identifier'(node) {
  362. if (!vueObjectData) {
  363. return
  364. }
  365. if (!isVmReference(node)) {
  366. return
  367. }
  368. const name = node.name
  369. if (
  370. name &&
  371. /** @type {Set<string>} */ (propsMap.get(vueObjectData.object)).has(
  372. name
  373. )
  374. ) {
  375. verifyMutating(node, name)
  376. }
  377. },
  378. /** @param {ESNode} node */
  379. "VAttribute[directive=true]:matches([key.name.name='model'], [key.name.name='bind']) VExpressionContainer > *"(
  380. node
  381. ) {
  382. if (!vueObjectData) {
  383. return
  384. }
  385. let attr = node.parent
  386. while (attr && attr.type !== 'VAttribute') {
  387. attr = attr.parent
  388. }
  389. if (attr && attr.directive && attr.key.name.name === 'bind') {
  390. if (!attr.key.modifiers.some((mod) => mod.name === 'sync')) {
  391. return
  392. }
  393. }
  394. const nodes = utils.getMemberChaining(node)
  395. const first = nodes[0]
  396. let name
  397. if (isVmReference(first)) {
  398. name = first.name
  399. } else if (first.type === 'ThisExpression') {
  400. const mem = nodes[1]
  401. if (!mem) {
  402. return
  403. }
  404. name = utils.getStaticPropertyName(mem)
  405. } else {
  406. return
  407. }
  408. if (
  409. name &&
  410. /** @type {Set<string>} */ (propsMap.get(vueObjectData.object)).has(
  411. name
  412. )
  413. ) {
  414. report(node, name)
  415. }
  416. }
  417. })
  418. )
  419. }
  420. }