@brutalway/check-tree 0.5.1 → 0.7.0

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.
package/README.md CHANGED
@@ -1,14 +1,16 @@
1
1
  # @brutalway/check-tree
2
2
 
3
- Checks the folders of a source tree, which a linter does not see: no empty folder, no category folder with a single child, and files of one kind grouped in that kind's folder once there are two of them.
3
+ Checks the folders of a source tree, which a linter does not see: only the folders the layout names, no empty folder, no category folder with a single child, files of one kind grouped in that kind's folder once there are two of them, and no file in a `shared/` folder that a single feature uses.
4
4
 
5
5
  ## Install
6
6
 
7
7
  ```sh
8
- npm install --save-dev @brutalway/check-tree
8
+ npm install --save-dev @brutalway/check-tree dependency-cruiser
9
9
  npx check-tree src
10
10
  ```
11
11
 
12
+ check-tree runs from the folder that holds the dependency-cruiser config (`.dependency-cruiser.cjs` and the like) and reads it to resolve the imports, with the same tsconfig and aliases.
13
+
12
14
  ## Usage
13
15
 
14
16
  ### Use your own category folders
@@ -17,7 +19,7 @@ npx check-tree src
17
19
  npx check-tree src --categories components,hooks,utils
18
20
  ```
19
21
 
20
- The grouping rule only applies to the kinds listed in the table below that are also in this list.
22
+ These are the kind folders the layout accepts, and the grouping rule only applies to the kinds listed in the table below that are also in this list.
21
23
 
22
24
  ### Keep the entry points of a published package
23
25
 
@@ -35,12 +37,23 @@ import { treeViolations } from '@brutalway/check-tree/treeViolations';
35
37
  const violations = treeViolations('src');
36
38
  ```
37
39
 
38
- It takes the category folders as second argument and `{ rootEntries: true }` as third, like `--categories` and `--root-entries`.
40
+ It takes the category folders as second argument and `{ rootEntries: true }` as third, like `--categories` and `--root-entries`. The check on `shared/` reads the imports, so it has its own export:
41
+
42
+ ```ts
43
+ import { sharedViolations } from '@brutalway/check-tree/sharedViolations';
44
+
45
+ const violations = await sharedViolations('src');
46
+ ```
39
47
 
40
48
  ## Reference
41
49
 
42
50
  ### Rules
43
51
 
52
+ - a folder has a name the layout gives it:
53
+ - `src/` holds `app/`, `features/`, `shared-features/` and `shared/`, next to its entry files, and `app/` is not checked
54
+ - `src/shared/` holds kind folders only (`lib/`, `types/`, `configs/`...), since it has no domain
55
+ - a feature (`features/<x>/`) or a shared feature (`shared-features/<x>/`), at any depth, holds kind folders, `features/` for its sub-features, `shared-features/` for the business code they share and `shared/` for the code with no domain
56
+ - a kind folder holds kind folders only, like `presenters/` inside `components/`
44
57
  - no empty folder
45
58
  - a category folder (`components`, `hooks`, `stores`…) does not hold a single child: move the child up and delete the folder
46
59
  - files of one kind stay at the root of their folder while there is one of them, and move into the kind's folder from two on. A folder that has that kind's folder keeps none of them next to it. The kinds are recognized by their name:
@@ -64,6 +77,8 @@ It takes the category folders as second argument and `{ rootEntries: true }` as
64
77
  | `stores/` | `xStore.ts` |
65
78
  | `lib/` | any other `.ts` file, except `xContent.ts`, `xEnv.ts` and `.d.ts` |
66
79
 
