@nx/eslint-plugin 24.1.0-beta.0 → 24.1.0-beta.2

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.
@@ -1,2 +1,4 @@
1
+ import directiveChecksRule from './src/rules/directive-checks';
1
2
  import enforceModuleBoundariesRule from './src/rules/enforce-module-boundaries';
3
+ export declare const directiveChecks: typeof directiveChecksRule;
2
4
  export declare const enforceModuleBoundaries: typeof enforceModuleBoundariesRule;
package/dist/internal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.enforceModuleBoundaries = void 0;
3
+ exports.enforceModuleBoundaries = exports.directiveChecks = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  // Semi-private surface for first-party Nx packages; may change without semver.
6
6
  // Rules come from here rather than `./nx`, whose `workspaceRules` initializer
@@ -9,6 +9,8 @@ const tslib_1 = require("tslib");
9
9
  // Keep the `const` assignment: `export { default as … } from` breaks the ESM
10
10
  // named import on Node below 24.14. `internal.spec.ts` pins the shape and
11
11
  // explains why.
12
+ const directive_checks_1 = tslib_1.__importDefault(require("./src/rules/directive-checks"));
12
13
  const enforce_module_boundaries_1 = tslib_1.__importDefault(require("./src/rules/enforce-module-boundaries"));
13
- // Keep the annotation: the inferred type names RuleModule via a pnpm store path (TS2883).
14
+ // Keep the annotations: the inferred types name RuleModule via a pnpm store path (TS2883).
15
+ exports.directiveChecks = directive_checks_1.default;
14
16
  exports.enforceModuleBoundaries = enforce_module_boundaries_1.default;
package/dist/nx.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  const resolve_workspace_rules_1 = require("./src/resolve-workspace-rules");
5
5
  const dependency_checks_1 = tslib_1.__importStar(require("./src/rules/dependency-checks"));
6
+ const directive_checks_1 = tslib_1.__importStar(require("./src/rules/directive-checks"));
6
7
  const enforce_module_boundaries_1 = tslib_1.__importStar(require("./src/rules/enforce-module-boundaries"));
7
8
  const nx_plugin_checks_1 = tslib_1.__importStar(require("./src/rules/nx-plugin-checks"));
8
9
  // Keep the annotation: the inferred type names RuleModule via a pnpm store path (TS2883).
@@ -12,6 +13,7 @@ const plugin = {
12
13
  [enforce_module_boundaries_1.RULE_NAME]: enforce_module_boundaries_1.default,
13
14
  [nx_plugin_checks_1.RULE_NAME]: nx_plugin_checks_1.default,
14
15
  [dependency_checks_1.RULE_NAME]: dependency_checks_1.default,
16
+ [directive_checks_1.RULE_NAME]: directive_checks_1.default,
15
17
  // Resolve any custom rules that might exist in the current workspace
16
18
  ...resolve_workspace_rules_1.workspaceRules,
17
19
  },
@@ -1,9 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
- const importPlugin = tslib_1.__importStar(require("eslint-plugin-import"));
5
4
  const globals_1 = tslib_1.__importDefault(require("globals"));
5
+ const semver_1 = require("semver");
6
6
  const typescript_eslint_1 = tslib_1.__importDefault(require("typescript-eslint"));
7
+ // ESLint v10 has no eslint-plugin-import release; v10 workspaces install the
8
+ // maintained eslint-plugin-import-x fork, whose rules are namespaced `import-x/*`.
9
+ // Require only the plugin installed for the running ESLint major.
10
+ const isEslint10OrLater = (0, semver_1.major)(require('eslint/package.json').version) >= 10;
11
+ const importPluginName = isEslint10OrLater ? 'import-x' : 'import';
12
+ const importPluginModule = isEslint10OrLater
13
+ ? require('eslint-plugin-import-x')
14
+ : require('eslint-plugin-import');
15
+ // import-x's own flat configs register its `.default`, and ESLint rejects two
16
+ // different objects under one plugin name. eslint-plugin-import has no `.default`.
17
+ const importPlugin = importPluginModule.default ?? importPluginModule;
7
18
  /**
8
19
  * This configuration is intended to be applied to ALL files within a React
9
20
  * project in an Nx workspace.
@@ -29,7 +40,7 @@ const config = typescript_eslint_1.default.config({
29
40
  '**/*.mjs',
30
41
  '**/*.jsx',
31
42
  ],
