@backstage/eslint-plugin 0.0.0-nightly-20230207022622

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.
@@ -0,0 +1,85 @@
1
+ /*
2
+ * Copyright 2023 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // @ts-check
18
+
19
+ const path = require('path');
20
+ const visitImports = require('../lib/visitImports');
21
+ const getPackageMap = require('../lib/getPackages');
22
+
23
+ /** @type {import('eslint').Rule.RuleModule} */
24
+ module.exports = {
25
+ meta: {
26
+ type: 'problem',
27
+ messages: {
28
+ outside: 'Import of {{path}} is outside of any known monorepo package',
29
+ forbidden:
30
+ "Relative imports of monorepo packages are forbidden, use '{{newImport}}' instead",
31
+ },
32
+ docs: {
33
+ description:
34
+ 'Forbid relative imports that reach outside of the package in a monorepo.',
35
+ url: 'https://github.com/backstage/backstage/blob/master/packages/eslint-plugin/docs/rules/no-relative-monorepo-imports.md',
36
+ },
37
+ },
38
+ create(context) {
39
+ const packages = getPackageMap(context.getCwd());
40
+ if (!packages) {
41
+ return {};
42
+ }
43
+ const filePath = context.getPhysicalFilename
44
+ ? context.getPhysicalFilename()
45
+ : context.getFilename();
46
+
47
+ const localPkg = packages.byPath(filePath);
48
+ if (!localPkg) {
49
+ return {};
50
+ }
51
+
52
+ return visitImports(context, (node, imp) => {
53
+ if (imp.type !== 'local') {
54
+ return;
55
+ }
56
+
57
+ const target = path.resolve(path.dirname(filePath), imp.path);
58
+ if (!path.relative(localPkg.dir, target).startsWith('..')) {
59
+ return;
60
+ }
61
+
62
+ const targetPkg = packages.byPath(target);
63
+ if (!targetPkg) {
64
+ context.report({
65
+ node: node,
66
+ messageId: 'outside',
67
+ data: {
68
+ path: target,
69
+ },
70
+ });
71
+ return;
72
+ }
73
+
74
+ const targetPath = path.relative(targetPkg.dir, target);
75
+ const targetName = targetPkg.packageJson.name ?? '<unknown>';
76
+ context.report({
77
+ node: node,
78
+ messageId: 'forbidden',
79
+ data: {
80
+ newImport: targetPath ? `${targetName}/${targetPath}` : targetName,
81
+ },
82
+ });
83
+ });
84
+ },
85
+ };
@@ -0,0 +1,205 @@
1
+ /*
2
+ * Copyright 2023 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // @ts-check
18
+
19
+ const path = require('path');
20
+ const getPackageMap = require('../lib/getPackages');
21
+ const visitImports = require('../lib/visitImports');
22
+ const minimatch = require('minimatch');
23
+
24
+ const depFields = {
25
+ dep: 'dependencies',
26
+ dev: 'devDependencies',
27
+ peer: 'peerDependencies',
28
+ };
29
+
30
+ const devModulePatterns = [
31
+ new minimatch.Minimatch('!src/**'),
32
+ new minimatch.Minimatch('src/**/*.test.*'),
33
+ new minimatch.Minimatch('src/**/*.stories.*'),
34
+ new minimatch.Minimatch('src/**/__testUtils__/**'),
35
+ new minimatch.Minimatch('src/**/__mocks__/**'),
36
+ new minimatch.Minimatch('src/setupTests.*'),
37
+ ];
38
+
39
+ function getExpectedDepType(
40
+ /** @type {any} */ localPkg,
41
+ /** @type {string} */ impPath,
42
+ /** @type {string} */ modulePath,
43
+ ) {
44
+ const role = localPkg?.backstage?.role;
45
+ // Some package roles have known dependency types
46
+ switch (role) {
47
+ case 'common-library':
48
+ case 'web-library':
49
+ case 'frontend-plugin':
50
+ case 'frontend-plugin-module':
51
+ case 'node-library':
52
+ case 'backend-plugin':
53
+ case 'backend-plugin-module':
54
+ switch (impPath) {
55
+ case 'react':
56
+ case 'react-dom':
57
+ case 'react-router':
58
+ case 'react-router-dom':
59
+ return 'peer';
60
+ }
61
+ break;
62
+ case 'cli':
63
+ case 'frontend':
64
+ case 'backend':
65
+ default:
66
+ break;
67
+ }
68
+
69
+ for (const pattern of devModulePatterns) {
70
+ if (pattern.match(modulePath)) {
71
+ return 'dev';
72
+ }
73
+ }
74
+ return 'dep';
75
+ }
76
+
77
+ /**
78
+ *
79
+ * @param {import('@manypkg/get-packages').Package['packageJson']} pkg
80
+ * @param {string} name
81
+ * @param {ReturnType<typeof getExpectedDepType>} expectedType
82
+ * @returns {{oldDepsField?: string, depsField: string} | undefined}
83
+ */
84
+ function findConflict(pkg, name, expectedType) {
85
+ const isDep = pkg.dependencies?.[name];
86
+ const isDevDep = pkg.devDependencies?.[name];
87
+ const isPeerDep = pkg.peerDependencies?.[name];
88
+ const depsField = depFields[expectedType];
89
+
90
+ if (expectedType === 'dep' && !isDep && !isPeerDep) {
91
+ const oldDepsField = isDevDep ? depFields.dev : undefined;
92
+ return { oldDepsField, depsField };
93
+ } else if (expectedType === 'dev' && !isDevDep && !isDep && !isPeerDep) {
94
+ return { oldDepsField: undefined, depsField };
95
+ } else if (expectedType === 'peer' && !isPeerDep) {
96
+ const oldDepsField = isDep
97
+ ? depFields.dep
98
+ : isDevDep
99
+ ? depFields.dev
100
+ : undefined;
101
+
102
+ return { oldDepsField, depsField };
103
+ }
104
+ return undefined;
105
+ }
106
+
107
+ /**
108
+ * @param {string} depsField
109
+ */
110
+ function getAddFlagForDepsField(depsField) {
111
+ switch (depsField) {
112
+ case depFields.dep:
113
+ return '';
114
+ case depFields.dev:
115
+ return ' --dev';
116
+ case depFields.peer:
117
+ return ' --peer';
118
+ default:
119
+ return '';
120
+ }
121
+ }
122
+
123
+ /** @type {import('eslint').Rule.RuleModule} */
124
+ module.exports = {
125
+ meta: {
126
+ type: 'problem',
127
+ messages: {
128
+ undeclared:
129
+ "{{ packageName }} must be declared in {{ depsField }} of {{ packageJsonPath }}, run 'yarn --cwd {{ packagePath }} add{{ addFlag }} {{ packageName }}' from the project root.",
130
+ switch:
131
+ '{{ packageName }} is declared in {{ oldDepsField }}, but should be moved to {{ depsField }} in {{ packageJsonPath }}.',
132
+ },
133
+ docs: {
134
+ description:
135
+ 'Forbid imports of external packages that have not been declared in the appropriate dependencies field in `package.json`.',
136
+ url: 'https://github.com/backstage/backstage/blob/master/packages/eslint-plugin/docs/rules/no-undeclared-imports.md',
137
+ },
138
+ },
139
+ create(context) {
140
+ const packages = getPackageMap(context.getCwd());
141
+ if (!packages) {
142
+ return {};
143
+ }
144
+ const filePath = context.getPhysicalFilename
145
+ ? context.getPhysicalFilename()
146
+ : context.getFilename();
147
+
148
+ const localPkg = packages.byPath(filePath);
149
+ if (!localPkg) {
150
+ return {};
151
+ }
152
+
153
+ return visitImports(context, (node, imp) => {
154
+ if (imp.type !== 'external') {
155
+ return;
156
+ }
157
+ // We leave checking of type imports to the repo-tools check
158
+ if (imp.kind === 'type') {
159
+ return;
160
+ }
161
+
162
+ const modulePath = path.relative(localPkg.dir, filePath);
163
+ const expectedType = getExpectedDepType(
164
+ localPkg.packageJson,
165
+ imp.packageName,
166
+ modulePath,
167
+ );
168
+
169
+ const conflict = findConflict(
170
+ localPkg.packageJson,
171
+ imp.packageName,
172
+ expectedType,
173
+ );
174
+
175
+ if (conflict) {
176
+ try {
177
+ const fullImport = imp.path
178
+ ? `${imp.packageName}/${imp.path}`
179
+ : imp.packageName;
180
+ require.resolve(fullImport, {
181
+ paths: [localPkg.dir],
182
+ });
183
+ } catch {
184
+ // If the dependency doesn't resolve then it's likely a type import, ignore
185
+ return;
186
+ }
187
+
188
+ const packagePath = path.relative(packages.root.dir, localPkg.dir);
189
+ const packageJsonPath = path.join(packagePath, 'package.json');
190
+
191
+ context.report({
192
+ node,
193
+ messageId: conflict.oldDepsField ? 'switch' : 'undeclared',
194
+ data: {
195
+ ...conflict,
196
+ packagePath,
197
+ addFlag: getAddFlagForDepsField(conflict.depsField),
198
+ packageName: imp.packageName,
199
+ packageJsonPath: packageJsonPath,
200
+ },
201
+ });
202
+ }
203
+ });
204
+ },
205
+ };
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "root",
3
+ "workspaces": [
4
+ "packages/*"
5
+ ]
6
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@internal/bar",
3
+ "exports": {
4
+ ".": "./src/index.ts",
5
+ "./BarPage": "./src/components/Bar.tsx",
6
+ "./package.json": "./package.json"
7
+ },
8
+ "backstage": {
9
+ "role": "frontend-plugin"
10
+ },
11
+ "dependencies": {
12
+ "react-router": "*"
13
+ },
14
+ "devDependencies": {
15
+ "react-router-dom": "*"
16
+ }
17
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@internal/foo",
3
+ "dependencies": {
4
+ "@internal/bar": "1.0.0"
5
+ },
6
+ "devDependencies": {
7
+ "lodash": "*"
8
+ },
9
+ "peerDependencies": {
10
+ "react": "*"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "type-utils"
15
+ ]
16
+ }
@@ -0,0 +1,120 @@
1
+ /*
2
+ * Copyright 2023 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { RuleTester } from 'eslint';
18
+ import path from 'path';
19
+ import rule from '../rules/no-forbidden-package-imports';
20
+
21
+ const RULE = 'no-forbidden-package-imports';
22
+ const FIXTURE = path.resolve(__dirname, '__fixtures__/monorepo');
23
+
24
+ const ERR = (name: string, path: string) => ({
25
+ message: `${name} does not export ${path}`,
26
+ });
27
+
28
+ process.chdir(FIXTURE);
29
+
30
+ const ruleTester = new RuleTester({
31
+ parserOptions: {
32
+ sourceType: 'module',
33
+ ecmaVersion: 2021,
34
+ },
35
+ });
36
+
37
+ ruleTester.run(RULE, rule, {
38
+ valid: [
39
+ {
40
+ code: `import '@internal/foo'`,
41
+ filename: path.join(FIXTURE, 'index.ts'),
42
+ },
43
+ {
44
+ code: `import '@internal/foo/type-utils'`,
45
+ filename: path.join(FIXTURE, 'index.ts'),
46
+ },
47
+ {
48
+ code: `import '@internal/foo/type-utils/anything'`,
49
+ filename: path.join(FIXTURE, 'index.ts'),
50
+ },
51
+ {
52
+ code: `import '@internal/foo/package.json'`,
53
+ filename: path.join(FIXTURE, 'index.ts'),
54
+ },
55
+ {
56
+ code: `import '@internal/bar'`,
57
+ filename: path.join(FIXTURE, 'index.ts'),
58
+ },
59
+ {
60
+ code: `import '@internal/bar/package.json'`,
61
+ filename: path.join(FIXTURE, 'index.ts'),
62
+ },
63
+ {
64
+ code: `import '@internal/bar/BarPage'`,
65
+ filename: path.join(FIXTURE, 'index.ts'),
66
+ },
67
+ ],
68
+ invalid: [
69
+ {
70
+ code: `import '@internal/foo/FooPage'`,
71
+ filename: path.join(FIXTURE, 'index.ts'),
72
+ errors: [ERR('@internal/foo', 'FooPage')],
73
+ },
74
+ {
75
+ code: `import '@internal/foo/dist'`,
76
+ filename: path.join(FIXTURE, 'index.ts'),
77
+ errors: [ERR('@internal/foo', 'dist')],
78
+ },
79
+ {
80
+ code: `import '@internal/foo/dist/FooPage'`,
81
+ filename: path.join(FIXTURE, 'index.ts'),
82
+ errors: [ERR('@internal/foo', 'dist/FooPage')],
83
+ },
84
+ {
85
+ code: `import '@internal/foo/src/FooPage'`,
86
+ filename: path.join(FIXTURE, 'index.ts'),
87
+ errors: [ERR('@internal/foo', 'src/FooPage')],
88
+ },
89
+ {
90
+ code: `import '@internal/foo/src'`,
91
+ filename: path.join(FIXTURE, 'index.ts'),
92
+ errors: [ERR('@internal/foo', 'src')],
93
+ },
94
+ {
95
+ code: `import '@internal/bar/OtherBarPage'`,
96
+ filename: path.join(FIXTURE, 'index.ts'),
97
+ errors: [ERR('@internal/bar', 'OtherBarPage')],
98
+ },
99
+ {
100
+ code: `import '@internal/bar/dist'`,
101
+ filename: path.join(FIXTURE, 'index.ts'),
102
+ errors: [ERR('@internal/bar', 'dist')],
103
+ },
104
+ {
105
+ code: `import '@internal/bar/dist/BarPage'`,
106
+ filename: path.join(FIXTURE, 'index.ts'),
107
+ errors: [ERR('@internal/bar', 'dist/BarPage')],
108
+ },
109
+ {
110
+ code: `import '@internal/bar/src/BarPage'`,
111
+ filename: path.join(FIXTURE, 'index.ts'),
112
+ errors: [ERR('@internal/bar', 'src/BarPage')],
113
+ },
114
+ {
115
+ code: `import '@internal/bar/src'`,
116
+ filename: path.join(FIXTURE, 'index.ts'),
117
+ errors: [ERR('@internal/bar', 'src')],
118
+ },
119
+ ],
120
+ });
@@ -0,0 +1,68 @@
1
+ /*
2
+ * Copyright 2023 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { RuleTester } from 'eslint';
18
+ import path from 'path';
19
+ import rule from '../rules/no-relative-monorepo-imports';
20
+
21
+ const RULE = 'no-relative-monorepo-imports';
22
+ const FIXTURE = path.resolve(__dirname, '__fixtures__/monorepo');
23
+
24
+ const ERR_OUTSIDE = (path: string) => ({
25
+ message: `Import of ${path} is outside of any known monorepo package`,
26
+ });
27
+ const ERR_FORBIDDEN = (newImp: string) => ({
28
+ message: `Relative imports of monorepo packages are forbidden, use '${newImp}' instead`,
29
+ });
30
+
31
+ process.chdir(FIXTURE);
32
+
33
+ const ruleTester = new RuleTester({
34
+ parserOptions: {
35
+ sourceType: 'module',
36
+ ecmaVersion: 2021,
37
+ },
38
+ });
39
+
40
+ ruleTester.run(RULE, rule, {
41
+ valid: [
42
+ {
43
+ code: `import { version } from '@internal/foo'`,
44
+ filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
45
+ },
46
+ {
47
+ code: `import { version } from '@internal/foo/src'`,
48
+ filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
49
+ },
50
+ ],
51
+ invalid: [
52
+ {
53
+ code: `import { version } from '../../foo'`,
54
+ filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
55
+ errors: [ERR_FORBIDDEN('@internal/foo')],
56
+ },
57
+ {
58
+ code: `import { version } from '../../foo/src'`,
59
+ filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
60
+ errors: [ERR_FORBIDDEN('@internal/foo/src')],
61
+ },
62
+ {
63
+ code: `import { version } from '../../../package.json'`,
64
+ filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
65
+ errors: [ERR_OUTSIDE(path.join(FIXTURE, 'package.json'))],
66
+ },
67
+ ],
68
+ });