@hero-design/snowflake-guard 1.2.3 → 1.2.4-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +2 -0
  2. package/lib/src/index.js +30 -22
  3. package/lib/src/parseMobileSource.d.ts +15 -0
  4. package/lib/src/parseMobileSource.js +118 -0
  5. package/lib/src/parsers/flow.d.ts +3 -0
  6. package/lib/src/parsers/flow.js +37 -0
  7. package/lib/src/reports/mobile/__tests__/reportCustomStyleProperties.spec.d.ts +1 -0
  8. package/lib/src/reports/mobile/__tests__/reportCustomStyleProperties.spec.js +123 -0
  9. package/lib/src/reports/mobile/__tests__/reportInlineStyle.spec.d.ts +1 -0
  10. package/lib/src/reports/mobile/__tests__/reportInlineStyle.spec.js +103 -0
  11. package/lib/src/reports/mobile/__tests__/reportStyledComponents.spec.d.ts +1 -0
  12. package/lib/src/reports/mobile/__tests__/reportStyledComponents.spec.js +54 -0
  13. package/lib/src/reports/mobile/constants.d.ts +260 -0
  14. package/lib/src/reports/mobile/constants.js +429 -0
  15. package/lib/src/reports/mobile/reportCustomStyleProperties.d.ts +38 -0
  16. package/lib/src/reports/mobile/reportCustomStyleProperties.js +155 -0
  17. package/lib/src/reports/mobile/reportInlineStyle.d.ts +21 -0
  18. package/lib/src/reports/mobile/reportInlineStyle.js +214 -0
  19. package/lib/src/reports/mobile/reportStyledComponents.d.ts +6 -0
  20. package/lib/src/reports/mobile/reportStyledComponents.js +95 -0
  21. package/lib/src/reports/mobile/reportToastStyle.d.ts +0 -0
  22. package/lib/src/reports/mobile/reportToastStyle.js +1 -0
  23. package/lib/src/reports/mobile/testUtils.d.ts +1 -0
  24. package/lib/src/reports/mobile/testUtils.js +32 -0
  25. package/lib/src/reports/mobile/types.d.ts +3 -0
  26. package/lib/src/reports/mobile/types.js +2 -0
  27. package/lib/src/reports/reportCustomStyleProperties.d.ts +1 -1
  28. package/lib/src/reports/reportStyledComponents.d.ts +1 -1
  29. package/package.json +2 -2
package/README.md CHANGED
@@ -10,6 +10,8 @@
10
10
  cp .env.example .env
11
11
  ```
12
12
 
13
+ For React Native projects, include your repo name in the `MOBILE_REPO_NAMES` env.
14
+
13
15
  2. Set up [internal-tool-integrations service](https://github.com/Thinkei/internal-tool-integrations) for the bot to store report.
14
16
 
15
17
  - Replace `DB_HOST` with the host of the internal-tool-integrations service.
package/lib/src/index.js CHANGED
@@ -11,12 +11,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
+ const parseMobileSource_1 = __importDefault(require("./parseMobileSource"));
14
15
  const parseSource_1 = __importDefault(require("./parseSource"));
15
16
  const constants_1 = require("./reports/constants");
16
17
  const fetchGraphql_1 = __importDefault(require("./graphql/fetchGraphql"));
17
18
  const queryGenerators_1 = require("./graphql/queryGenerators");
18
19
  const getDiffLocs_1 = require("./utils/getDiffLocs");
19
20
  const TSX_REGEX = /\.tsx$/;
21
+ const TSX_AND_JSX_REGEX = /\.(tsx|jsx|js)$/;
20
22
  const TEST_REGEX = /__tests__/;
21
23
  const SNOWFLAKE_COMMENTS = {
22
24
  style: 'Snowflake detected! A component is customized using inline styles. Make sure to not use [prohibited CSS properties](https://docs.google.com/spreadsheets/d/1Dj8vqLdFaf-CSaSVoYqyYZIkGqF6OoyP7K4G1_9L62U/edit?usp=sharing).',
@@ -24,6 +26,7 @@ const SNOWFLAKE_COMMENTS = {
24
26
  'styled-component': 'Please do not use styled-component to customize this component, use sx prop or inline style instead.',
25
27
  className: `Please make sure that this className is not used as a CSS classname for component customization purposes, use sx prop or inline style instead. In case this is none-css classname, please flag it with this comment \`${constants_1.APPROVED_CLASSNAME_COMMENT}\`.`,
