no-restricted-call-after-await.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /**
  2. * @author Yosuke Ota
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const fs = require('fs')
  7. const path = require('path')
  8. const { ReferenceTracker } = require('@eslint-community/eslint-utils')
  9. const utils = require('../utils')
  10. /**
  11. * @typedef {import('@eslint-community/eslint-utils').TYPES.TraceMap} TraceMap
  12. * @typedef {import('@eslint-community/eslint-utils').TYPES.TraceKind} TraceKind
  13. */
  14. /**
  15. * @param {string} id
  16. */
  17. function safeRequireResolve(id) {
  18. try {
  19. if (fs.statSync(id).isDirectory()) {
  20. return require.resolve(id)
  21. }
  22. } catch (_error) {
  23. // ignore
  24. }
  25. return id
  26. }
  27. module.exports = {
  28. meta: {
  29. type: 'suggestion',
  30. docs: {
  31. description: 'disallow asynchronously called restricted methods',
  32. categories: undefined,
  33. url: 'https://eslint.vuejs.org/rules/no-restricted-call-after-await.html'
  34. },
  35. fixable: null,
  36. schema: {
  37. type: 'array',
  38. items: {
  39. type: 'object',
  40. properties: {
  41. module: { type: 'string' },
  42. path: {
  43. anyOf: [
  44. { type: 'string' },
  45. {
  46. type: 'array',
  47. items: {
  48. type: 'string'
  49. }
  50. }
  51. ]
  52. },
  53. message: { type: 'string', minLength: 1 }
  54. },
  55. required: ['module'],
  56. additionalProperties: false
  57. },
  58. uniqueItems: true,
  59. minItems: 0
  60. },
  61. messages: {
  62. // eslint-disable-next-line eslint-plugin/report-message-format
  63. restricted: '{{message}}'
  64. }
  65. },
  66. /** @param {RuleContext} context */
  67. create(context) {
  68. /**
  69. * @typedef {object} SetupScopeData
  70. * @property {boolean} afterAwait
  71. * @property {[number,number]} range
  72. */
  73. /** @type {Map<ESNode, string>} */
  74. const restrictedCallNodes = new Map()
  75. /** @type {Map<FunctionExpression | ArrowFunctionExpression | FunctionDeclaration, SetupScopeData>} */
  76. const setupScopes = new Map()
  77. /**x
  78. * @typedef {object} ScopeStack
  79. * @property {ScopeStack | null} upper
  80. * @property {FunctionExpression | ArrowFunctionExpression | FunctionDeclaration} scopeNode
  81. */
  82. /** @type {ScopeStack | null} */
  83. let scopeStack = null
  84. /** @type {Record<string, string[]> | null} */
  85. let allLocalImports = null
  86. /**
  87. * @param {Program} ast
  88. */
  89. function getAllLocalImports(ast) {
  90. if (!allLocalImports) {
  91. allLocalImports = {}
  92. const dir = path.dirname(context.getFilename())
  93. for (const body of ast.body) {
  94. if (body.type !== 'ImportDeclaration') {
  95. continue
  96. }
  97. const source = String(body.source.value)
  98. if (!source.startsWith('.')) {
  99. continue
  100. }
  101. const modulePath = safeRequireResolve(path.join(dir, source))
  102. const list =
  103. allLocalImports[modulePath] || (allLocalImports[modulePath] = [])
  104. list.push(source)
  105. }
  106. }
  107. return allLocalImports
  108. }
  109. function getCwd() {
  110. if (context.getCwd) {
  111. return context.getCwd()
  112. }
  113. return path.resolve('')
  114. }
  115. /**
  116. * @param {string} moduleName
  117. * @param {Program} ast
  118. * @returns {string[]}
  119. */
  120. function normalizeModules(moduleName, ast) {
  121. /** @type {string} */
  122. let modulePath
  123. if (moduleName.startsWith('.')) {
  124. modulePath = safeRequireResolve(path.join(getCwd(), moduleName))
  125. } else if (path.isAbsolute(moduleName)) {
  126. modulePath = safeRequireResolve(moduleName)
  127. } else {
  128. return [moduleName]
  129. }
  130. return getAllLocalImports(ast)[modulePath] || []
  131. }
  132. return utils.compositingVisitors(
  133. {
  134. /** @param {Program} node */
  135. Program(node) {
  136. const tracker = new ReferenceTracker(utils.getScope(context, node))
  137. for (const option of context.options) {
  138. const modules = normalizeModules(option.module, node)
  139. for (const module of modules) {
  140. /** @type {TraceMap} */
  141. const traceMap = {
  142. [module]: {
  143. [ReferenceTracker.ESM]: true
  144. }
  145. }
  146. /** @type {TraceKind & TraceMap} */
  147. const mod = traceMap[module]
  148. let local = mod
  149. const paths = Array.isArray(option.path)
  150. ? option.path
  151. : [option.path || 'default']
  152. for (const path of paths) {
  153. local = local[path] || (local[path] = {})
  154. }
  155. local[ReferenceTracker.CALL] = true
  156. const message =
  157. option.message ||
  158. `\`${[`import("${module}")`, ...paths].join(
  159. '.'
  160. )}\` is forbidden after an \`await\` expression.`
  161. for (const { node } of tracker.iterateEsmReferences(traceMap)) {
  162. restrictedCallNodes.set(node, message)
  163. }
  164. }
  165. }
  166. }
  167. },
  168. utils.defineVueVisitor(context, {
  169. onSetupFunctionEnter(node) {
  170. setupScopes.set(node, {
  171. afterAwait: false,
  172. range: node.range
  173. })
  174. },
  175. /** @param {FunctionExpression | ArrowFunctionExpression | FunctionDeclaration} node */
  176. ':function'(node) {
  177. scopeStack = {
  178. upper: scopeStack,
  179. scopeNode: node
  180. }
  181. },
  182. ':function:exit'() {
  183. scopeStack = scopeStack && scopeStack.upper
  184. },
  185. /** @param {AwaitExpression} node */
  186. AwaitExpression(node) {
  187. if (!scopeStack) {
  188. return
  189. }
  190. const setupScope = setupScopes.get(scopeStack.scopeNode)
  191. if (!setupScope || !utils.inRange(setupScope.range, node)) {
  192. return
  193. }
  194. setupScope.afterAwait = true
  195. },
  196. /** @param {CallExpression} node */
  197. CallExpression(node) {
  198. if (!scopeStack) {
  199. return
  200. }
  201. const setupScope = setupScopes.get(scopeStack.scopeNode)
  202. if (
  203. !setupScope ||
  204. !setupScope.afterAwait ||
  205. !utils.inRange(setupScope.range, node)
  206. ) {
  207. return
  208. }
  209. const message = restrictedCallNodes.get(node)
  210. if (message) {
  211. context.report({
  212. node,
  213. messageId: 'restricted',
  214. data: { message }
  215. })
  216. }
  217. },
  218. onSetupFunctionExit(node) {
  219. setupScopes.delete(node)
  220. }
  221. })
  222. )
  223. }
  224. }