80
+ - a file of a `shared/` folder is used by at least two consumers. For `src/shared/`, a consumer is a feature or a shared feature, a sub-feature counting as the feature it sits in. For the `shared/` of a feature or a shared feature, a consumer is one of its sub-features, one of its sub shared features, or its own files outside them. A file imported by another file of the same `shared/` gets the consumers of that file. A test counts for the feature it sits in, since moving the file would make that test import another feature, and a test next to the file in `shared/` adds no consumer. A file of `src/shared/` used only by `app/` or by the entry files of `src/` passes. A file with a single consumer gets `src/shared/lib/format.ts is only used by src/features/cart: move it into src/features/cart`.
81
+
67
82
  So a feature with two components puts them in `components/`, and a `components/` folder with two presenters puts them in `presenters/`. The `components/` rule does not apply inside `components/`, `orchestrators/` or `presenters/`.
68
83
 
69
84
  Test files (`*.test.ts`, `*.test.tsx`) are not counted.
package/dist/checkTree.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as treeViolations } from "./treeViolations-DzriZgEc.js";
2
+ import { t as treeViolations } from "./treeViolations-lxAwbM5R.js";
3
+ import { n as cruiseImports, t as sharedConsumerViolations } from "./sharedConsumerViolations-CmRppyrD.js";
3
4
  import { resolve } from "node:path";
4
5
  import { parseArgs } from "node:util";
5
6
  // src/checkTree.ts
@@ -10,8 +11,14 @@ const { values, positionals } = parseArgs({
10
11
  "root-entries": { type: "boolean" }
11
12
  }
12
13
  });
14
+ const folder = positionals[0] ?? "src";
13
15
  const categories = values.categories?.split(",").map((category) => category.trim());
14
- const violations = treeViolations(resolve(positionals[0] ?? "src"), categories, { rootEntries: values["root-entries"] === true });
15
- for (const violation of violations) console.error(violation);
16
- process.exitCode = violations.length === 0 ? 0 : 1;
16
+ try {
17
+ const violations = [...treeViolations(resolve(folder), categories, { rootEntries: values["root-entries"] === true }), ...sharedConsumerViolations(folder, await cruiseImports(folder))];
18
+ for (const violation of violations) console.error(violation);
19
+ process.exitCode = violations.length === 0 ? 0 : 1;
20
+ } catch (error) {
21
+ console.error(error instanceof Error ? error.message : String(error));
22
+ process.exitCode = 1;
23
+ }
17
24
  export {};