26
28
  };
29
+ const MOBILE_REPO_NAMES = JSON.parse(process.env.MOBILE_REPO_NAMES || '[]');
27
30
  const checkIfDetectedSnowflakesInDiff = (diffLocs, locToComment) => {
28
31
  const locIdx = diffLocs.findIndex(([start, end]) => {
29
32
  return locToComment >= start && locToComment <= end;
@@ -42,16 +45,19 @@ module.exports = (app) => {
42
45
  const prBranch = context.payload.pull_request.head.ref;
43
46
  // List all changed files
44
47
  const prFiles = yield context.octokit.pulls.listFiles(Object.assign(Object.assign({}, repoInfo), { pull_number: prNumber }));
45
- const tsxFiles = prFiles.data.filter((file) => TSX_REGEX.test(file.filename) &&
48
+ const isMobile = MOBILE_REPO_NAMES.includes(context.payload.repository.name);
49
+ const parseSource = isMobile ? parseMobileSource_1.default : parseSource_1.default;
50
+ const SOURCE_REGEX = isMobile ? TSX_AND_JSX_REGEX : TSX_REGEX;
51
+ const sourceFiles = prFiles.data.filter((file) => SOURCE_REGEX.test(file.filename) &&
46
52
  !TEST_REGEX.test(file.filename) &&
47
53
  file.status !== 'removed');
48
54
  // Saving file patches to get diff locations
49
- const prFilePatches = tsxFiles.reduce((acc, file) => {
55
+ const prFilePatches = sourceFiles.reduce((acc, file) => {
50
56
  acc[file.filename] = file.patch || '';
51
57
  return acc;
52
58
  }, {});
53
59
  // Get file contents
54
- const prFileContentPromises = tsxFiles.map((file) => context.octokit.repos.getContent(Object.assign(Object.assign({}, repoInfo), { path: file.filename, ref: prBranch })));
60
+ const prFileContentPromises = sourceFiles.map((file) => context.octokit.repos.getContent(Object.assign(Object.assign({}, repoInfo), { path: file.filename, ref: prBranch })));
55
61
  const prFileContents = yield Promise.all(prFileContentPromises);
56
62
  const snowflakeComments = [];
57
63
  const approvedSnowflakeLocs = [];
@@ -65,7 +71,7 @@ module.exports = (app) => {
65
71
  // @ts-ignore
66
72
  file.data.content, 'base64').toString();
67
73
  // Parse file content to check for snowflakes
68
- const snowflakeReport = (0, parseSource_1.default)(stringContent);
74
+ const snowflakeReport = parseSource(stringContent);
69
75
  snowflakeReport.styleLocs.forEach((loc) => {
70
76
  if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
71
77
  snowflakeComments.push({
@@ -75,15 +81,6 @@ module.exports = (app) => {
75
81
  });
76
82
  }
77
83
  });
78
- snowflakeReport.sxLocs.forEach((loc) => {
79
- if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
80
- snowflakeComments.push({
81
- path: filePath,
82
- body: SNOWFLAKE_COMMENTS['sx'],
83
- line: loc,
84
- });
85
- }
86
- });
87
84
  snowflakeReport.styledComponentLocs.forEach((loc) => {
88
85
  if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
89
86
  snowflakeComments.push({
@@ -93,20 +90,31 @@ module.exports = (app) => {
93
90
  });
94
91
  }
95
92
  });
96
- snowflakeReport.classNameLocs.forEach((loc) => {
97
- if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
98
- snowflakeComments.push({
99
- path: filePath,
100
- body: SNOWFLAKE_COMMENTS['className'],
101
- line: loc,
102
- });
103
- }
104
- });
105
93
  snowflakeReport.approvedLocs.forEach((loc) => {
106
94
  if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
107
95
  approvedSnowflakeLocs.push(loc);
108
96
  }
109
97
  });
98
+ if (!isMobile) {
99
+ snowflakeReport.sxLocs.forEach((loc) => {
100
+ if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
101
+ snowflakeComments.push({
102
+ path: filePath,
103
+ body: SNOWFLAKE_COMMENTS['sx'],
104
+ line: loc,
105
+ });
106
+ }
107
+ });
108
+ snowflakeReport.classNameLocs.forEach((loc) => {
109
+ if (checkIfDetectedSnowflakesInDiff(diffLocs, loc)) {
110
+ snowflakeComments.push({
111
+ path: filePath,
112
+ body: SNOWFLAKE_COMMENTS['className'],
113
+ line: loc,
114
+ });
115
+ }
116
+ });
117
+ }
110
118
  }));
