requireReadonlyReactProps.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports["default"] = void 0;
  6. var _lodash = _interopRequireDefault(require("lodash"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  8. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  9. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  10. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  11. var schema = [{
  12. additionalProperties: false,
  13. properties: {
  14. useImplicitExactTypes: {
  15. type: 'boolean'
  16. }
  17. },
  18. type: 'object'
  19. }];
  20. var reComponentName = /^(Pure)?Component$/;
  21. var reReadOnly = /^\$(ReadOnly|FlowFixMe)$/;
  22. var isReactComponent = function isReactComponent(node) {
  23. if (!node.superClass) {
  24. return false;
  25. }
  26. return (// class Foo extends Component { }
  27. // class Foo extends PureComponent { }
  28. node.superClass.type === 'Identifier' && reComponentName.test(node.superClass.name) // class Foo extends React.Component { }
  29. // class Foo extends React.PureComponent { }
  30. || node.superClass.type === 'MemberExpression' && node.superClass.object.name === 'React' && reComponentName.test(node.superClass.property.name)
  31. );
  32. }; // type Props = {| +foo: string |}
  33. var isReadOnlyObjectType = function isReadOnlyObjectType(node, _ref) {
  34. var useImplicitExactTypes = _ref.useImplicitExactTypes;
  35. if (!node || node.type !== 'ObjectTypeAnnotation') {
  36. return false;
  37. }
  38. if (node.properties.length === 0) {
  39. // we consider `{}` to be ReadOnly since it's exact
  40. // AND has no props (when `implicitExactTypes=true`)
  41. // we consider `{||}` to be ReadOnly since it's exact
  42. // AND has no props (when `implicitExactTypes=false`)
  43. if (useImplicitExactTypes === true && node.exact === false) {
  44. return true;
  45. }
  46. if (node.exact === true) {
  47. return true;
  48. }
  49. } // { +foo: ..., +bar: ..., ... }
  50. return node.properties.length > 0 && node.properties.every(function (prop) {
  51. return prop.variance && prop.variance.kind === 'plus';
  52. });
  53. }; // type Props = {| +foo: string |} | {| +bar: number |}
  54. var isReadOnlyObjectUnionType = function isReadOnlyObjectUnionType(node, options) {
  55. if (!node || node.type !== 'UnionTypeAnnotation') {
  56. return false;
  57. }
  58. return node.types.every(function (type) {
  59. return isReadOnlyObjectType(type, options);
  60. });
  61. };
  62. var isReadOnlyType = function isReadOnlyType(node, options) {
  63. return node.right.id && reReadOnly.test(node.right.id.name) || isReadOnlyObjectType(node.right, options) || isReadOnlyObjectUnionType(node.right, options);
  64. };
  65. var create = function create(context) {
  66. var useImplicitExactTypes = _lodash["default"].get(context, ['options', 0, 'useImplicitExactTypes'], false);
  67. var options = {
  68. useImplicitExactTypes: useImplicitExactTypes
  69. };
  70. var readOnlyTypes = [];
  71. var foundTypes = [];
  72. var reportedFunctionalComponents = [];
  73. var isReadOnlyClassProp = function isReadOnlyClassProp(node) {
  74. var id = node.superTypeParameters && node.superTypeParameters.params[0].id;
  75. return id && !reReadOnly.test(id.name) && !readOnlyTypes.includes(id.name) && foundTypes.includes(id.name);
  76. };
  77. var _iterator = _createForOfIteratorHelper(context.getSourceCode().ast.body),
  78. _step;
  79. try {
  80. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  81. var node = _step.value;
  82. var idName = void 0;
  83. var typeNode = void 0; // type Props = $ReadOnly<{}>
  84. if (node.type === 'TypeAlias') {
  85. idName = node.id.name;
  86. typeNode = node; // export type Props = $ReadOnly<{}>
  87. } else if (node.type === 'ExportNamedDeclaration' && node.declaration && node.declaration.type === 'TypeAlias') {
  88. idName = node.declaration.id.name;
  89. typeNode = node.declaration;
  90. }
  91. if (idName) {
  92. foundTypes.push(idName);
  93. if (isReadOnlyType(typeNode, options)) {
  94. readOnlyTypes.push(idName);
  95. }
  96. }
  97. }
  98. } catch (err) {
  99. _iterator.e(err);
  100. } finally {
  101. _iterator.f();
  102. }
  103. return {
  104. // class components
  105. ClassDeclaration: function ClassDeclaration(node) {
  106. if (isReactComponent(node) && isReadOnlyClassProp(node)) {
  107. context.report({
  108. message: "".concat(node.superTypeParameters.params[0].id.name, " must be $ReadOnly"),
  109. node: node
  110. });
  111. } else if (node.superTypeParameters && node.superTypeParameters.params[0].type === 'ObjectTypeAnnotation' && !isReadOnlyObjectType(node.superTypeParameters.params[0], options)) {
  112. context.report({
  113. message: "".concat(node.id.name, " class props must be $ReadOnly"),
  114. node: node
  115. });
  116. }
  117. },
  118. // functional components
  119. JSXElement: function JSXElement(node) {
  120. var currentNode = node;
  121. while (currentNode && currentNode.type !== 'FunctionDeclaration') {
  122. currentNode = currentNode.parent;
  123. } // functional components can only have 1 param
  124. if (!currentNode || currentNode.params.length !== 1) {
  125. return;
  126. }
  127. var typeAnnotation = currentNode.params[0].typeAnnotation;
  128. if (currentNode.params[0].type === 'Identifier' && typeAnnotation) {
  129. var identifier = typeAnnotation.typeAnnotation.id;
  130. if (identifier && foundTypes.includes(identifier.name) && !readOnlyTypes.includes(identifier.name) && !reReadOnly.test(identifier.name)) {
  131. if (reportedFunctionalComponents.includes(identifier)) {
  132. return;
  133. }
  134. context.report({
  135. message: "".concat(identifier.name, " must be $ReadOnly"),
  136. node: identifier
  137. });
  138. reportedFunctionalComponents.push(identifier);
  139. return;
  140. }
  141. if (typeAnnotation.typeAnnotation.type === 'ObjectTypeAnnotation' && !isReadOnlyObjectType(typeAnnotation.typeAnnotation, options)) {
  142. context.report({
  143. message: "".concat(currentNode.id.name, " component props must be $ReadOnly"),
  144. node: node
  145. });
  146. }
  147. }
  148. }
  149. };
  150. };
  151. var _default = {
  152. create: create,
  153. schema: schema
  154. };
  155. exports["default"] = _default;
  156. module.exports = exports.default;