no-async-in-computed-properties.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /**
  2. * @fileoverview Check if there are no asynchronous actions inside computed properties.
  3. * @author Armano
  4. */
  5. 'use strict'
  6. const { ReferenceTracker } = require('eslint-utils')
  7. const utils = require('../utils')
  8. /**
  9. * @typedef {import('../utils').VueObjectData} VueObjectData
  10. * @typedef {import('../utils').VueVisitor} VueVisitor
  11. * @typedef {import('../utils').ComponentComputedProperty} ComponentComputedProperty
  12. */
  13. const PROMISE_FUNCTIONS = new Set(['then', 'catch', 'finally'])
  14. const PROMISE_METHODS = new Set(['all', 'race', 'reject', 'resolve'])
  15. const TIMED_FUNCTIONS = new Set([
  16. 'setTimeout',
  17. 'setInterval',
  18. 'setImmediate',
  19. 'requestAnimationFrame'
  20. ])
  21. /**
  22. * @param {CallExpression} node
  23. */
  24. function isTimedFunction(node) {
  25. const callee = utils.skipChainExpression(node.callee)
  26. return (
  27. ((callee.type === 'Identifier' && TIMED_FUNCTIONS.has(callee.name)) ||
  28. (callee.type === 'MemberExpression' &&
  29. callee.object.type === 'Identifier' &&
  30. callee.object.name === 'window' &&
  31. TIMED_FUNCTIONS.has(utils.getStaticPropertyName(callee) || ''))) &&
  32. node.arguments.length > 0
  33. )
  34. }
  35. /**
  36. * @param {CallExpression} node
  37. */
  38. function isPromise(node) {
  39. const callee = utils.skipChainExpression(node.callee)
  40. if (callee.type === 'MemberExpression') {
  41. const name = utils.getStaticPropertyName(callee)
  42. return (
  43. name &&
  44. // hello.PROMISE_FUNCTION()
  45. (PROMISE_FUNCTIONS.has(name) ||
  46. // Promise.PROMISE_METHOD()
  47. (callee.object.type === 'Identifier' &&
  48. callee.object.name === 'Promise' &&
  49. PROMISE_METHODS.has(name)))
  50. )
  51. }
  52. return false
  53. }
  54. /**
  55. * @param {CallExpression} node
  56. * @param {RuleContext} context
  57. */
  58. function isNextTick(node, context) {
  59. const callee = utils.skipChainExpression(node.callee)
  60. if (callee.type === 'MemberExpression') {
  61. const name = utils.getStaticPropertyName(callee)
  62. return (
  63. (utils.isThis(callee.object, context) && name === '$nextTick') ||
  64. (callee.object.type === 'Identifier' &&
  65. callee.object.name === 'Vue' &&
  66. name === 'nextTick')
  67. )
  68. }
  69. return false
  70. }
  71. // ------------------------------------------------------------------------------
  72. // Rule Definition
  73. // ------------------------------------------------------------------------------
  74. module.exports = {
  75. meta: {
  76. type: 'problem',
  77. docs: {
  78. description: 'disallow asynchronous actions in computed properties',
  79. categories: ['vue3-essential', 'essential'],
  80. url: 'https://eslint.vuejs.org/rules/no-async-in-computed-properties.html'
  81. },
  82. fixable: null,
  83. schema: []
  84. },
  85. /** @param {RuleContext} context */
  86. create(context) {
  87. /** @type {Map<ObjectExpression, ComponentComputedProperty[]>} */
  88. const computedPropertiesMap = new Map()
  89. /** @type {(FunctionExpression | ArrowFunctionExpression)[]} */
  90. const computedFunctionNodes = []
  91. /**
  92. * @typedef {object} ScopeStack
  93. * @property {ScopeStack | null} upper
  94. * @property {BlockStatement | Expression} body
  95. */
  96. /** @type {ScopeStack | null} */
  97. let scopeStack = null
  98. const expressionTypes = {
  99. promise: 'asynchronous action',
  100. nextTick: 'asynchronous action',
  101. await: 'await operator',
  102. async: 'async function declaration',
  103. new: 'Promise object',
  104. timed: 'timed function'
  105. }
  106. /**
  107. * @param {FunctionExpression | FunctionDeclaration | ArrowFunctionExpression} node
  108. * @param {VueObjectData|undefined} [info]
  109. */
  110. function onFunctionEnter(node, info) {
  111. if (node.async) {
  112. verify(
  113. node,
  114. node.body,
  115. 'async',
  116. info ? computedPropertiesMap.get(info.node) : null
  117. )
  118. }
  119. scopeStack = {
  120. upper: scopeStack,
  121. body: node.body
  122. }
  123. }
  124. function onFunctionExit() {
  125. scopeStack = scopeStack && scopeStack.upper
  126. }
  127. /**
  128. * @param {ESNode} node
  129. * @param {BlockStatement | Expression} targetBody
  130. * @param {keyof expressionTypes} type
  131. * @param {ComponentComputedProperty[]|undefined|null} computedProperties
  132. */
  133. function verify(node, targetBody, type, computedProperties) {
  134. for (const cp of computedProperties || []) {
  135. if (
  136. cp.value &&
  137. node.loc.start.line >= cp.value.loc.start.line &&
  138. node.loc.end.line <= cp.value.loc.end.line &&
  139. targetBody === cp.value
  140. ) {
  141. context.report({
  142. node,
  143. message:
  144. 'Unexpected {{expressionName}} in "{{propertyName}}" computed property.',
  145. data: {
  146. expressionName: expressionTypes[type],
  147. propertyName: cp.key || 'unknown'
  148. }
  149. })
  150. return
  151. }
  152. }
  153. for (const cf of computedFunctionNodes) {
  154. if (
  155. node.loc.start.line >= cf.body.loc.start.line &&
  156. node.loc.end.line <= cf.body.loc.end.line &&
  157. targetBody === cf.body
  158. ) {
  159. context.report({
  160. node,
  161. message: 'Unexpected {{expressionName}} in computed function.',
  162. data: {
  163. expressionName: expressionTypes[type]
  164. }
  165. })
  166. return
  167. }
  168. }
  169. }
  170. const nodeVisitor = {
  171. ':function': onFunctionEnter,
  172. ':function:exit': onFunctionExit,
  173. /**
  174. * @param {NewExpression} node
  175. * @param {VueObjectData|undefined} [info]
  176. */
  177. NewExpression(node, info) {
  178. if (!scopeStack) {
  179. return
  180. }
  181. if (
  182. node.callee.type === 'Identifier' &&
  183. node.callee.name === 'Promise'
  184. ) {
  185. verify(
  186. node,
  187. scopeStack.body,
  188. 'new',
  189. info ? computedPropertiesMap.get(info.node) : null
  190. )
  191. }
  192. },
  193. /**
  194. * @param {CallExpression} node
  195. * @param {VueObjectData|undefined} [info]
  196. */
  197. CallExpression(node, info) {
  198. if (!scopeStack) {
  199. return
  200. }
  201. if (isPromise(node)) {
  202. verify(
  203. node,
  204. scopeStack.body,
  205. 'promise',
  206. info ? computedPropertiesMap.get(info.node) : null
  207. )
  208. } else if (isTimedFunction(node)) {
  209. verify(
  210. node,
  211. scopeStack.body,
  212. 'timed',
  213. info ? computedPropertiesMap.get(info.node) : null
  214. )
  215. } else if (isNextTick(node, context)) {
  216. verify(
  217. node,
  218. scopeStack.body,
  219. 'nextTick',
  220. info ? computedPropertiesMap.get(info.node) : null
  221. )
  222. }
  223. },
  224. /**
  225. * @param {AwaitExpression} node
  226. * @param {VueObjectData|undefined} [info]
  227. */
  228. AwaitExpression(node, info) {
  229. if (!scopeStack) {
  230. return
  231. }
  232. verify(
  233. node,
  234. scopeStack.body,
  235. 'await',
  236. info ? computedPropertiesMap.get(info.node) : null
  237. )
  238. }
  239. }
  240. return utils.compositingVisitors(
  241. {
  242. Program() {
  243. const tracker = new ReferenceTracker(context.getScope())
  244. const traceMap = utils.createCompositionApiTraceMap({
  245. [ReferenceTracker.ESM]: true,
  246. computed: {
  247. [ReferenceTracker.CALL]: true
  248. }
  249. })
  250. for (const { node } of tracker.iterateEsmReferences(traceMap)) {
  251. if (node.type !== 'CallExpression') {
  252. continue
  253. }
  254. const getter = utils.getGetterBodyFromComputedFunction(node)
  255. if (getter) {
  256. computedFunctionNodes.push(getter)
  257. }
  258. }
  259. }
  260. },
  261. utils.isScriptSetup(context)
  262. ? utils.defineScriptSetupVisitor(context, nodeVisitor)
  263. : utils.defineVueVisitor(context, {
  264. onVueObjectEnter(node) {
  265. computedPropertiesMap.set(node, utils.getComputedProperties(node))
  266. },
  267. ...nodeVisitor
  268. })
  269. )
  270. }
  271. }