111
119
  // Saving report
112
120
  const snowflakeCount = snowflakeComments.length;
@@ -0,0 +1,15 @@
1
+ import { InlineStyleProps } from './reports/mobile/reportInlineStyle';
2
+ import type { CompoundMobileComponentName } from './reports/mobile/types';
3
+ declare const parseMobileSource: (source: string) => {
4
+ styleLocs: number[];
5
+ styledComponentLocs: number[];
6
+ approvedLocs: number[];
7
+ violatingAttributes: {
8
+ attributeName: string;
9
+ attributeValue: string | null;
10
+ inlineStyleProps: InlineStyleProps;
11
+ componentName: CompoundMobileComponentName;
12
+ loc: number | undefined;
13
+ }[];
14
+ };
15
+ export default parseMobileSource;
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const recast = __importStar(require("recast"));
30
+ const flowParser = __importStar(require("./parsers/flow"));
31
+ const tsParser = __importStar(require("./parsers/typescript"));
32
+ const constants_1 = require("./reports/mobile/constants");
33
+ const constants_2 = require("./reports/constants");
34
+ const reportCustomStyleProperties_1 = __importDefault(require("./reports/mobile/reportCustomStyleProperties"));
35
+ const reportStyledComponents_1 = __importDefault(require("./reports/mobile/reportStyledComponents"));
36
+ const parseMobileSource = (source) => {
37
+ let hasHeroDesignImport = false;
38
+ let hasStyledComponentsImport = false;
39
+ const componentList = {};
40
+ let styledAliasName = 'styled';
41
+ let styledComponentLocs = [];
42
+ let styleLocs = [];
43
+ let violatingAttributes = [];
44
+ const approvedInlineStyleCmts = [];
45
+ const approvedStyledComponentLocs = [];
46
+ const ast = recast.parse(source, {
47
+ parser: source.includes('@flow') ? flowParser : tsParser,
48
+ });
49
+ recast.visit(ast, {
50
+ visitImportDeclaration(path) {
51
+ this.traverse(path);
52
+ const importedFrom = path.value.source.value;
53
+ // Check if file imports components from '@hero-design/rn'
54
+ if (importedFrom === '@hero-design/rn') {
55
+ recast.visit(path.node, {
56
+ visitImportSpecifier(importPath) {
57
+ this.traverse(importPath);
58
+ if (constants_1.HD_MOBILE_COMPONENTS.includes(importPath.value.imported.name)) {
59
+ componentList[importPath.value.local.name] =
60
+ importPath.value.imported.name;
61
+ hasHeroDesignImport = true;
62
+ }
63
+ },
64
+ });
65
+ }
66
+ // Check if file imports from '@emotion/native'
67
+ if (importedFrom === '@emotion/native') {
68
+ recast.visit(path.node, {
69
+ visitImportDefaultSpecifier(importPath) {
70
+ this.traverse(importPath);
71
+ styledAliasName = importPath.value.local.name;
72
+ hasStyledComponentsImport = true;
73
+ },
74
+ });
75
+ }
76
+ },
77
+ visitComment(path) {
78
+ this.traverse(path);
79
+ const comment = path.value.value;
80
+ if (comment
81
+ .toLowerCase()
82
+ .includes(constants_2.APPROVED_INLINE_STYLE_COMMENT.toLowerCase())) {
83
+ approvedInlineStyleCmts.push({
84
+ loc: path.value.loc.start.line,
85
+ comment,
86
+ });
87
+ }
88
+ if (comment
89
+ .toLowerCase()
90
+ .includes(constants_2.APPROVED_STYLED_COMPONENTS_COMMENT.toLowerCase())) {
91
+ approvedStyledComponentLocs.push(path.value.loc.start.line);
92
+ }
93
+ },
94
+ });
95
+ const isNotApprovedStyledComponentSnowflakes = (loc) => !approvedStyledComponentLocs.includes(loc - 1);
96
+ if (hasHeroDesignImport) {
97
+ // Case 1: Using style object to customise components
98
+ const customPropLocs = (0, reportCustomStyleProperties_1.default)(ast, componentList, {
99
+ styleCmts: approvedInlineStyleCmts,
100
+ });
101
+ styleLocs = customPropLocs.style;
102
+ // Case 2: Using styled-components to customise components
103
+ if (hasStyledComponentsImport) {
104
+ styledComponentLocs = (0, reportStyledComponents_1.default)(ast, componentList, styledAliasName).filter(isNotApprovedStyledComponentSnowflakes);
105
+ }
106
+ violatingAttributes = customPropLocs.violatingAttributes;
107
+ }
108
+ return {
109
+ styleLocs,
110
+ styledComponentLocs,
111
+ approvedLocs: [
112
+ ...approvedInlineStyleCmts.map((cmt) => cmt.loc),
113
+ ...approvedStyledComponentLocs,
114
+ ],
115
+ violatingAttributes,
116
+ };
117
+ };
118
+ exports.default = parseMobileSource;
@@ -0,0 +1,3 @@
1
+ import * as babelParser from '@babel/parser';
2
+ import { Overrides } from 'recast/parsers/_babel_options';
3
+ export declare const parse: (source: string, options?: Overrides) => babelParser.ParseResult<import("@babel/types").File>;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.parse = void 0;
30
+ const babelParser = __importStar(require("@babel/parser"));
31
+ const _babel_options_1 = __importDefault(require("recast/parsers/_babel_options"));
32
+ const parse = (source, options) => {
33
+ const babelOptions = (0, _babel_options_1.default)(options);
34
+ babelOptions.plugins.push('jsx', 'flow');
35
+ return babelParser.parse(source, babelOptions);
36
+ };
37
+ exports.parse = parse;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const reportCustomStyleProperties_1 = __importDefault(require("../reportCustomStyleProperties"));
7
+ const testUtils_1 = require("../testUtils");
8
+ const componentList = {
9
+ Card: 'Card',
10
+ Button: 'Button',
11
+ };
12
+ const commentList = {
13
+ styleCmts: [],
14
+ };
15
+ describe('reportCustomStyleProperties', () => {
16
+ beforeEach(() => {
17
+ jest.clearAllMocks();
18
+ });
19
+ it('should detect component with inline styles', () => {
20
+ const source = `const styles = {
21
+ card: {
22
+ padding: 10,
23
+ },
24
+ };
25
+
26
+ const App = () => (
27
+ <Card style={styles.card}>Content</Card>
28
+ );
29
+ `;
30
+ const ast = (0, testUtils_1.parseTypeScript)(source);
31
+ const result = (0, reportCustomStyleProperties_1.default)(ast, componentList, commentList);
32
+ expect(result).toEqual({
33
+ style: [8],
34
+ violatingAttributes: [
35
+ {
36
+ attributeName: 'padding',
37
+ attributeValue: '10',
38
+ componentName: 'Card',
39
+ inlineStyleProps: 'style',
40
+ loc: 8,
41
+ },
42
+ ],
43
+ });
44
+ });
45
+ it('should detect compound component with inline styles', () => {
46
+ const source = `const App = () => (
47
+ <Button.Icon style={{ padding: 10 }} />
48
+ );
49
+ `;
50
+ const ast = (0, testUtils_1.parseTypeScript)(source);
51
+ const result = (0, reportCustomStyleProperties_1.default)(ast, componentList, commentList);
52
+ expect(result).toEqual({
53
+ style: [2],
54
+ violatingAttributes: [
55
+ {
56
+ attributeName: 'padding',
57
+ attributeValue: '10',
58
+ componentName: 'Button.Icon',
59
+ inlineStyleProps: 'style',
60
+ loc: 2,
61
+ },
62
+ ],
63
+ });
64
+ });
65
+ it('should detect compound component using spread operator with inline styles', () => {
66
+ const source = `const { Icon } = Button;
67
+ const App = () => (
68
+ <Icon style={{ padding: 10 }} />
69
+ );
70
+ `;
71
+ const ast = (0, testUtils_1.parseTypeScript)(source);
72
+ const result = (0, reportCustomStyleProperties_1.default)(ast, componentList, commentList);
73
+ expect(result).toEqual({
74
+ style: [3],
75
+ violatingAttributes: [
76
+ {
77
+ attributeName: 'padding',
78
+ attributeValue: '10',
79
+ componentName: 'Button.Icon',
80
+ inlineStyleProps: 'style',
81
+ loc: 3,
82
+ },
83
+ ],
84
+ });
85
+ });
86
+ it('should not detect non-custom style properties', () => {
87
+ const source = `
88
+ const App = () => (
89
+ <Card>Content</Card>
90
+ );
91
+ `;
92
+ const ast = (0, testUtils_1.parseTypeScript)(source);
93
+ const result = (0, reportCustomStyleProperties_1.default)(ast, componentList, commentList);
94
+ expect(result).toEqual({ style: [], violatingAttributes: [] });
95
+ });
96
+ it('should ignore approved inline styles', () => {
97
+ const mockedCommentList = {
98
+ styleCmts: [
99
+ {
100
+ loc: 10,
101
+ comment: '@snowflake-guard/approved-inline-style attributes: padding',
102
+ },
103
+ ],
104
+ };
105
+ const source = `
106
+ const styles = {
107
+ button: {
108
+ padding: 10,
109
+ },
110
+ };
111
+
112
+ const App = () => (
113
+ <>
114
+ {/* @snowflake-guard/approved-inline-style attributes: padding */}
115
+ <Button style={styles.button} />
116
+ </>
117
+ );
118
+ `;
119
+ const ast = (0, testUtils_1.parseTypeScript)(source);
120
+ const result = (0, reportCustomStyleProperties_1.default)(ast, componentList, mockedCommentList);
121
+ expect(result).toEqual({ style: [], violatingAttributes: [] });
122
+ });
123
+ });
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const recast = __importStar(require("recast"));
30
+ const reportInlineStyle_1 = __importDefault(require("../reportInlineStyle"));
31
+ const constants_1 = require("../constants");
32
+ const tsParser = __importStar(require("../../../parsers/typescript"));
33
+ describe('reportInlineStyle', () => {
34
+ it('should return line numbers and violating attributes for inline styles that violate the ruleset', () => {
35
+ const code = `
36
+ const MyComponent = () => (
37
+ <Card style={{
38
+ color: 'red',
39
+ backgroundColor: 'blue'
40
+ }}
41
+ />
42
+ );
43
+ `;
44
+ // Step 1: Parse the code to generate the AST
45
+ const ast = recast.parse(code, { parser: tsParser });
46
+ const attributes = [];
47
+ // Step 2: Traverse the AST to extract relevant JSXAttributes (style)
48
+ recast.visit(ast, {
49
+ visitJSXAttribute(path) {
50
+ const { node } = path;
51
+ attributes.push(node);
52
+ this.traverse(path);
53
+ },
54
+ });
55
+ const componentName = 'Card';
56
+ // Mock the RULESET_MAP for this test
57
+ constants_1.MOBILE_RULESET_MAP.Card = ['color', 'backgroundColor'];
58
+ // Step 3: Run the function with the dynamically extracted attributes
59
+ const result = (0, reportInlineStyle_1.default)(ast, attributes, componentName);
60
+ expect(result.locs.style).toEqual(3);
61
+ expect(result.violatingAttributes).toEqual([
62
+ {
63
+ attributeName: 'color',
64
+ attributeValue: "'red'",
65
+ componentName: 'Card',
66
+ inlineStyleProps: 'style',
67
+ loc: 3,
68
+ },
69
+ {
70
+ attributeName: 'backgroundColor',
71
+ attributeValue: "'blue'",
72
+ componentName: 'Card',
73
+ inlineStyleProps: 'style',
74
+ loc: 3,
75
+ },
76
+ ]);
77
+ });
78
+ it('should return empty arrays when no violations are found', () => {
79
+ const code = `
80
+ const MyComponent = () => (
81
+ <Card style={{ margin: 10 }} />
82
+ );
83
+ `;
84
+ // Step 1: Parse the code to generate the AST
85
+ const ast = recast.parse(code, { parser: tsParser });
86
+ const attributes = [];
87
+ // Step 2: Traverse the AST to extract relevant JSXAttributes (style)
88
+ recast.visit(ast, {
89
+ visitJSXAttribute(path) {
90
+ const { node } = path;
91
+ attributes.push(node);
92
+ this.traverse(path);
93
+ },
94
+ });
95
+ const componentName = 'Card';
96
+ // Mock the RULESET_MAP and SX_RULESET_MAP for this test
97
+ constants_1.MOBILE_RULESET_MAP.Card = ['color'];
98
+ const result = (0, reportInlineStyle_1.default)(ast, attributes, componentName);
99
+ expect(result.locs.style).toEqual(undefined);
100
+ expect(result.violatingAttributes).toEqual([]);
101
+ expect(result.violatingAttributes).toEqual([]);
102
+ });
103
+ });
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const reportStyledComponents_1 = __importDefault(require("../reportStyledComponents"));
7
+ const testUtils_1 = require("../testUtils");
8
+ const componentList = {
9
+ Button: 'Button',
10
+ Alert: 'Alert',
11
+ };
12
+ const styledAliasName = 'styled';
13
+ describe('reportStyledComponents', () => {
14
+ it('should detect styled components with default component', () => {
15
+ const source = `
16
+ const StyledCard = styled(Button)\`
17
+ padding: 10px;
18
+ \`;
19
+ `;
20
+ const ast = (0, testUtils_1.parseTypeScript)(source);
21
+ const locs = (0, reportStyledComponents_1.default)(ast, componentList, styledAliasName);
22
+ expect(locs).toEqual([2]);
23
+ });
24
+ it('should detect styled components with compound component', () => {
25
+ const source = `
26
+ const StyledCardIcon = styled(Button.Icon)\`
27
+ padding: 10px;
28
+ \`;
29
+ `;
30
+ const ast = (0, testUtils_1.parseTypeScript)(source);
31
+ const locs = (0, reportStyledComponents_1.default)(ast, componentList, styledAliasName);
32
+ expect(locs).toEqual([2]);
33
+ });
34
+ it('should detect styled components with spread operator', () => {
35
+ const source = `
36
+ const { Icon } = Button;
37
+ const StyledIcon = styled(Icon)\`
38
+ color: red;
39
+ \`;
40
+ <StyledIcon />;
41
+ `;
42
+ const ast = (0, testUtils_1.parseTypeScript)(source);
43
+ const locs = (0, reportStyledComponents_1.default)(ast, componentList, styledAliasName);
44
+ expect(locs).toEqual([3]);
45
+ });
46
+ it('should not detect non-styled components', () => {
47
+ const source = `
48
+ const NotStyled = Button;
49
+ `;
50
+ const ast = (0, testUtils_1.parseTypeScript)(source);
51
+ const locs = (0, reportStyledComponents_1.default)(ast, componentList, styledAliasName);
52
+ expect(locs).toEqual([]);
53
+ });
54
+ });