@@ -0,0 +1,75 @@
1
+ import { existsSync } from "node:fs";
2
+ import { cruise } from "dependency-cruiser";
3
+ import extractDepcruiseOptions from "dependency-cruiser/config-utl/extract-depcruise-options";
4
+ import extractTSConfig from "dependency-cruiser/config-utl/extract-ts-config";
5
+ // src/features/shared-consumers/lib/cruiseImports.ts
6
+ const CONFIG_FILES = [
7
+ ".dependency-cruiser.js",
8
+ ".dependency-cruiser.cjs",
9
+ ".dependency-cruiser.mjs",
10
+ ".dependency-cruiser.json"
11
+ ];
12
+ async function cruiseImports(root) {
13
+ const configFile = CONFIG_FILES.find((file) => existsSync(file));
14
+ if (configFile === void 0) throw new Error(`check-tree reads the dependency-cruiser config to resolve imports, and the current folder has none of ${CONFIG_FILES.join(", ")}`);
15
+ const options = await extractDepcruiseOptions(`./${configFile}`);
16
+ const tsConfigFile = options.tsConfig?.fileName;
17
+ const result = await cruise([root], {
18
+ ...options,
19
+ validate: false,
20
+ tsPreCompilationDeps: true
21
+ }, {}, { tsConfig: tsConfigFile === void 0 ? void 0 : extractTSConfig(tsConfigFile) });
22
+ if (typeof result.output === "string") throw new Error(result.output);
23
+ return result.output.modules.map(({ source, dependencies }) => ({
24
+ source,
25
+ imports: dependencies.map(({ resolved }) => resolved)
26
+ }));
27
+ }
28
+ // src/features/shared-consumers/SharedConsumersConfig.ts
29
+ const TEST_CODE = /\.test\.tsx?$/u;
30
+ const SLICE = /^(?:features|shared-features)\/[^/]+/u;
31
+ // src/features/shared-consumers/lib/consumerSlots.ts
32
+ function slotOf(owner, importer) {
33
+ if (!importer.startsWith(`${owner}/`)) return importer;
34
+ const slice = SLICE.exec(importer.slice(owner.length + 1));
35
+ return slice === null ? owner : `${owner}/${slice[0]}`;
36
+ }
37
+ function importersByModule(modules) {
38
+ const importers = /* @__PURE__ */ new Map();
39
+ for (const { source, imports } of modules) for (const target of imports) importers.set(target, [...importers.get(target) ?? [], source]);
40
+ return importers;
41
+ }
42
+ function consumerSlots(modules) {
43
+ const importers = importersByModule(modules);
44
+ const slotsByModule = /* @__PURE__ */ new Map();
45
+ return function slots(path, owner) {
46
+ const known = slotsByModule.get(path);
47
+ if (known !== void 0) return known;
48
+ const found = /* @__PURE__ */ new Set();
49
+ slotsByModule.set(path, found);
50
+ for (const importer of importers.get(path) ?? []) if (importer.startsWith(`${owner}/shared/`)) for (const slot of slots(importer, owner)) found.add(slot);
51
+ else found.add(slotOf(owner, importer));
52
+ return found;
53
+ };
54
+ }
55
+ // src/features/shared-consumers/lib/sharedConsumerViolations.ts
56
+ function ownerOf(path) {
57
+ const index = path.lastIndexOf("/shared/");
58
+ return index === -1 ? void 0 : path.slice(0, index);
59
+ }
60
+ function violation(path, owner, slot) {
61
+ if (slot === owner) return `${path} is only used by ${owner} outside its sub-features: move it out of shared/ into the kind folders of ${owner}`;
62
+ return `${path} is only used by ${slot}: move it into ${slot}`;
63
+ }
64
+ function sharedConsumerViolations(root, modules) {
65
+ const slots = consumerSlots(modules);
66
+ return modules.flatMap(({ source }) => {
67
+ const owner = ownerOf(source);
68
+ if (owner === void 0 || TEST_CODE.test(source) || !source.startsWith(`${root}/`)) return [];
69
+ const [slot, ...others] = slots(source, owner);
70
+ if (slot === void 0 || others.length > 0) return [];
71
+ if (owner === root && !SLICE.test(slot.slice(root.length + 1))) return [];
72
+ return [violation(source, owner, slot)];
73
+ });
74
+ }
75
+ export { cruiseImports as n, sharedConsumerViolations as t };
@@ -0,0 +1 @@
1
+ export declare function sharedViolations(root: string): Promise<string[]>;
@@ -0,0 +1,6 @@
1
+ import { n as cruiseImports, t as sharedConsumerViolations } from "./sharedConsumerViolations-CmRppyrD.js";
2
+ // src/sharedViolations.ts
3
+ async function sharedViolations(root) {
4
+ return sharedConsumerViolations(root, await cruiseImports(root));
5
+ }
6
+ export { sharedViolations };
@@ -1,4 +1,4 @@
1
- import { basename, join, relative } from "node:path";
1
+ import { basename, dirname, join, relative } from "node:path";
2
2
  import { readdirSync } from "node:fs";
3
3
  // src/features/tree-violations/TreeViolationsConfig.ts
4
4
  const DEFAULT_CATEGORY_FOLDERS = [
@@ -116,17 +116,72 @@ const FILE_GROUPS = [
116
116
  appliesIn: outsideOwnFolder("lib")
117
117
  }
118
118
  ];