32
- plugins: { import: importPlugin },
43
+ plugins: { [importPluginName]: importPlugin },
33
44
  languageOptions: {
34
45
  globals: {
35
46
  ...globals_1.default.browser,
@@ -146,11 +157,12 @@ const config = typescript_eslint_1.default.config({
146
157
  'getter-return': 'warn',
147
158
  /**
148
159
  * Import rule configurations
149
- * https://github.com/benmosher/eslint-plugin-import
160
+ * https://github.com/import-js/eslint-plugin-import (ESLint v9 and earlier)
161
+ * https://github.com/un-ts/eslint-plugin-import-x (ESLint v10 and later)
150
162
  */
151
- 'import/first': 'error',
152
- 'import/no-amd': 'error',
153
- 'import/no-webpack-loader-syntax': 'error',
163
+ [`${importPluginName}/first`]: 'error',
164
+ [`${importPluginName}/no-amd`]: 'error',
165
+ [`${importPluginName}/no-webpack-loader-syntax`]: 'error',
154
166
  },
155
167
  });
156
168
  exports.default = config;
@@ -1,13 +1,3 @@
1
1
  import { type ConfigArray } from 'typescript-eslint';
2
- /**
3
- * This configuration is intended to be applied to ONLY files which contain JSX/TSX
4
- * code.
5
- *
6
- * It should therefore NOT contain any rules or plugins which are generic
7
- * to all file types within variants of React projects.
8
- *
9
- * This configuration is intended to be combined with other configs from this
10
- * package.
11
- */
12
- declare const config: ConfigArray;
2
+ declare let config: ConfigArray;
13
3
  export default config;
@@ -1,9 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
- const eslint_plugin_jsx_a11y_1 = tslib_1.__importDefault(require("eslint-plugin-jsx-a11y"));
5
- const eslint_plugin_react_1 = tslib_1.__importDefault(require("eslint-plugin-react"));
6
4
  const eslint_plugin_react_hooks_1 = tslib_1.__importDefault(require("eslint-plugin-react-hooks"));
5
+ const semver_1 = require("semver");
7
6
  const typescript_eslint_1 = tslib_1.__importDefault(require("typescript-eslint"));
8
7
  /**
9
8
  * This configuration is intended to be applied to ONLY files which contain JSX/TSX
@@ -15,83 +14,98 @@ const typescript_eslint_1 = tslib_1.__importDefault(require("typescript-eslint")
15
14
  * This configuration is intended to be combined with other configs from this
16
15
  * package.
17
16
  */
18
- const config = typescript_eslint_1.default.config({
19
- files: [
20
- '**/*.ts',
21
- '**/*.cts',
22
- '**/*.mts',
23
- '**/*.tsx',
24
- '**/*.js',
25
- '**/*.cjs',
26
- '**/*.mjs',
27
- '**/*.jsx',
28
- ],
29
- plugins: {
30
- 'react-hooks': eslint_plugin_react_hooks_1.default,
31
- },
32
- rules: eslint_plugin_react_hooks_1.default.configs.recommended.rules,
33
- }, {
34
- files: [
35
- '**/*.ts',
36
- '**/*.cts',
37
- '**/*.mts',
38
- '**/*.tsx',
39
- '**/*.js',
40
- '**/*.cjs',
41
- '**/*.mjs',
42
- '**/*.jsx',
43
- ],
44
- settings: { react: { version: 'detect' } },
45
- plugins: {
46
- 'jsx-a11y': eslint_plugin_jsx_a11y_1.default,
47
- react: eslint_plugin_react_1.default,
48
- },
49
- rules: {
50
- /**
51
- * React-specific rule configurations
52
- * https://github.com/yannickcr/eslint-plugin-react
53
- */
54
- 'react/forbid-foreign-prop-types': ['warn', { allowInPropTypes: true }],
55
- 'react/jsx-no-comment-textnodes': 'warn',
56
- 'react/jsx-no-duplicate-props': 'warn',
57
- 'react/jsx-no-target-blank': 'warn',
58
- 'react/jsx-no-undef': 'error',
59
- 'react/jsx-pascal-case': ['warn', { allowAllCaps: true, ignore: [] }],
60
- 'react/jsx-uses-vars': 'warn',
61
- 'react/no-danger-with-children': 'warn',
62
- 'react/no-direct-mutation-state': 'warn',
63
- 'react/no-is-mounted': 'warn',
64
- 'react/no-typos': 'error',
65
- 'react/jsx-uses-react': 'off',
66
- 'react/react-in-jsx-scope': 'off',
67
- 'react/require-render-return': 'error',
68
- 'react/style-prop-object': 'warn',
69
- 'react/jsx-no-useless-fragment': 'warn',
70
- /**
71
- * JSX Accessibility rule configurations
72
- * https://github.com/evcohen/eslint-plugin-jsx-a11y
73
- */
74
- 'jsx-a11y/accessible-emoji': 'warn',
75
- 'jsx-a11y/alt-text': 'warn',
76
- 'jsx-a11y/anchor-has-content': 'warn',
77
- 'jsx-a11y/anchor-is-valid': [
78
- 'warn',
79
- { aspects: ['noHref', 'invalidHref'] },
80
- ],
81
- 'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
82
- 'jsx-a11y/aria-props': 'warn',
83
- 'jsx-a11y/aria-proptypes': 'warn',
84
- 'jsx-a11y/aria-role': 'warn',
85
- 'jsx-a11y/aria-unsupported-elements': 'warn',
86
- 'jsx-a11y/heading-has-content': 'warn',
87
- 'jsx-a11y/iframe-has-title': 'warn',
88
- 'jsx-a11y/img-redundant-alt': 'warn',
89
- 'jsx-a11y/no-access-key': 'warn',
90
- 'jsx-a11y/no-distracting-elements': 'warn',
91
- 'jsx-a11y/no-redundant-roles': 'warn',
92
- 'jsx-a11y/role-has-required-aria-props': 'warn',
93
- 'jsx-a11y/role-supports-aria-props': 'warn',
94
- 'jsx-a11y/scope': 'warn',
95
- },
96
- });
17
+ // eslint-plugin-react and -jsx-a11y have no ESLint v10 release, so their rules
18
+ // only apply on ESLint <10. react-hooks 7.1 supports ESLint v10. Require only
19
+ // the plugins installed for the running ESLint major.
20
+ const isEslint10OrLater = (0, semver_1.major)(require('eslint/package.json').version) >= 10;
21
+ const files = [
22
+ '**/*.ts',
23
+ '**/*.cts',
24
+ '**/*.mts',
25
+ '**/*.tsx',
26
+ '**/*.js',
27
+ '**/*.cjs',
28
+ '**/*.mjs',
29
+ '**/*.jsx',
30
+ ];
31
+ let config;
32
+ if (isEslint10OrLater) {
33
+ config = typescript_eslint_1.default.config({
34
+ files,
35
+ plugins: {
36
+ 'react-hooks': eslint_plugin_react_hooks_1.default,
37
+ },
38
+ // react-hooks v7's `recommended` enables the React Compiler rules, most
39
+ // as errors; keep only the classic two rules to match ESLint <10 behavior.
40
+ rules: {
41
+ 'react-hooks/rules-of-hooks': 'error',
42
+ 'react-hooks/exhaustive-deps': 'warn',
43
+ },
44
+ });
45
+ }
46
+ else {
47
+ const jsxA11yPlugin = require('eslint-plugin-jsx-a11y');
48
+ const reactPlugin = require('eslint-plugin-react');
49
+ config = typescript_eslint_1.default.config({
50
+ files,
51
+ plugins: {
52
+ 'react-hooks': eslint_plugin_react_hooks_1.default,
53
+ },
54
+ rules: eslint_plugin_react_hooks_1.default.configs.recommended.rules,
55
+ }, {
56
+ files,
57
+ settings: { react: { version: 'detect' } },
58
+ plugins: {
59
+ 'jsx-a11y': jsxA11yPlugin,
60
+ react: reactPlugin,
61
+ },
62
+ rules: {
63
+ /**
64
+ * React-specific rule configurations
65
+ * https://github.com/yannickcr/eslint-plugin-react
66
+ */
67
+ 'react/forbid-foreign-prop-types': ['warn', { allowInPropTypes: true }],
68
+ 'react/jsx-no-comment-textnodes': 'warn',
69
+ 'react/jsx-no-duplicate-props': 'warn',
70
+ 'react/jsx-no-target-blank': 'warn',
71
+ 'react/jsx-no-undef': 'error',
72
+ 'react/jsx-pascal-case': ['warn', { allowAllCaps: true, ignore: [] }],
73
+ 'react/jsx-uses-vars': 'warn',
74
+ 'react/no-danger-with-children': 'warn',
75
+ 'react/no-direct-mutation-state': 'warn',
76
+ 'react/no-is-mounted': 'warn',
77
+ 'react/no-typos': 'error',
78
+ 'react/jsx-uses-react': 'off',
79
+ 'react/react-in-jsx-scope': 'off',
80
+ 'react/require-render-return': 'error',
81
+ 'react/style-prop-object': 'warn',
82
+ 'react/jsx-no-useless-fragment': 'warn',
83
+ /**
84
+ * JSX Accessibility rule configurations
85
+ * https://github.com/evcohen/eslint-plugin-jsx-a11y
86
+ */
87
+ 'jsx-a11y/accessible-emoji': 'warn',
88
+ 'jsx-a11y/alt-text': 'warn',
89
+ 'jsx-a11y/anchor-has-content': 'warn',
90
+ 'jsx-a11y/anchor-is-valid': [
91
+ 'warn',
92
+ { aspects: ['noHref', 'invalidHref'] },
93
+ ],
94
+ 'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
95
+ 'jsx-a11y/aria-props': 'warn',
96
+ 'jsx-a11y/aria-proptypes': 'warn',
97
+ 'jsx-a11y/aria-role': 'warn',
98
+ 'jsx-a11y/aria-unsupported-elements': 'warn',
99
+ 'jsx-a11y/heading-has-content': 'warn',
100
+ 'jsx-a11y/iframe-has-title': 'warn',
101
+ 'jsx-a11y/img-redundant-alt': 'warn',
102
+ 'jsx-a11y/no-access-key': 'warn',
103
+ 'jsx-a11y/no-distracting-elements': 'warn',
104
+ 'jsx-a11y/no-redundant-roles': 'warn',
105
+ 'jsx-a11y/role-has-required-aria-props': 'warn',
106
+ 'jsx-a11y/role-supports-aria-props': 'warn',
107
+ 'jsx-a11y/scope': 'warn',
108
+ },
109
+ });
110
+ }
97
111
  exports.default = config;
package/dist/src/index.js CHANGED
@@ -14,6 +14,7 @@ const base_1 = tslib_1.__importDefault(require("./flat-configs/base"));
14
14
  const enforce_module_boundaries_1 = tslib_1.__importStar(require("./rules/enforce-module-boundaries"));
15
15
  const nx_plugin_checks_1 = tslib_1.__importStar(require("./rules/nx-plugin-checks"));
16
16
  const dependency_checks_1 = tslib_1.__importStar(require("./rules/dependency-checks"));
17
+ const directive_checks_1 = tslib_1.__importStar(require("./rules/directive-checks"));
17
18
  // Resolve any custom rules that might exist in the current workspace
18
19
  const resolve_workspace_rules_1 = require("./resolve-workspace-rules");
19
20
  Object.defineProperty(exports, "loadWorkspaceRules", { enumerable: true, get: function () { return resolve_workspace_rules_1.loadWorkspaceRules; } });
@@ -61,6 +62,7 @@ const rules = {
61
62
  [enforce_module_boundaries_1.RULE_NAME]: enforce_module_boundaries_1.default,
62
63
  [nx_plugin_checks_1.RULE_NAME]: nx_plugin_checks_1.default,
63
64
  [dependency_checks_1.RULE_NAME]: dependency_checks_1.default,
65
+ [directive_checks_1.RULE_NAME]: directive_checks_1.default,
64
66
  ...resolve_workspace_rules_1.workspaceRules,
65
67
  };
66
68
  exports.rules = rules;
@@ -0,0 +1,9 @@
1
+ import { ESLintUtils } from '@typescript-eslint/utils';
2
+ import { type HeaderMessageId } from '../utils/directive-checks/header';
3
+ export type Options = [];
4
+ export type MessageIds = HeaderMessageId | 'unsupportedDirective' | 'unmatchedProject' | 'unmatchedProjectSuggestion';
5
+ export declare const RULE_NAME = "directive-checks";
6
+ declare const _default: ESLintUtils.RuleModule<MessageIds, [], unknown, ESLintUtils.RuleListener> & {
7
+ name: string;
8
+ };
9
+ export default _default;
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RULE_NAME = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const utils_1 = require("@typescript-eslint/utils");
6
+ const header_1 = require("../utils/directive-checks/header");
7
+ const project_patterns_1 = require("../utils/directive-checks/project-patterns");
8
+ const split_targets_1 = require("../utils/directive-checks/split-targets");
9
+ const project_graph_utils_1 = require("../utils/project-graph-utils");
10
+ const runtime_lint_utils_1 = require("../utils/runtime-lint-utils");
11
+ exports.RULE_NAME = 'directive-checks';
12
+ const VALUE_PROBLEM_DIRECTIVES = {
13
+ emptyDependsOn: 'depends-on',
14
+ ignoreServerInputsValue: 'ignore-server-inputs',
15
+ };
16
+ exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://nx.dev/docs/kb/directive-checks`)({
17
+ name: exports.RULE_NAME,
18
+ meta: {
19
+ type: 'problem',
20
+ docs: {
21
+ description: 'Checks the `@nx-` directives in the comment block that opens a file.',
22
+ },
23
+ schema: [],
24
+ messages: {
25
+ unknownDirective: '"@nx-{{name}}" is not a directive Nx reads, so Nx ignores it.',
26
+ unknownDirectiveSuggestion: '"@nx-{{name}}" is not a directive Nx reads, so Nx ignores it. Did you mean "@nx-{{suggestion}}"?',
27
+ unparsableDirective: 'Nx can\'t read this "@nx-{{name}}" directive, so it ignores it. Write it as "{{form}}".',
28
+ directiveAfterCode: 'Nx reads "@nx-{{name}}" only in the comments that open the file, on lines before any code, so it ignores this one.',
29
+ emptyDependsOn: '"@nx-depends-on" lists no projects, so Nx ignores it. List the projects the test depends on, separated by commas.',
30
+ ignoreServerInputsValue: '"@nx-ignore-server-inputs" takes no value, so Nx ignores it. Write "@nx-ignore-server-inputs" alone.',
31
+ emptyTargetName: '"@nx-target-name" is empty, so Nx ignores it.',
32
+ extraTargetName: 'Nx reads only the first "@nx-target-name", so it ignores this one.',
33
+ unsupportedDirective: 'No split task that runs this file applies "@nx-{{name}}", so Nx ignores it.',
34
+ unmatchedProject: '"{{pattern}}" matches no project.',
35
+ unmatchedProjectSuggestion: '"{{pattern}}" matches no project. Did you mean "{{suggestion}}"?',
36
+ },
37
+ },
38
+ defaultOptions: [],
39
+ create(context) {
40
+ const sourceCode = context.sourceCode;
41
+ if (!sourceCode.text.includes('@nx-')) {
42
+ return {};
43
+ }
44
+ function report(span, messageId, data) {
45
+ context.report({
46
+ loc: {
47
+ start: sourceCode.getLocFromIndex(span.start),
48
+ end: sourceCode.getLocFromIndex(span.end),
49
+ },
50
+ messageId,
51
+ data,
52
+ });
53
+ }
54
+ function reportUnsupported(lines, name) {
55
+ for (const line of lines) {
56
+ report(line, 'unsupportedDirective', { name });
57
+ }
58
+ }
59
+ function checkSplitTargets({ dependsOn, ignoreServerInputs, }) {
60
+ const ignoredByRunner = new Set();
61
+ if (dependsOn.lines.length === 0 &&
62
+ ignoreServerInputs.lines.length === 0) {
63
+ return ignoredByRunner;
64
+ }
65
+ const graph = (0, project_graph_utils_1.readProjectGraph)(exports.RULE_NAME, 'The checks that read the project graph will be skipped.');
66
+ if (!graph.projectGraph) {
67
+ return ignoredByRunner;
68
+ }
69
+ const projectPath = (0, devkit_1.normalizePath)(global.projectPath || devkit_1.workspaceRoot);
70
+ const sourceFilePath = (0, runtime_lint_utils_1.getSourceFilePath)((0, devkit_1.normalizePath)(context.filename ?? context.getFilename()), projectPath);
71
+ const sourceProject = (0, runtime_lint_utils_1.findProject)(graph.projectGraph, graph.projectRootMappings, sourceFilePath);
72
+ if (!sourceProject) {
73
+ return ignoredByRunner;
74
+ }
75
+ const targets = (0, split_targets_1.findSplitTargets)(sourceProject, sourceFilePath);
76
+ if (targets.length === 0) {
77
+ return ignoredByRunner;
78
+ }
79
+ if (dependsOn.lines.length > 0) {
80
+ if (!(0, split_targets_1.splitTargetsApply)(targets, 'depends-on')) {
81
+ reportUnsupported(dependsOn.lines, 'depends-on');
82
+ ignoredByRunner.add('depends-on');
83
+ }
84
+ else {
85
+ const unmatched = (0, project_patterns_1.findUnmatchedProjectPatterns)(dependsOn.patterns
86
+ .map(({ pattern }) => pattern)
87
+ .filter((pattern) => !pattern.startsWith('!')), graph.projectGraph);
88
+ for (const { pattern, ...span } of dependsOn.patterns) {
89
+ if (!unmatched.has(pattern)) {
90
+ continue;
91
+ }
92
+ const suggestion = unmatched.get(pattern);
93
+ if (suggestion) {
94
+ report(span, 'unmatchedProjectSuggestion', {
95
+ pattern,
96
+ suggestion,
97
+ });
98
+ }
99
+ else {
100
+ report(span, 'unmatchedProject', { pattern });
101
+ }
102
+ }
103
+ }
104
+ }
105
+ if (ignoreServerInputs.lines.length > 0 &&
106
+ !(0, split_targets_1.splitTargetsApply)(targets, 'ignore-server-inputs')) {
107
+ reportUnsupported(ignoreServerInputs.lines, 'ignore-server-inputs');
108
+ ignoredByRunner.add('ignore-server-inputs');
109
+ }
110
+ return ignoredByRunner;
111
+ }
112
+ return {
113
+ Program() {
114
+ const header = (0, header_1.checkDirectiveHeader)(sourceCode.text, sourceCode.getAllComments());
115
+ const ignoredByRunner = checkSplitTargets(header);
116
+ for (const { messageId, data, ...span } of header.problems) {
117
+ // Nx reports only that the runner ignores the directive.
118
+ if (!ignoredByRunner.has(VALUE_PROBLEM_DIRECTIVES[messageId])) {
119
+ report(span, messageId, data);
120
+ }
121
+ }
122
+ },
123
+ };
124
+ },
125
+ });
@@ -6,10 +6,10 @@ const utils_1 = require("@typescript-eslint/utils");
6
6
  const internal_1 = require("@nx/js/internal");
