no-mutating-props.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /**
  2. * @fileoverview disallow mutation component props
  3. * @author 2018 Armano
  4. */
  5. 'use strict'
  6. /**
  7. * @typedef {{name?: string, set: Set<string>}} PropsInfo
  8. */
  9. const utils = require('../utils')
  10. const { findVariable } = require('@eslint-community/eslint-utils')
  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. /**
  39. * @param {ASTNode} node
  40. * @returns {VExpressionContainer}
  41. */
  42. function getVExpressionContainer(node) {
  43. let n = node
  44. while (n.type !== 'VExpressionContainer') {
  45. n = /** @type {ASTNode} */ (n.parent)
  46. }
  47. return n
  48. }
  49. /**
  50. * @param {ASTNode} node
  51. * @returns {node is Identifier}
  52. */
  53. function isVmReference(node) {
  54. if (node.type !== 'Identifier') {
  55. return false
  56. }
  57. const parent = node.parent
  58. if (parent.type === 'MemberExpression') {
  59. if (parent.property === node) {
  60. // foo.id
  61. return false
  62. }
  63. } else if (
  64. parent.type === 'Property' &&
  65. parent.key === node &&
  66. !parent.computed
  67. ) {
  68. // {id: foo}
  69. return false
  70. }
  71. const exprContainer = getVExpressionContainer(node)
  72. for (const reference of exprContainer.references) {
  73. if (reference.variable != null) {
  74. // Not vm reference
  75. continue
  76. }
  77. if (reference.id === node) {
  78. return true
  79. }
  80. }
  81. return false
  82. }
  83. /**
  84. * @param { object } options
  85. * @param { boolean } options.shallowOnly Enables mutating the value of a prop but leaving the reference the same
  86. */
  87. function parseOptions(options) {
  88. return Object.assign(
  89. {
  90. shallowOnly: false
  91. },
  92. options
  93. )
  94. }
  95. module.exports = {
  96. meta: {
  97. type: 'suggestion',
  98. docs: {
  99. description: 'disallow mutation of component props',
  100. categories: ['vue3-essential', 'vue2-essential'],
  101. url: 'https://eslint.vuejs.org/rules/no-mutating-props.html'
  102. },
  103. fixable: null,
  104. schema: [
  105. {
  106. type: 'object',
  107. properties: {
  108. shallowOnly: {
  109. type: 'boolean'
  110. }
  111. },
  112. additionalProperties: false
  113. }
  114. ],
  115. messages: {
  116. unexpectedMutation: 'Unexpected mutation of "{{key}}" prop.'
  117. }
  118. },
  119. /** @param {RuleContext} context */
  120. create(context) {
  121. const { shallowOnly } = parseOptions(context.options[0])
  122. /** @type {Map<ObjectExpression|CallExpression, PropsInfo>} */
  123. const propsMap = new Map()
  124. /** @type { { type: 'export' | 'mark' | 'definition', object: ObjectExpression } | { type: 'setup', object: CallExpression } | null } */
  125. let vueObjectData = null
  126. /**
  127. * @param {ASTNode} node
  128. * @param {string} name
  129. */
  130. function report(node, name) {
  131. context.report({
  132. node,
  133. messageId: 'unexpectedMutation',
  134. data: {
  135. key: name
  136. }
  137. })
  138. }
  139. /**
  140. * @param {MemberExpression|AssignmentProperty} node
  141. * @returns {string}
  142. */
  143. function getPropertyNameText(node) {
  144. const name = utils.getStaticPropertyName(node)
  145. if (name) {
  146. return name
  147. }
  148. if (node.computed) {
  149. const expr = node.type === 'Property' ? node.key : node.property
  150. const str = context.getSourceCode().getText(expr)
  151. return `[${str}]`
  152. }
  153. return '?unknown?'
  154. }
  155. /**
  156. * @param {MemberExpression|Identifier} props
  157. * @param {string} name
  158. * @param {boolean} isRootProps
  159. */
  160. function verifyMutating(props, name, isRootProps = false) {
  161. const invalid = utils.findMutating(props)
  162. if (invalid && isShallowOnlyInvalid(invalid, isRootProps)) {
  163. report(invalid.node, name)
  164. }
  165. }
  166. /**
  167. * @param {Pattern} param
  168. * @param {string[]} path
  169. * @returns {Generator<{ node: Identifier, path: string[] }>}
  170. */
  171. function* iteratePatternProperties(param, path) {
  172. if (!param) {
  173. return
  174. }
  175. switch (param.type) {
  176. case 'Identifier': {
  177. yield { node: param, path }
  178. break
  179. }
  180. case 'RestElement': {
  181. yield* iteratePatternProperties(param.argument, path)
  182. break
  183. }
  184. case 'AssignmentPattern': {
  185. yield* iteratePatternProperties(param.left, path)
  186. break
  187. }
  188. case 'ObjectPattern': {
  189. for (const prop of param.properties) {
  190. if (prop.type === 'Property') {
  191. const name = getPropertyNameText(prop)
  192. yield* iteratePatternProperties(prop.value, [...path, name])
  193. } else if (prop.type === 'RestElement') {
  194. yield* iteratePatternProperties(prop.argument, path)
  195. }
  196. }
  197. break
  198. }
  199. case 'ArrayPattern': {
  200. for (let index = 0; index < param.elements.length; index++) {
  201. const element = param.elements[index]
  202. if (element)
  203. yield* iteratePatternProperties(element, [...path, `${index}`])
  204. }
  205. break
  206. }
  207. }
  208. }
  209. /**
  210. * @param {Identifier} prop
  211. * @param {string[]} path
  212. */
  213. function verifyPropVariable(prop, path) {
  214. const variable = findVariable(utils.getScope(context, prop), prop)
  215. if (!variable) {
  216. return
  217. }
  218. for (const reference of variable.references) {
  219. if (!reference.isRead()) {
  220. continue
  221. }
  222. const id = reference.identifier
  223. const invalid = utils.findMutating(id)
  224. if (!invalid) {
  225. continue
  226. }
  227. let name
  228. if (!isShallowOnlyInvalid(invalid, path.length === 0)) {
  229. continue
  230. }
  231. if (path.length === 0) {
  232. if (invalid.pathNodes.length === 0) {
  233. continue
  234. }
  235. const mem = invalid.pathNodes[0]
  236. name = getPropertyNameText(mem)
  237. } else {
  238. if (invalid.pathNodes.length === 0 && invalid.kind !== 'call') {
  239. continue
  240. }
  241. name = path[0]
  242. }
  243. report(invalid.node, name)
  244. }
  245. }
  246. function* extractDefineVariableNames() {
  247. const globalScope = context.getSourceCode().scopeManager.globalScope
  248. if (globalScope) {
  249. for (const variable of globalScope.variables) {
  250. if (variable.defs.length > 0) {
  251. yield variable.name
  252. }
  253. }
  254. const moduleScope = globalScope.childScopes.find(
  255. (scope) => scope.type === 'module'
  256. )
  257. for (const variable of (moduleScope && moduleScope.variables) || []) {
  258. if (variable.defs.length > 0) {
  259. yield variable.name
  260. }
  261. }
  262. }
  263. }
  264. /**
  265. * Is shallowOnly false or the prop reassigned
  266. * @param {Exclude<ReturnType<typeof utils.findMutating>, null>} invalid
  267. * @param {boolean} isRootProps
  268. * @return {boolean}
  269. */
  270. function isShallowOnlyInvalid(invalid, isRootProps) {
  271. return (
  272. !shallowOnly ||
  273. (invalid.pathNodes.length === (isRootProps ? 1 : 0) &&
  274. ['assignment', 'update'].includes(invalid.kind))
  275. )
  276. }
  277. return utils.compositingVisitors(
  278. {},
  279. utils.defineScriptSetupVisitor(context, {
  280. onDefinePropsEnter(node, props) {
  281. const defineVariableNames = new Set(extractDefineVariableNames())
  282. const propsInfo = {
  283. name: '',
  284. set: new Set(
  285. props
  286. .map((p) => p.propName)
  287. .filter(
  288. /**
  289. * @returns {propName is string}
  290. */
  291. (propName) =>
  292. utils.isDef(propName) &&
  293. !GLOBALS_WHITE_LISTED.has(propName) &&
  294. !defineVariableNames.has(propName)
  295. )
  296. )
  297. }
  298. propsMap.set(node, propsInfo)
  299. vueObjectData = {
  300. type: 'setup',
  301. object: node
  302. }
  303. let target = node
  304. if (
  305. target.parent &&
  306. target.parent.type === 'CallExpression' &&
  307. target.parent.arguments[0] === target &&
  308. target.parent.callee.type === 'Identifier' &&
  309. target.parent.callee.name === 'withDefaults'
  310. ) {
  311. target = target.parent
  312. }
  313. if (
  314. !target.parent ||
  315. target.parent.type !== 'VariableDeclarator' ||
  316. target.parent.init !== target
  317. ) {
  318. return
  319. }
  320. for (const { node: prop, path } of iteratePatternProperties(
  321. target.parent.id,
  322. []
  323. )) {
  324. if (path.length === 0) {
  325. propsInfo.name = prop.name
  326. } else {
  327. propsInfo.set.add(prop.name)
  328. }
  329. verifyPropVariable(prop, path)
  330. }
  331. }
  332. }),
  333. utils.defineVueVisitor(context, {
  334. onVueObjectEnter(node) {
  335. propsMap.set(node, {
  336. set: new Set(
  337. utils
  338. .getComponentPropsFromOptions(node)
  339. .map((p) => p.propName)
  340. .filter(utils.isDef)
  341. )
  342. })
  343. },
  344. onVueObjectExit(node, { type }) {
  345. if (
  346. (!vueObjectData ||
  347. (vueObjectData.type !== 'export' &&
  348. vueObjectData.type !== 'setup')) &&
  349. type !== 'instance'
  350. ) {
  351. vueObjectData = {
  352. type,
  353. object: node
  354. }
  355. }
  356. },
  357. onSetupFunctionEnter(node) {
  358. const propsParam = node.params[0]
  359. if (!propsParam) {
  360. // no arguments
  361. return
  362. }
  363. if (
  364. propsParam.type === 'RestElement' ||
  365. propsParam.type === 'ArrayPattern'
  366. ) {
  367. // cannot check
  368. return
  369. }
  370. for (const { node: prop, path } of iteratePatternProperties(
  371. propsParam,
  372. []
  373. )) {
  374. verifyPropVariable(prop, path)
  375. }
  376. },
  377. /** @param {(Identifier | ThisExpression) & { parent: MemberExpression } } node */
  378. 'MemberExpression > :matches(Identifier, ThisExpression)'(
  379. node,
  380. { node: vueNode }
  381. ) {
  382. if (!utils.isThis(node, context)) {
  383. return
  384. }
  385. const mem = node.parent
  386. if (mem.object !== node) {
  387. return
  388. }
  389. const name = utils.getStaticPropertyName(mem)
  390. if (
  391. name &&
  392. /** @type {PropsInfo} */ (propsMap.get(vueNode)).set.has(name)
  393. ) {
  394. verifyMutating(mem, name)
  395. }
  396. }
  397. }),
  398. utils.defineTemplateBodyVisitor(context, {
  399. /** @param {ThisExpression & { parent: MemberExpression } } node */
  400. 'VExpressionContainer MemberExpression > ThisExpression'(node) {
  401. if (!vueObjectData) {
  402. return
  403. }
  404. const mem = node.parent
  405. if (mem.object !== node) {
  406. return
  407. }
  408. const name = utils.getStaticPropertyName(mem)
  409. if (
  410. name &&
  411. /** @type {PropsInfo} */ (
  412. propsMap.get(vueObjectData.object)
  413. ).set.has(name)
  414. ) {
  415. verifyMutating(mem, name)
  416. }
  417. },
  418. /** @param {Identifier } node */
  419. 'VExpressionContainer Identifier'(node) {
  420. if (!vueObjectData) {
  421. return
  422. }
  423. if (!isVmReference(node)) {
  424. return
  425. }
  426. const propsInfo = /** @type {PropsInfo} */ (
  427. propsMap.get(vueObjectData.object)
  428. )
  429. const isRootProps = !!node.name && propsInfo.name === node.name
  430. const parent = node.parent
  431. const name =
  432. (isRootProps &&
  433. parent.type === 'MemberExpression' &&
  434. utils.getStaticPropertyName(parent)) ||
  435. node.name
  436. if (name && (propsInfo.set.has(name) || isRootProps)) {
  437. verifyMutating(node, name, isRootProps)
  438. }
  439. },
  440. /** @param {ESNode} node */
  441. "VAttribute[directive=true]:matches([key.name.name='model'], [key.name.name='bind']) VExpressionContainer > *"(
  442. node
  443. ) {
  444. if (!vueObjectData) {
  445. return
  446. }
  447. let attr = node.parent
  448. while (attr && attr.type !== 'VAttribute') {
  449. attr = attr.parent
  450. }
  451. if (
  452. attr &&
  453. attr.directive &&
  454. attr.key.name.name === 'bind' &&
  455. !attr.key.modifiers.some((mod) => mod.name === 'sync')
  456. ) {
  457. return
  458. }
  459. const propsInfo = /** @type {PropsInfo} */ (
  460. propsMap.get(vueObjectData.object)
  461. )
  462. const nodes = utils.getMemberChaining(node)
  463. const first = nodes[0]
  464. let name
  465. if (isVmReference(first)) {
  466. if (first.name === propsInfo.name) {
  467. // props variable
  468. if (shallowOnly && nodes.length > 2) {
  469. return
  470. }
  471. name = (nodes[1] && getPropertyNameText(nodes[1])) || first.name
  472. } else {
  473. if (shallowOnly && nodes.length > 1) {
  474. return
  475. }
  476. name = first.name
  477. if (!name || !propsInfo.set.has(name)) {
  478. return
  479. }
  480. }
  481. } else if (first.type === 'ThisExpression') {
  482. if (shallowOnly && nodes.length > 2) {
  483. return
  484. }
  485. const mem = nodes[1]
  486. if (!mem) {
  487. return
  488. }
  489. name = utils.getStaticPropertyName(mem)
  490. if (!name || !propsInfo.set.has(name)) {
  491. return
  492. }
  493. } else {
  494. return
  495. }
  496. report(node, name)
  497. }
  498. })
  499. )
  500. }
  501. }