prefer-read-only-props.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @fileoverview Require component props to be typed as read-only.
  3. * @author Luke Zapart
  4. */
  5. 'use strict';
  6. const Components = require('../util/Components');
  7. const docsUrl = require('../util/docsUrl');
  8. const report = require('../util/report');
  9. function isFlowPropertyType(node) {
  10. return node.type === 'ObjectTypeProperty';
  11. }
  12. function isCovariant(node) {
  13. return (node.variance && node.variance.kind === 'plus')
  14. || (
  15. node.parent
  16. && node.parent.parent
  17. && node.parent.parent.parent
  18. && node.parent.parent.parent.id
  19. && node.parent.parent.parent.id.name === '$ReadOnly'
  20. );
  21. }
  22. // ------------------------------------------------------------------------------
  23. // Rule Definition
  24. // ------------------------------------------------------------------------------
  25. const messages = {
  26. readOnlyProp: 'Prop \'{{name}}\' should be read-only.',
  27. };
  28. module.exports = {
  29. meta: {
  30. docs: {
  31. description: 'Enforce that props are read-only',
  32. category: 'Stylistic Issues',
  33. recommended: false,
  34. url: docsUrl('prefer-read-only-props'),
  35. },
  36. fixable: 'code',
  37. messages,
  38. schema: [],
  39. },
  40. create: Components.detect((context, components) => ({
  41. 'Program:exit'() {
  42. const list = components.list();
  43. Object.keys(list).forEach((key) => {
  44. const component = list[key];
  45. if (!component.declaredPropTypes) {
  46. return;
  47. }
  48. Object.keys(component.declaredPropTypes).forEach((propName) => {
  49. const prop = component.declaredPropTypes[propName];
  50. if (!prop.node || !isFlowPropertyType(prop.node)) {
  51. return;
  52. }
  53. if (!isCovariant(prop.node)) {
  54. report(context, messages.readOnlyProp, 'readOnlyProp', {
  55. node: prop.node,
  56. data: {
  57. name: propName,
  58. },
  59. fix: (fixer) => {
  60. if (!prop.node.variance) {
  61. // Insert covariance
  62. return fixer.insertTextBefore(prop.node, '+');
  63. }
  64. // Replace contravariance with covariance
  65. return fixer.replaceText(prop.node.variance, '+');
  66. },
  67. });
  68. }
  69. });
  70. });
  71. },
  72. })),
  73. };