119
+ // src/features/tree-violations/features/layout/childLayer.ts
120
+ const SOURCE_LAYERS = /* @__PURE__ */ new Map([
121
+ ["app", "free"],
122
+ ["features", "features"],
123
+ ["shared-features", "features"],
124
+ ["shared", "shared"]
125
+ ]);
126
+ const FEATURE_LAYERS = /* @__PURE__ */ new Map([
127
+ ["features", "features"],
128
+ ["shared-features", "features"],
129
+ ["shared", "shared"]
130
+ ]);
131
+ function kindFolder(path, categories, reason) {
132
+ if (categories.has(basename(path))) return {
133
+ layer: "kind",
134
+ violations: []
135
+ };
136
+ return {
137
+ layer: "free",
138
+ violations: [`${path} is not a kind folder: ${reason}`]
139
+ };
140
+ }
141
+ function sourceChild(path) {
142
+ const layer = SOURCE_LAYERS.get(basename(path));
143
+ if (layer !== void 0) return {
144
+ layer,
145
+ violations: []
146
+ };
147
+ return {
148
+ layer: "free",
149
+ violations: [`${path} is not a layer: ${dirname(path)}/ holds app/, features/, shared-features/ and shared/ next to its entry files, move it into one of them`]
150
+ };
151
+ }
152
+ function featureChild(path, categories) {
153
+ const layer = FEATURE_LAYERS.get(basename(path));
154
+ if (layer !== void 0) return {
155
+ layer,
156
+ violations: []
157
+ };
158
+ return kindFolder(path, categories, "a feature holds kind folders, features/ for its sub-features, shared-features/ for the business code they share and shared/, move it into features/ as a sub-feature or spread its files into kind folders");
159
+ }
160
+ function childLayer(layer, path, categories) {
161
+ if (layer === "source") return sourceChild(path);
162
+ if (layer === "features") return {
163
+ layer: "feature",
164
+ violations: []
165
+ };
166
+ if (layer === "feature") return featureChild(path, categories);
167
+ if (layer === "shared") return kindFolder(path, categories, `${dirname(path)}/ holds no domain, move its files into lib/, types/, configs/... or into a shared feature`);
168
+ if (layer === "kind") return kindFolder(path, categories, `${dirname(path)}/ holds its files and kind folders only`);
169
+ return {
170
+ layer: "free",
171
+ violations: []
172
+ };
173
+ }
119
174
  // src/features/tree-violations/treeViolations.ts
120
175
  function groupViolations(name, folderName, listing, categoryFolders) {
121
- const violations = [];
122
- for (const { folder, belongs, appliesIn } of FILE_GROUPS) {
123
- if (!categoryFolders.has(folder) || !appliesIn(folderName)) continue;
176
+ const holdsFilesOnly = categoryFolders.has(folderName) && listing.folders.size === 0;
177
+ return FILE_GROUPS.flatMap(({ folder, belongs, appliesIn }) => {
178
+ if (!categoryFolders.has(folder) || !appliesIn(folderName)) return [];
124
179
  const loose = listing.files.filter(belongs);
125
- if (loose.length === 0) continue;
126
- if (listing.folders.has(folder)) violations.push(`${name} has a ${folder}/ folder: move ${loose.join(", ")} into it`);
127
- else if (loose.length > 1) violations.push(`${name} holds ${loose.length} ${folder} files (${loose.join(", ")}): move them into ${folder}/`);
128
- }
129
- return violations;
180
+ if (loose.length === 0 || holdsFilesOnly && loose.length === listing.files.length) return [];
181
+ if (listing.folders.has(folder)) return [`${name} has a ${folder}/ folder: move ${loose.join(", ")} into it`];
182
+ if (loose.length === 1) return [];
183
+ return [`${name} holds ${loose.length} ${folder} files (${loose.join(", ")}): move them into ${folder}/`];
184
+ });
130
185
  }