7
7
  const path_1 = require("path");
8
8
  const ast_utils_1 = require("../utils/ast-utils");
9
- const graph_utils_1 = require("../utils/graph-utils");
9
+ const internal_2 = require("@nx/devkit/internal");
10
+ const split_targets_1 = require("../utils/directive-checks/split-targets");
10
11
  const project_graph_utils_1 = require("../utils/project-graph-utils");
11
12
  const runtime_lint_utils_1 = require("../utils/runtime-lint-utils");
12
- const internal_2 = require("@nx/devkit/internal");
13
13
  exports.RULE_NAME = 'enforce-module-boundaries';
14
14
  exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://github.com/nrwl/nx/blob/${devkit_1.NX_VERSION}/docs/generated/packages/eslint-plugin/documents/enforce-module-boundaries.md`)({
15
15
  name: exports.RULE_NAME,
@@ -145,7 +145,7 @@ exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://github.com/nrwl
145
145
  return {};
146
146
  }
147
147
  const workspaceLayout = global.workspaceLayout;
148
- const expandedIgnoreCircularDependencies = (0, graph_utils_1.expandIgnoredCircularDependencies)(ignoredCircularDependencies, projectGraph);
148
+ const expandedIgnoreCircularDependencies = (0, internal_2.expandIgnoredCircularDependencies)(ignoredCircularDependencies, projectGraph);
149
149
  let ignoreServerInputsSpec;
