max-template-depth.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * @author kevsommer Kevin Sommer
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. module.exports = {
  7. meta: {
  8. type: 'problem',
  9. docs: {
  10. description: 'enforce maximum depth of template',
  11. categories: undefined,
  12. url: 'https://eslint.vuejs.org/rules/max-template-depth.html'
  13. },
  14. fixable: null,
  15. schema: [
  16. {
  17. type: 'object',
  18. properties: {
  19. maxDepth: {
  20. type: 'integer',
  21. minimum: 1
  22. }
  23. },
  24. additionalProperties: false,
  25. minProperties: 1
  26. }
  27. ],
  28. messages: {
  29. templateTooDeep:
  30. 'Element is nested too deeply (depth of {{depth}}, maximum allowed is {{limit}}).'
  31. }
  32. },
  33. /** @param {RuleContext} context */
  34. create(context) {
  35. const option = context.options[0] || {}
  36. /**
  37. * @param {VElement} element
  38. * @param {number} curDepth
  39. */
  40. function checkMaxDepth(element, curDepth) {
  41. if (curDepth > option.maxDepth) {
  42. context.report({
  43. node: element,
  44. messageId: 'templateTooDeep',
  45. data: {
  46. depth: curDepth,
  47. limit: option.maxDepth
  48. }
  49. })
  50. }
  51. if (!element.children) {
  52. return
  53. }
  54. for (const child of element.children) {
  55. if (child.type === 'VElement') {
  56. checkMaxDepth(child, curDepth + 1)
  57. }
  58. }
  59. }
  60. return {
  61. /** @param {Program} program */
  62. Program(program) {
  63. const element = program.templateBody
  64. if (element == null) {
  65. return
  66. }
  67. if (element.type !== 'VElement') {
  68. return
  69. }
  70. checkMaxDepth(element, 0)
  71. }
  72. }
  73. }
  74. }