reactStableReferences.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import { Node, Project } from "ts-morph";
  2. import { describe, expect, it } from "vitest";
  3. interface Finding {
  4. file: string;
  5. line: number;
  6. message: string;
  7. }
  8. function createProject() {
  9. const project = new Project({
  10. compilerOptions: {
  11. allowJs: true,
  12. jsx: 4,
  13. },
  14. });
  15. project.addSourceFilesAtPaths(["packages/ui/src/**/*.tsx"]);
  16. return project;
  17. }
  18. function formatFinding(finding: Finding) {
  19. return `${finding.file}:${finding.line} ${finding.message}`;
  20. }
  21. function sourceLocation(sourceFile: ReturnType<Project["getSourceFiles"]>[number], node: Node) {
  22. const { line } = sourceFile.getLineAndColumnAtPos(node.getStart());
  23. return {
  24. file: sourceFile.getFilePath().replace(`${process.cwd()}/`, ""),
  25. line,
  26. };
  27. }
  28. function getJsxTagRoot(tagName: string) {
  29. return tagName.split(".")[0] ?? tagName;
  30. }
  31. function getUnstableExpressionKind(expression: Node | undefined) {
  32. if (!expression) {
  33. return null;
  34. }
  35. if (Node.isArrowFunction(expression) || Node.isFunctionExpression(expression)) {
  36. return "function";
  37. }
  38. if (Node.isArrayLiteralExpression(expression)) {
  39. return "array";
  40. }
  41. if (Node.isObjectLiteralExpression(expression)) {
  42. return "object";
  43. }
  44. if (
  45. Node.isJsxElement(expression) ||
  46. Node.isJsxFragment(expression) ||
  47. Node.isJsxSelfClosingElement(expression)
  48. ) {
  49. return "jsx";
  50. }
  51. return null;
  52. }
  53. function collectMemoComponentNames(project: Project) {
  54. const memoComponentNames = new Set<string>();
  55. for (const sourceFile of project.getSourceFiles()) {
  56. sourceFile.forEachDescendant((node) => {
  57. if (!Node.isVariableDeclaration(node)) {
  58. return;
  59. }
  60. const initializer = node.getInitializer();
  61. if (
  62. !initializer ||
  63. !Node.isCallExpression(initializer) ||
  64. !["memo", "React.memo"].includes(initializer.getExpression().getText())
  65. ) {
  66. return;
  67. }
  68. const exportedName = node.getNameNode().getText();
  69. memoComponentNames.add(exportedName);
  70. const memoTarget = initializer.getArguments()[0];
  71. if (memoTarget && Node.isIdentifier(memoTarget)) {
  72. memoComponentNames.add(memoTarget.getText());
  73. }
  74. });
  75. }
  76. return memoComponentNames;
  77. }
  78. function collectInlinePropsForMemoComponents(project: Project) {
  79. const memoComponentNames = collectMemoComponentNames(project);
  80. const findings: Finding[] = [];
  81. for (const sourceFile of project.getSourceFiles()) {
  82. sourceFile.forEachDescendant((node) => {
  83. if (!Node.isJsxOpeningElement(node) && !Node.isJsxSelfClosingElement(node)) {
  84. return;
  85. }
  86. const tagName = node.getTagNameNode().getText();
  87. if (!memoComponentNames.has(getJsxTagRoot(tagName))) {
  88. return;
  89. }
  90. for (const attribute of node.getAttributes()) {
  91. if (!Node.isJsxAttribute(attribute)) {
  92. continue;
  93. }
  94. const initializer = attribute.getInitializer();
  95. if (!initializer || !Node.isJsxExpression(initializer)) {
  96. continue;
  97. }
  98. const unstableKind = getUnstableExpressionKind(initializer.getExpression());
  99. if (!unstableKind) {
  100. continue;
  101. }
  102. const { file, line } = sourceLocation(sourceFile, attribute);
  103. findings.push({
  104. file,
  105. line,
  106. message: `<${tagName}> prop "${attribute.getNameNode().getText()}" uses inline ${unstableKind}`,
  107. });
  108. }
  109. });
  110. }
  111. return findings;
  112. }
  113. function collectMemoComponentsWithInlineDefaults(project: Project) {
  114. const memoComponentNames = collectMemoComponentNames(project);
  115. const findings: Finding[] = [];
  116. const inspectFunction = (name: string, fn: Node) => {
  117. if (!memoComponentNames.has(name)) {
  118. return;
  119. }
  120. if (
  121. !Node.isFunctionDeclaration(fn) &&
  122. !Node.isFunctionExpression(fn) &&
  123. !Node.isArrowFunction(fn)
  124. ) {
  125. return;
  126. }
  127. const firstParameter = fn.getParameters()[0];
  128. const nameNode = firstParameter?.getNameNode();
  129. if (!nameNode || !Node.isObjectBindingPattern(nameNode)) {
  130. return;
  131. }
  132. for (const element of nameNode.getElements()) {
  133. const unstableKind = getUnstableExpressionKind(element.getInitializer());
  134. if (!unstableKind) {
  135. continue;
  136. }
  137. const sourceFile = fn.getSourceFile();
  138. const { file, line } = sourceLocation(sourceFile, element);
  139. findings.push({
  140. file,
  141. line,
  142. message: `${name} default prop "${element.getNameNode().getText()}" creates inline ${unstableKind}`,
  143. });
  144. }
  145. };
  146. for (const sourceFile of project.getSourceFiles()) {
  147. sourceFile.forEachDescendant((node) => {
  148. if (Node.isFunctionDeclaration(node)) {
  149. const name = node.getNameNode()?.getText();
  150. if (name) {
  151. inspectFunction(name, node);
  152. }
  153. return;
  154. }
  155. if (!Node.isVariableDeclaration(node)) {
  156. return;
  157. }
  158. const initializer = node.getInitializer();
  159. if (!initializer) {
  160. return;
  161. }
  162. const name = node.getNameNode().getText();
  163. if (Node.isArrowFunction(initializer) || Node.isFunctionExpression(initializer)) {
  164. inspectFunction(name, initializer);
  165. return;
  166. }
  167. if (
  168. Node.isCallExpression(initializer) &&
  169. ["memo", "React.memo"].includes(initializer.getExpression().getText())
  170. ) {
  171. const memoTarget = initializer.getArguments()[0];
  172. if (
  173. memoTarget &&
  174. (Node.isArrowFunction(memoTarget) || Node.isFunctionExpression(memoTarget))
  175. ) {
  176. inspectFunction(name, memoTarget);
  177. }
  178. }
  179. });
  180. }
  181. return findings;
  182. }
  183. function collectInlineProviderValues(project: Project) {
  184. const findings: Finding[] = [];
  185. for (const sourceFile of project.getSourceFiles()) {
  186. sourceFile.forEachDescendant((node) => {
  187. if (!Node.isJsxOpeningElement(node) && !Node.isJsxSelfClosingElement(node)) {
  188. return;
  189. }
  190. const tagName = node.getTagNameNode().getText();
  191. if (!tagName.endsWith(".Provider")) {
  192. return;
  193. }
  194. for (const attribute of node.getAttributes()) {
  195. if (!Node.isJsxAttribute(attribute) || attribute.getNameNode().getText() !== "value") {
  196. continue;
  197. }
  198. const initializer = attribute.getInitializer();
  199. const expression =
  200. initializer && Node.isJsxExpression(initializer)
  201. ? initializer.getExpression()
  202. : undefined;
  203. if (!expression || !Node.isObjectLiteralExpression(expression)) {
  204. continue;
  205. }
  206. const { file, line } = sourceLocation(sourceFile, attribute);
  207. findings.push({
  208. file,
  209. line,
  210. message: `<${tagName}> value uses inline object`,
  211. });
  212. }
  213. });
  214. }
  215. return findings;
  216. }
  217. describe("React stable reference boundaries", () => {
  218. it("does not pass inline non-primitive props into memoized components", () => {
  219. const findings = collectInlinePropsForMemoComponents(createProject());
  220. expect(findings.map(formatFinding)).toEqual([]);
  221. });
  222. it("does not create non-primitive defaults inside memoized component props", () => {
  223. const findings = collectMemoComponentsWithInlineDefaults(createProject());
  224. expect(findings.map(formatFinding)).toEqual([]);
  225. });
  226. it("does not create inline object context provider values", () => {
  227. const findings = collectInlineProviderValues(createProject());
  228. expect(findings.map(formatFinding)).toEqual([]);
  229. });
  230. });