131
186
  function folderListing(entries) {
132
187
  return {
@@ -148,9 +203,13 @@ function folderViolations(folder, name, categoryFolders, groupsFiles) {
148
203
  }
149
204
  function treeViolations(root, categoryFolders = DEFAULT_CATEGORY_FOLDERS, options = {}) {
150
205
  const categories = new Set(categoryFolders);
151
- function walk(folder) {
152
- return [...folderViolations(folder, relative(join(root, ".."), folder), categories, folder !== root || options.rootEntries !== true), ...readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => walk(join(folder, entry.name)))];
206
+ function walk(folder, layer) {
207
+ const name = relative(join(root, ".."), folder);
208
+ return [...folderViolations(folder, name, categories, folder !== root || options.rootEntries !== true), ...readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
209
+ const child = childLayer(layer, `${name}/${entry.name}`, categories);
210
+ return [...child.violations, ...walk(join(folder, entry.name), child.layer)];
211
+ })];
153
212
  }
154
- return walk(root);
213
+ return walk(root, "source");
155
214
  }
156
215
  export { treeViolations as t };
@@ -1 +1 @@
1
- export { t as treeViolations } from "./treeViolations-DzriZgEc.js";
1
+ export { t as treeViolations } from "./treeViolations-lxAwbM5R.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@brutalway/check-tree",
3
- "version": "0.5.1",
4
- "description": "Checks a source tree: no empty folder, no category folder holding a single child, stylesheets grouped in styles/.",
3
+ "version": "0.7.0",
4
+ "description": "Checks a source tree: only the folders the layout names, no empty folder, no category folder holding a single child, stylesheets grouped in styles/, no file of shared/ used by a single feature.",
5
5
  "keywords": [
6
6
  "lint",
7
7
  "folder-structure",
@@ -28,7 +28,8 @@
28
28
  "check-tree": "./dist/checkTree.js"
29
29
  },
30
30
  "exports": {
31
- "./treeViolations": "./dist/treeViolations.js"
31
+ "./treeViolations": "./dist/treeViolations.js",
32
+ "./sharedViolations": "./dist/sharedViolations.js"
32
33
  },
33
34
  "scripts": {
34
35
  "build": "tsdown",
@@ -37,22 +38,41 @@
37
38
  "deps": "depcruise --output-type err-long src",
38
39
  "tree": "node src/checkTree.ts src --root-entries",
39
40
  "duplicates": "jscpd src",
40
- "check": "npm run typecheck && npm run lint && npm run deps && npm run tree && npm run duplicates",
41
- "test": "node --test 'src/**/*.test.ts'"
41
+ "check": "prettier --check . && npm run typecheck && npm run lint && npm run deps && npm run tree && npm run duplicates && npm run unused",
42
+ "test": "node --test 'src/**/*.test.ts'",
43
+ "format": "prettier --write .",
44
+ "unused": "knip"
42
45
  },
43
46
  "devDependencies": {
44
47
  "@brutalway/dependency-cruiser-config": "0.5.0",
45
48
  "@brutalway/oxlint-config-node": "0.2.1",
46
49
  "@brutalway/oxlint-config-node-test": "0.1.0",
50
+ "@brutalway/prettier-config": "0.3.0",
47
51
  "@brutalway/tsconfig": "0.4.0",
52
+ "@swc/core": "1.16.22",
53
+ "@types/node": "26.6.6",
48
54
  "dependency-cruiser": "18.7.2",
49
- "jscpd": "5.4.2",
50
- "oxlint": "1.91.0",
51
- "oxlint-tsgolint": "7.0.2005",
52
- "tsdown": "0.23.5",
55
+ "jscpd": "5.4.3",
56
+ "knip": "6.44.2",
57
+ "oxlint": "1.92.0",
58
+ "oxlint-tsgolint": "7.0.2006",
59
+ "prettier": "3.9.10",
60
+ "tsdown": "0.23.7",
53
61
  "typescript": "7.0.2"
54
62
  },
55
63
  "imports": {
56
64
  "#src/*": "./src/*"
65
+ },
66
+ "prettier": "@brutalway/prettier-config",
67
+ "allowScripts": {
68
+ "@swc/core": false
69
+ },
70
+ "overrides": {
71
+ "eslint-plugin-no-comments": {
72
+ "minimatch": "^11.0.1"
73
+ }
74
+ },
75
+ "peerDependencies": {
76
+ "dependency-cruiser": ">=18"
57
77
  }
58
78
  }