150
150
  // Atomized e2e specs (`<target>--<spec path>`) with
151
151
  // `// @nx-ignore-server-inputs` import app code with bare imports
@@ -157,10 +157,9 @@ exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://github.com/nrwl
157
157
  return false;
158
158
  }
159
159
  if (ignoreServerInputsSpec === undefined) {
160
- const specPath = (0, devkit_1.normalizePath)((0, path_1.relative)(sourceProject.data.root, sourceFilePath));
161
160
  ignoreServerInputsSpec =
162
161
  (0, internal_2.hasIgnoreServerInputsDirective)(context.sourceCode.text) &&
163
- Object.keys(sourceProject.data.targets ?? {}).some((targetName) => targetName.endsWith(`--${specPath}`));
162
+ (0, split_targets_1.splitTargetsApply)((0, split_targets_1.findSplitTargets)(sourceProject, sourceFilePath), 'ignore-server-inputs');
164
163
  }
165
164
  return ignoreServerInputsSpec;
166
165
  }
@@ -280,7 +279,7 @@ exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://github.com/nrwl
280
279
  // we only allow relative paths within the same project
281
280
  // and if it's not a secondary entrypoint in an angular lib
282
281
  if (sourceProject === targetProject &&
283
- !(0, graph_utils_1.circularPathHasPair)([sourceProject, targetProject], expandedIgnoreCircularDependencies)) {
282
+ !(0, internal_2.circularPathHasPair)([sourceProject, targetProject], expandedIgnoreCircularDependencies)) {
284
283
  if (!allowCircularSelfDependency &&
285
284
  !(0, internal_2.isRelativePath)(imp) &&
286
285
  !(0, runtime_lint_utils_1.belongsToDifferentEntryPoint)(imp, sourceFilePath, sourceProject.data.root)) {
@@ -367,10 +366,10 @@ exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://github.com/nrwl
367
366
  targetProject = targetProject;
368
367
  // check constraints between libs and apps
369
368
  // check for circular dependency
370
- const circularPath = (0, graph_utils_1.checkCircularPath)(projectGraph, sourceProject, targetProject);
369
+ const circularPath = (0, internal_2.checkCircularPath)(projectGraph, sourceProject, targetProject);
371
370
  if (circularPath.length !== 0 &&
372
- !(0, graph_utils_1.circularPathHasPair)(circularPath, expandedIgnoreCircularDependencies)) {
373
- const circularFilePath = (0, graph_utils_1.findFilesInCircularPath)(projectFileMap, circularPath);
371
+ !(0, internal_2.circularPathHasPair)(circularPath, expandedIgnoreCircularDependencies)) {
372
+ const circularFilePath = (0, internal_2.findFilesInCircularPath)(projectFileMap, circularPath);
374
373
  // spacer text used for indirect dependencies when printing one line per file.
375
374
  // without this, we can end up with a very long line that does not display well in the terminal.
376
375
  const spacer = ' ';
@@ -429,7 +428,7 @@ exports.default = utils_1.ESLintUtils.RuleCreator(() => `https://github.com/nrwl
429
428
  !checkDynamicDependenciesExceptions.some((a) => (0, runtime_lint_utils_1.matchImportWithWildcard)(a, imp)) &&
430
429
  (0, runtime_lint_utils_1.hasStaticImportOfDynamicResource)(node, projectGraph, sourceProject.name, targetProject.name, imp, sourceFilePath) &&
431
430
  !isIgnoreServerInputsImport(node, sourceProject, sourceFilePath)) {
432
- const filesWithLazyImports = (0, graph_utils_1.findFilesWithDynamicImports)(projectFileMap, sourceProject.name, targetProject.name);
431
+ const filesWithLazyImports = (0, internal_2.findFilesWithDynamicImports)(projectFileMap, sourceProject.name, targetProject.name);
433
432
  context.report({
434
433
  data: {
435
434
  filePaths: filesWithLazyImports
@@ -0,0 +1,27 @@
1
+ import type { TSESTree } from '@typescript-eslint/utils';
2
+ export type HeaderMessageId = 'unknownDirective' | 'unknownDirectiveSuggestion' | 'unparsableDirective' | 'directiveAfterCode' | 'emptyDependsOn' | 'ignoreServerInputsValue' | 'emptyTargetName' | 'extraTargetName';
3
+ export interface Span {
4
+ start: number;
5
+ end: number;
6
+ }
7
+ export interface HeaderProblem extends Span {
8
+ messageId: HeaderMessageId;
9
+ data?: Record<string, string>;
10
+ }
11
+ export interface DirectiveHeader {
12
+ problems: HeaderProblem[];
13
+ dependsOn: {
14
+ lines: Span[];
15
+ patterns: (Span & {
16
+ pattern: string;
17
+ })[];
18
+ };
19
+ ignoreServerInputs: {
20
+ lines: Span[];
21
+ };
22
+ }
23
+ /**
24
+ * The directives in the comment block that opens `content`, and the mistakes
25
+ * that make Nx ignore one.
26
+ */
27
+ export declare function checkDirectiveHeader(content: string, comments: TSESTree.Comment[]): DirectiveHeader;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkDirectiveHeader = checkDirectiveHeader;
4
+ const internal_1 = require("@nx/devkit/internal");
5
+ const DIRECTIVE_FORMS = {
6
+ 'depends-on': '@nx-depends-on: <project>, <project>',
7
+ 'ignore-server-inputs': '@nx-ignore-server-inputs',
8
+ 'target-name': '@nx-target-name: <name>',
9
+ };
10
+ // A known name not followed by a name character, e.g. `@nx-depends-on shop`.
11
+ const KNOWN_DIRECTIVE_START = new RegExp(`^@nx-(${internal_1.NX_DIRECTIVE_NAMES.join('|')})(?![\\w-])`);
12
+ /**
13
+ * The directives in the comment block that opens `content`, and the mistakes
14
+ * that make Nx ignore one.
15
+ */
16
+ function checkDirectiveHeader(content, comments) {
17
+ const header = (0, internal_1.readNxDirectiveHeader)(content);
18
+ const problems = [];
19
+ const dependsOn = { lines: [], patterns: [] };
20
+ const ignoreServerInputs = {
21
+ lines: [],
22
+ };
23
+ const targetNames = [];
24
+ for (const line of header.lines) {
25
+ const span = lineSpan(line);
26
+ const directive = (0, internal_1.matchNxDirective)(line.text);
27
+ if (!directive) {
28
+ const name = line.text.match(KNOWN_DIRECTIVE_START)?.[1];
29
+ if (name) {
30
+ problems.push({
31
+ ...span,
32
+ messageId: 'unparsableDirective',
33
+ data: { name, form: DIRECTIVE_FORMS[name] },
34
+ });
35
+ }
36
+ continue;
37
+ }
38
+ const name = directive.name;
39
+ if (!isNxDirectiveName(name)) {
40
+ const [suggestion] = (0, internal_1.findClosestMatches)(name, internal_1.NX_DIRECTIVE_NAMES, 1);
41
+ problems.push(suggestion
42
+ ? {
43
+ ...span,
44
+ messageId: 'unknownDirectiveSuggestion',
45
+ data: { name, suggestion },
46
+ }
47
+ : { ...span, messageId: 'unknownDirective', data: { name } });
48
+ continue;
49
+ }
50
+ switch (name) {
51
+ case 'depends-on':
52
+ dependsOn.lines.push(span);
53
+ dependsOn.patterns.push(...projectPatterns(line));
54
+ break;
55
+ case 'ignore-server-inputs':
56
+ ignoreServerInputs.lines.push(span);
57
+ if (directive.value !== '') {
58
+ problems.push({ ...span, messageId: 'ignoreServerInputsValue' });
59
+ }
60
+ break;
61
+ case 'target-name':
62
+ targetNames.push({ ...span, value: directive.value });
63
+ break;
64
+ default: {
65
+ const unhandled = name;
66
+ throw new Error(`Unhandled directive "@nx-${unhandled}"`);
67
+ }
68
+ }
69
+ }
70
+ // Nx merges every `@nx-depends-on` line, so one empty line is harmless.
71
+ if (dependsOn.lines.length > 0 && dependsOn.patterns.length === 0) {
72
+ for (const span of dependsOn.lines) {
73
+ problems.push({ ...span, messageId: 'emptyDependsOn' });
74
+ }
75
+ }
76
+ // Nx reads the first `@nx-target-name` only.
77
+ const [targetName, ...extraTargetNames] = targetNames;
78
+ if (targetName?.value === '') {
79
+ problems.push({ ...targetName, messageId: 'emptyTargetName' });
80
+ }
81
+ for (const extra of extraTargetNames) {
82
+ problems.push({ ...extra, messageId: 'extraTargetName' });
83
+ }
84
+ // A block comment can start in the header and end on a line with code, so
85
+ // compare each line, not the comment, with the header's end.
86
+ for (const comment of comments) {
87
+ for (const line of commentLines(comment)) {
88
+ if (line.start < header.end) {
89
+ continue;
90
+ }
91
+ const name = line.text.match(KNOWN_DIRECTIVE_START)?.[1];
92
+ if (name) {
93
+ problems.push({
94
+ ...lineSpan(line),
95
+ messageId: 'directiveAfterCode',
96
+ data: { name },
97
+ });
98
+ continue;
99
+ }
100
+ // After code, only a name close to a known one marks a line meant for Nx.
101
+ const unknownName = (0, internal_1.matchNxDirective)(line.text)?.name;
102
+ const [suggestion] = unknownName
103
+ ? (0, internal_1.findClosestMatches)(unknownName, internal_1.NX_DIRECTIVE_NAMES, 1)
104
+ : [];
105
+ if (suggestion) {
106
+ problems.push({
107
+ ...lineSpan(line),
108
+ messageId: 'unknownDirectiveSuggestion',
109
+ data: { name: unknownName, suggestion },
110
+ });
111
+ }
112
+ }
113
+ }
114
+ return { problems, dependsOn, ignoreServerInputs };
115
+ }
116
+ function isNxDirectiveName(name) {
117
+ return internal_1.NX_DIRECTIVE_NAMES.includes(name);
118
+ }
119
+ function lineSpan(line) {
120
+ return { start: line.start, end: line.start + line.text.length };
121
+ }
122
+ function projectPatterns(line) {
123
+ const patterns = [];
124
+ const valueStart = line.text.indexOf(':') + 1;
125
+ if (valueStart === 0) {
126
+ return patterns;
127
+ }
128
+ let offset = line.start + valueStart;
129
+ for (const part of line.text.slice(valueStart).split(',')) {
130
+ const [pattern] = (0, internal_1.dependsOnProjects)([part]);
131
+ if (pattern) {
132
+ const start = offset + part.indexOf(pattern);
133
+ patterns.push({ pattern, start, end: start + pattern.length });
134
+ }
135
+ offset += part.length + 1;
136
+ }
137
+ return patterns;
138
+ }
139
+ function commentLines(comment) {
140
+ const lines = [];
141
+ let offset = comment.range[0] + 2;
142
+ for (const raw of comment.value.split('\n')) {
143
+ const marker = comment.type === 'Block' ? (raw.match(/^\s*\*+/)?.[0].length ?? 0) : 0;
144
+ const rest = raw.slice(marker);
145
+ const text = rest.trim();
146
+ lines.push({
147
+ text,
148
+ start: offset + marker + rest.length - rest.trimStart().length,
149
+ });
150
+ offset += raw.length + 1;
151
+ }
152
+ return lines;
153
+ }
@@ -0,0 +1,6 @@
1
+ import type { ProjectGraph } from '@nx/devkit';
2
+ /**
3
+ * The patterns that select no project under the task hasher's rules, each
4
+ * mapped to a project name to suggest, or undefined.
5
+ */
6
+ export declare function findUnmatchedProjectPatterns(patterns: string[], projectGraph: ProjectGraph): Map<string, string | undefined>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findUnmatchedProjectPatterns = findUnmatchedProjectPatterns;
4
+ const internal_1 = require("@nx/devkit/internal");
5
+ /**
6
+ * The patterns that select no project under the task hasher's rules, each
7
+ * mapped to a project name to suggest, or undefined.
8
+ */
9
+ function findUnmatchedProjectPatterns(patterns, projectGraph) {
10
+ const unmatched = new Map();
11
+ for (const pattern of (0, internal_1.unmatchedProjectPatterns)((0, internal_1.transformProjectGraphForProjectMatching)(projectGraph), patterns)) {
12
+ unmatched.set(pattern, suggestProject(pattern, projectGraph));
13
+ }
14
+ return unmatched;
15
+ }
16
+ /**
17
+ * Suggests a project name only, which the hasher accepts because it matches an
18
+ * exact name before reading any prefix.
19
+ */
20
+ function suggestProject(pattern, projectGraph) {
21
+ if (pattern.startsWith('tag:') || pattern.startsWith('directory:')) {
22
+ return undefined;
23
+ }
24
+ // The looser TypeScript matcher finds the project a case-insensitive or
25
+ // unscoped name means.
26
+ const looseMatches = (0, internal_1.findMatchingProjects)([pattern], projectGraph.nodes);
27
+ if (looseMatches.length === 1) {
28
+ return looseMatches[0];
29
+ }
30
+ const name = pattern.startsWith('name:')
31
+ ? pattern.slice('name:'.length)
32
+ : pattern;
33
+ return (0, internal_1.findClosestMatches)(name, Object.keys(projectGraph.nodes), 1)[0];
34
+ }
@@ -0,0 +1,10 @@
1
+ import { type ProjectGraphProjectNode, type TargetConfiguration } from '@nx/devkit';
2
+ import { type TestFileDirective } from '@nx/devkit/internal';
3
+ export type SplitTarget = [name: string, configuration: TargetConfiguration];
4
+ /**
5
+ * The atomized targets that record `sourceFilePath` as their test file, or else
6
+ * the unrecorded ones named `<target>--<file path>`. A name can end with
7
+ * another file's path, but an unrecorded target applies no directive.
8
+ */
9
+ export declare function findSplitTargets(project: ProjectGraphProjectNode, sourceFilePath: string): SplitTarget[];
10
+ export declare function splitTargetsApply(targets: SplitTarget[], directive: TestFileDirective): boolean;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findSplitTargets = findSplitTargets;
4
+ exports.splitTargetsApply = splitTargetsApply;
5
+ const devkit_1 = require("@nx/devkit");
6
+ const internal_1 = require("@nx/devkit/internal");
7
+ const node_path_1 = require("node:path");
8
+ /**
9
+ * The atomized targets that record `sourceFilePath` as their test file, or else
10
+ * the unrecorded ones named `<target>--<file path>`. A name can end with
11
+ * another file's path, but an unrecorded target applies no directive.
12
+ */
13
+ function findSplitTargets(project, sourceFilePath) {
14
+ const targets = Object.entries(project.data.targets ?? {});
15
+ const recorded = targets.filter(([, target]) => (0, internal_1.recordedTestFile)(target) === sourceFilePath);
16
+ if (recorded.length > 0) {
17
+ return recorded;
18
+ }
19
+ const filePath = (0, devkit_1.normalizePath)((0, node_path_1.relative)(project.data.root, sourceFilePath));
20
+ return targets.filter(([name, target]) => (0, internal_1.recordedTestFile)(target) === undefined && name.endsWith(`--${filePath}`));
21
+ }
22
+ function splitTargetsApply(targets, directive) {
23
+ return targets.some(([, target]) => (0, internal_1.appliesTestFileDirective)(target, directive));
24
+ }
@@ -1,8 +1,8 @@
1
1
  import { ProjectFileMap, ProjectGraph } from '@nx/devkit';
2
2
  import { TargetProjectLocator } from '@nx/js/internal';
3
3
  import { ProjectRootMappings } from '@nx/devkit/internal';
4
- export declare function ensureGlobalProjectGraph(ruleName: string): void;
5
- export declare function readProjectGraph(ruleName: string): {
4
+ export declare function ensureGlobalProjectGraph(ruleName: string, skipped?: string): void;
5
+ export declare function readProjectGraph(ruleName: string, skipped?: string): {
6
6
  projectGraph: ProjectGraph;
7
7
  projectFileMap: ProjectFileMap;
8
8
  projectRootMappings: ProjectRootMappings;
@@ -8,7 +8,7 @@ const runtime_lint_utils_1 = require("./runtime-lint-utils");
8
8
  const picocolors_1 = tslib_1.__importDefault(require("picocolors"));
9
9
  const internal_1 = require("@nx/js/internal");
10
10
  const internal_2 = require("@nx/devkit/internal");
11
- function ensureGlobalProjectGraph(ruleName) {
11
+ function ensureGlobalProjectGraph(ruleName, skipped = 'The rule will be skipped.') {
12
12
  /**
13
13
  * Only reuse graph when running from terminal
14
14
  * Enforce every IDE change to get a fresh nxdeps.json
@@ -34,14 +34,14 @@ function ensureGlobalProjectGraph(ruleName) {
34
34
  const WARNING_PREFIX = `${picocolors_1.default.reset(picocolors_1.default.yellow('warning'))}`;
35
35
  const RULE_NAME_SUFFIX = `${picocolors_1.default.reset(picocolors_1.default.dim(`@nx/${ruleName}`))}`;
36
36
  process.stdout
37
- .write(`${WARNING_PREFIX} No cached ProjectGraph is available. The rule will be skipped.
37
+ .write(`${WARNING_PREFIX} No cached ProjectGraph is available. ${skipped}
38
38
  If you encounter this error as part of running standard \`nx\` commands then please open an issue on https://github.com/nrwl/nx
39
39
  ${RULE_NAME_SUFFIX}\n`);
40
40
  }
41
41
  }
42
42
  }
43
- function readProjectGraph(ruleName) {
44
- ensureGlobalProjectGraph(ruleName);
43
+ function readProjectGraph(ruleName, skipped) {
44
+ ensureGlobalProjectGraph(ruleName, skipped);
45
45
  return {
46
46
  projectGraph: globalThis.projectGraph,
47
47
  projectFileMap: globalThis.projectFileMap,
@@ -30,7 +30,6 @@ const devkit_1 = require("@nx/devkit");
30
30
  const js_1 = require("@nx/js");
31
31
  const utils_1 = require("@typescript-eslint/utils");
32
32
  const path = tslib_1.__importStar(require("node:path"));
33
- const graph_utils_1 = require("./graph-utils");
34
33
  const internal_1 = require("@nx/devkit/internal");
35
34
  function stringifyTags(tags) {
36
35
  return tags.map((t) => `"${t}"`).join(', ');
@@ -50,12 +49,12 @@ function isComboDepConstraint(depConstraint) {
50
49
  function findDependenciesWithTags(targetProject, tags, graph) {
51
50
  // find all reachable projects that have one of the tags and
52
51
  // are reacheable from the targetProject (including self)
53
- const allReachableProjects = Object.keys(graph.nodes).filter((projectName) => (0, graph_utils_1.pathExists)(graph, targetProject.name, projectName) &&
52
+ const allReachableProjects = Object.keys(graph.nodes).filter((projectName) => (0, internal_1.pathExists)(graph, targetProject.name, projectName) &&
54
53
  tags.some((tag) => hasTag(graph.nodes[projectName], tag)));
55
54
  // return path from targetProject to reachable project
56
55
  return allReachableProjects.map((project) => targetProject.name === project
57
56
  ? [targetProject]
58
- : (0, graph_utils_1.getPath)(graph, targetProject.name, project));
57
+ : (0, internal_1.getPath)(graph, targetProject.name, project));
59
58
  }
60
59
  const regexMap = new Map();
61
60
  function hasTag(proj, tag) {
@@ -213,7 +212,7 @@ function findTransitiveExternalDependencies(graph, source) {
213
212
  const allReachableProjects = [];
214
213
  const allProjects = Object.keys(graph.nodes);
215
214
  for (let i = 0; i < allProjects.length; i++) {
216
- if ((0, graph_utils_1.pathExists)(graph, source.name, allProjects[i])) {
215
+ if ((0, internal_1.pathExists)(graph, source.name, allProjects[i])) {
217
216
  allReachableProjects.push(allProjects[i]);
218
217
  }
219
218
  }
@@ -369,8 +368,12 @@ function belongsToDifferentEntryPoint(importExpr, filePath, projectRoot) {
369
368
  return importEntryPoint !== srcEntryPoint;
370
369
  }
371
370
  function getSecondaryEntryPointPath(importExpr, filePath, projectRoot) {
371
+ const rootTsConfig = (0, js_1.getRootTsConfigFileName)();
372
+ if (!rootTsConfig) {
373
+ return undefined;
374
+ }
372
375
  const resolvedImportFile = (0, js_1.resolveModuleByImport)(importExpr, filePath, // not strictly necessary, but speeds up resolution
373
- path.join(devkit_1.workspaceRoot, (0, js_1.getRootTsConfigFileName)()));
376
+ path.join(devkit_1.workspaceRoot, rootTsConfig));
374
377
  if (!resolvedImportFile) {
375
378
  return undefined;
376
379
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/eslint-plugin",
3
- "version": "24.1.0-beta.0",
3
+ "version": "24.1.0-beta.2",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "files": [
@@ -89,6 +89,7 @@
89
89
  },
90
90
  "peerDependencies": {
91
91
  "@typescript-eslint/parser": "^8.0.0",
92
+ "eslint": "^9.0.0 || ^10.0.0",
92
93
  "eslint-config-prettier": "^10.0.0"
93
94
  },
94
95
  "peerDependenciesMeta": {
@@ -100,11 +101,11 @@
100
101
  }
101
102
  },
102
103
  "dependencies": {
103
- "@nx/devkit": "24.1.0-beta.0",
104
- "@nx/js": "24.1.0-beta.0",
104
+ "@nx/devkit": "24.1.0-beta.2",
105
+ "@nx/js": "24.1.0-beta.2",
105
106
  "@phenomnomnominal/tsquery": "~6.2.0",
106
- "@typescript-eslint/type-utils": "^8.0.0",
107
- "@typescript-eslint/utils": "^8.0.0",
107
+ "@typescript-eslint/type-utils": "^8.58.0",
108
+ "@typescript-eslint/utils": "^8.58.0",
108
109
  "confusing-browser-globals": "^1.0.9",
109
110
  "globals": "^17.0.0",
110
111
  "jsonc-eslint-parser": "^2.1.0",
@@ -113,7 +114,7 @@
113
114
  "tslib": "^2.3.0"
114
115
  },
115
116
  "devDependencies": {
116
- "nx": "24.1.0-beta.0"
117
+ "nx": "24.1.0-beta.2"
117
118
  },
118
119
  "publishConfig": {
119
120
  "access": "public"
@@ -1,8 +0,0 @@
1
- import type { FileData, ProjectFileMap, ProjectGraph, ProjectGraphProjectNode } from '@nx/devkit';
2
- export declare function getPath(graph: ProjectGraph, sourceProjectName: string, targetProjectName: string): Array<ProjectGraphProjectNode>;
3
- export declare function pathExists(graph: ProjectGraph, sourceProjectName: string, targetProjectName: string): boolean;
4
- export declare function checkCircularPath(graph: ProjectGraph, sourceProject: ProjectGraphProjectNode, targetProject: ProjectGraphProjectNode): ProjectGraphProjectNode[];
5
- export declare function circularPathHasPair(circularPath: ProjectGraphProjectNode[], ignored: Map<string, Set<string>>): boolean;
6
- export declare function findFilesInCircularPath(projectFileMap: ProjectFileMap, circularPath: ProjectGraphProjectNode[]): Array<string[]>;
7
- export declare function findFilesWithDynamicImports(projectFileMap: ProjectFileMap, sourceProjectName: string, targetProjectName: string): FileData[];
8
- export declare function expandIgnoredCircularDependencies(ignoredCircularDependencies: Array<[string, string]>, projectGraph: ProjectGraph): Map<string, Set<string>>;
@@ -1,170 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPath = getPath;
4
- exports.pathExists = pathExists;
5
- exports.checkCircularPath = checkCircularPath;
6
- exports.circularPathHasPair = circularPathHasPair;
7
- exports.findFilesInCircularPath = findFilesInCircularPath;
8
- exports.findFilesWithDynamicImports = findFilesWithDynamicImports;
9
- exports.expandIgnoredCircularDependencies = expandIgnoredCircularDependencies;
10
- const devkit_1 = require("@nx/devkit");
11
- const internal_1 = require("@nx/devkit/internal");
12
- const reach = {
13
- graph: null,
14
- matrix: null,
15
- adjList: null,
16
- };
17
- function buildMatrix(graph) {
18
- const nodes = Object.keys(graph.nodes);
19
- const nodesLength = nodes.length;
20
- const adjList = {};
21
- const matrix = {};
22
- // create matrix value set
23
- for (let i = 0; i < nodesLength; i++) {
24
- const v = nodes[i];
25
- adjList[v] = [];
26
- // meeroslav: turns out this is 10x faster than spreading the pre-generated initMatrixValues
27
- matrix[v] = {};
28
- }
29
- const projectsWithDependencies = Object.keys(graph.dependencies);
30
- for (let i = 0; i < projectsWithDependencies.length; i++) {
31
- const dependencies = graph.dependencies[projectsWithDependencies[i]];
32
- for (let j = 0; j < dependencies.length; j++) {
33
- const dependency = dependencies[j];
34
- if (graph.nodes[dependency.target]) {
35
- adjList[dependency.source].push(dependency.target);
36
- }
37
- }
38
- }
39
- const traverse = (s, v) => {
40
- matrix[s][v] = true;
41
- const adjListLength = adjList[v].length;
42
- for (let i = 0; i < adjListLength; i++) {
43
- const adj = adjList[v][i];
44
- if (!matrix[s][adj]) {
45
- traverse(s, adj);
46
- }
47
- }
48
- };
49
- for (let i = 0; i < nodesLength; i++) {
50
- const v = nodes[i];
51
- traverse(v, v);
52
- }
53
- return {
54
- matrix,
55
- adjList,
56
- };
57
- }
58
- function getPath(graph, sourceProjectName, targetProjectName) {
59
- if (sourceProjectName === targetProjectName)
60
- return [];
61
- if (reach.graph !== graph) {
62
- const { matrix, adjList } = buildMatrix(graph);
63
- reach.graph = graph;
64
- reach.matrix = matrix;
65
- reach.adjList = adjList;
66
- }
67
- const adjList = reach.adjList;
68
- let path = [];
69
- const queue = [[sourceProjectName, path]];
70
- const visited = [sourceProjectName];
71
- while (queue.length > 0) {
72
- const [current, p] = queue.pop();
73
- path = [...p, current];
74
- if (current === targetProjectName)
75
- break;
76
- if (!adjList[current])
77
- break;
78
- adjList[current]
79
- .filter((adj) => visited.indexOf(adj) === -1)
80
- .filter((adj) => reach.matrix[adj][targetProjectName])
81
- .forEach((adj) => {
82
- visited.push(adj);
83
- queue.push([adj, [...path]]);
84
- });
85
- }
86
- if (path.length > 1) {
87
- return path.map((n) => graph.nodes[n]);
88
- }
89
- else {
90
- return [];
91
- }
92
- }
93
- function pathExists(graph, sourceProjectName, targetProjectName) {
94
- if (sourceProjectName === targetProjectName)
95
- return true;
96
- if (reach.graph !== graph) {
97
- const { matrix, adjList } = buildMatrix(graph);
98
- reach.graph = graph;
99
- reach.matrix = matrix;
100
- reach.adjList = adjList;
101
- }
102
- return !!reach.matrix[sourceProjectName][targetProjectName];
103
- }
104
- function checkCircularPath(graph, sourceProject, targetProject) {
105
- if (!graph.nodes[targetProject.name])
106
- return [];
107
- return getPath(graph, targetProject.name, sourceProject.name);
108
- }
109
- function circularPathHasPair(circularPath, ignored) {
110
- if (circularPath.length < 2)
111
- return false;
112
- for (let i = 0; i < circularPath.length - 1; i++) {
113
- const dependencyIsIgnored = ignored
114
- .get(circularPath[i].name)
115
- ?.has(circularPath[i + 1].name);
116
- if (dependencyIsIgnored) {
117
- return true;
118
- }
119
- }
120
- return false;
121
- }
122
- function findFilesInCircularPath(projectFileMap, circularPath) {
123
- const filePathChain = [];
124
- for (let i = 0; i < circularPath.length - 1; i++) {
125
- const next = circularPath[i + 1].name;
126
- const files = projectFileMap[circularPath[i].name] || [];
127
- filePathChain.push(files
128
- .filter((file) => file.deps && file.deps.find((d) => (0, internal_1.fileDataDepTarget)(d) === next))
129
- .map((file) => file.file));
130
- }
131
- return filePathChain;
132
- }
133
- function findFilesWithDynamicImports(projectFileMap, sourceProjectName, targetProjectName) {
134
- const files = [];
135
- projectFileMap[sourceProjectName].forEach((file) => {
136
- if (!file.deps)
137
- return;
138
- if (file.deps.some((d) => (0, internal_1.fileDataDepTarget)(d) === targetProjectName &&
139
- (0, internal_1.fileDataDepType)(d) === devkit_1.DependencyType.dynamic)) {
140
- files.push(file);
141
- }
142
- });
143
- return files;
144
- }
145
- function expandIgnoredCircularDependencies(ignoredCircularDependencies, projectGraph) {
146
- const allowed = new Map();
147
- for (const [a, b] of ignoredCircularDependencies) {
148
- const setA = new Set((0, internal_1.findMatchingProjects)([a], projectGraph.nodes));
149
- const setB = new Set((0, internal_1.findMatchingProjects)([b], projectGraph.nodes));
150
- for (const projectA of setA) {
151
- if (!allowed.has(projectA)) {
152
- allowed.set(projectA, new Set());
153
- }
154
- const currentSetA = allowed.get(projectA);
155
- for (const projectB of setB) {
156
- currentSetA.add(projectB);
157
- }
158
- }
159
- for (const projectB of setB) {
160
- if (!allowed.has(projectB)) {
161
- allowed.set(projectB, new Set());
162
- }
163
- const currentSetB = allowed.get(projectB);
164
- for (const projectA of setA) {
165
- currentSetB.add(projectA);
166
- }
167
- }
168
- }
169
- return allowed;
170
- }