@brutalway/check-tree 0.8.0 → 0.10.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
@@ -13,22 +13,50 @@ check-tree runs from the folder that holds the dependency-cruiser config (`.depe
13
13
 
14
14
  ## Usage
15
15
 
16
- ### Use your own category folders
17
-
18
- ```sh
19
- npx check-tree src --categories components,hooks,utils
16
+ ### Set the options in package.json
17
+
18
+ check-tree reads its options from the `"check-tree"` key of the `package.json` in the current folder. `npm run check`, the agent hook and a manual run then check the tree the same way:
19
+
20
+ ```json
21
+ {
22
+ "check-tree": {
23
+ "categories": ["components", "hooks", "utils"],
24
+ "rootEntries": true,
25
+ "platforms": ["web", "tv"]
26
+ }
27
+ }
20
28
  ```
21
29
 
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.
30
+ Each key has a flag, `--categories`, `--root-entries` and `--platforms`, which wins over the key for one run.
31
+
32
+ ### Use your own category folders
33
+
34
+ `categories` lists 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.
23
35
 
24
36
  ### Keep the entry points of a published package
25
37
 
26
- A published package keeps its entry points at the root of `src/`, one file per bin or export, whatever their kind. `--root-entries` leaves the files at the root of the checked folder where they are, and checks everything below as usual:
38
+ A published package keeps its entry points at the root of `src/`, one file per bin or export, whatever their kind. `"rootEntries": true` leaves the files at the root of the checked folder where they are, and checks everything below as usual.
39
+
40
+ ### Use your own platforms
41
+
42
+ A platform variant (`X.web.ts`, `X.ios.tsx`) is the file that Metro and Expo pick in place of `X.ts` for one platform. check-tree knows `web`, `ios`, `android` and `native`, and `platforms` replaces that list.
43
+
44
+ ### Keep the violations of an existing tree
45
+
46
+ On a codebase that did not follow the layout, the first run prints a lot. Write the current violations to `.check-tree-known-violations.json` and commit it:
27
47
 
28
48
  ```sh
29
- npx check-tree src --root-entries
49
+ npx check-tree src --write-known-violations
50
+ ```
51
+
52
+ check-tree then skips the violations listed in that file, which it reads from the current folder. It still fails on a violation that is not in the list, and on an entry that no longer happens, which you delete from the file. The file is a JSON array of the messages check-tree prints:
53
+
54
+ ```json
55
+ ["src/features/player/hooks holds a single child: move it up one level and delete the folder"]
30
56
  ```
31
57
 
58
+ A message that names a count, like `holds 3 groups of files`, changes when the count changes: run `--write-known-violations` again and check the diff.
59
+
32
60
  ### Run the check from code
33
61
 
34
62
  ```ts
@@ -37,7 +65,7 @@ import { treeViolations } from '@brutalway/check-tree/treeViolations';
37
65
  const violations = treeViolations('src');
38
66
  ```
39
67
 
40
- It takes the category folders as second argument and `{ rootEntries: true }` as third, like `--categories` and `--root-entries`. The checks on the slices of `shared/` read the imports, so they have their own export:
68
+ It takes the category folders as second argument and `{ rootEntries: true, platforms: ['web'] }` as third, like `--categories`, `--root-entries` and `--platforms`. The checks on the slices of `shared/` read the imports, so they have their own export, which takes the platforms as second argument:
41
69
 
42
70
  ```ts
43
71
  import { sharedViolations } from '@brutalway/check-tree/sharedViolations';
@@ -86,14 +114,20 @@ So a feature with two components puts them in `components/`, and a `components/`
86
114
 
87
115
  Test files (`*.test.ts`, `*.test.tsx`) are not counted.
88
116
 
117
+ The files of a folder named `X.<platform>.<ext>`, like `useScreenTitle.web.ts` and `useScreenTitle.native.ts`, go with `X.<ext>`, whether that file exists or not. The bundler picks them by name and nothing imports them, so the variants and their base count as one file: they have the kind of `X.<ext>` (`AvatarPhoto.web.tsx` is a presenter), a `lib/` holding only `alert.ts` and `alert.web.ts` holds a single child, and they belong to one group in the import graph of a slice. check-tree does not compare their exports: TypeScript checks the base only, unless `moduleSuffixes` in the tsconfig points it at a variant.
118
+
89
119
  ### Output
90
120
 
91
- It prints one line per problem and exits with code 1 if it found any.
121
+ It prints one line per problem and exits with code 1 if it found any. The violations listed in `.check-tree-known-violations.json` are left out.
92
122
 
93
123
  ### Options
94
124
 
95
- | Option | Default |
96
- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
97
- | folder | `src` |
98
- | `--categories <list>` | `components`, `orchestrators`, `presenters`, `hooks`, `styles`, `types`, `configs`, `stores`, `routes`, `services`, `queries`, `keys`, `schemas`, `clients`, `workers`, `lib` |
99
- | `--root-entries` | off |
125
+ | Flag | Key in `"check-tree"` | Default |
126
+ | -------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
127
+ | folder | | `src` |
128
+ | `--categories <list>` | `categories` | `components`, `orchestrators`, `presenters`, `hooks`, `styles`, `types`, `configs`, `stores`, `routes`, `services`, `queries`, `keys`, `schemas`, `clients`, `workers`, `lib` |
129
+ | `--platforms <list>` | `platforms` | `web`, `ios`, `android`, `native` |
130
+ | `--root-entries` | `rootEntries` | off |
131
+ | `--write-known-violations` | | off |
132
+
133
+ A flag wins over its key. A key that is not one of these, or a value of the wrong type, stops check-tree with a message.
package/dist/checkTree.js CHANGED
@@ -1,22 +1,76 @@
1
1
  #!/usr/bin/env node
2
- import { t as treeViolations } from "./treeViolations-CEQ5ks7L.js";
3
- import { n as cruiseImports, t as sliceViolations } from "./sliceViolations-DojT6WkL.js";
2
+ import { t as treeViolations } from "./treeViolations-DV1n3hcr.js";
3
+ import { n as cruiseImports, t as sliceViolations } from "./sliceViolations-BfTZYfD3.js";
4
4
  import { resolve } from "node:path";
5
5
  import { parseArgs } from "node:util";
6
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
7
+ // src/features/known-violations/KnownViolationsConfig.ts
8
+ const KNOWN_VIOLATIONS_FILE = ".check-tree-known-violations.json";
9
+ // src/shared/string-lists/isStringList.ts
10
+ function isStringList(value) {
11
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
12
+ }
13
+ // src/features/known-violations/knownViolations.ts
14
+ function readKnownViolations(file) {
15
+ if (!existsSync(file)) return [];
16
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
17
+ if (!isStringList(parsed)) throw new Error(`${file} holds a JSON array with one string per known violation`);
18
+ return parsed;
19
+ }
20
+ function unknownViolations(violations, file) {
21
+ const known = new Set(readKnownViolations(file));
22
+ const found = new Set(violations);
23
+ return [...violations.filter((violation) => !known.has(violation)), ...[...known].filter((entry) => !found.has(entry)).map((entry) => `${file} lists a violation that no longer happens: ${entry}`)];
24
+ }
25
+ function writeKnownViolations(violations, file) {
26
+ writeFileSync(file, `${JSON.stringify(violations.toSorted(), void 0, 2)}\n`);
27
+ }
28
+ // src/features/tree-settings/readTreeSettings.ts
29
+ const SETTING_CHECKS = /* @__PURE__ */ new Map([
30
+ ["categories", isStringList],
31
+ ["rootEntries", (value) => typeof value === "boolean"],
32
+ ["platforms", isStringList]
33
+ ]);
34
+ function isTreeSettings(value) {
35
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
36
+ return Object.entries(value).every(([key, entry]) => SETTING_CHECKS.get(key)?.(entry) === true);
37
+ }
38
+ function readTreeSettings(file) {
39
+ if (!existsSync(file)) return {};
40
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
41
+ if (typeof parsed !== "object" || parsed === null || !("check-tree" in parsed)) return {};
42
+ const config = parsed["check-tree"];
43
+ if (!isTreeSettings(config)) throw new Error(`the "check-tree" key of ${file} holds an object with categories (a list of strings), rootEntries (a boolean) and platforms (a list of strings), all optional`);
44
+ return config;
45
+ }
6
46
  // src/checkTree.ts
7
47
  const { values, positionals } = parseArgs({
8
48
  allowPositionals: true,
9
49
  options: {
10
50
  categories: { type: "string" },
11
- "root-entries": { type: "boolean" }
51
+ platforms: { type: "string" },
52
+ "root-entries": { type: "boolean" },
53
+ "write-known-violations": { type: "boolean" }
12
54
  }
13
55
  });
14
56
  const folder = positionals[0] ?? "src";
15
- const categories = values.categories?.split(",").map((category) => category.trim());
57
+ function listFlag(flag) {
58
+ return flag?.split(",").map((entry) => entry.trim());
59
+ }
16
60
  try {
17
- const violations = [...treeViolations(resolve(folder), categories, { rootEntries: values["root-entries"] === true }), ...sliceViolations(folder, await cruiseImports(folder))];
18
- for (const violation of violations) console.error(violation);
19
- process.exitCode = violations.length === 0 ? 0 : 1;
61
+ const settings = readTreeSettings("package.json");
62
+ const categories = listFlag(values.categories) ?? settings.categories;
63
+ const platforms = listFlag(values.platforms) ?? settings.platforms;
64
+ const violations = [...treeViolations(resolve(folder), categories, {
65
+ rootEntries: values["root-entries"] === true || settings.rootEntries === true,
66
+ platforms
67
+ }), ...sliceViolations(folder, await cruiseImports(folder), platforms)];
68
+ if (values["write-known-violations"] === true) writeKnownViolations(violations, KNOWN_VIOLATIONS_FILE);
69
+ else {
70
+ const reported = unknownViolations(violations, KNOWN_VIOLATIONS_FILE);
71
+ for (const violation of reported) console.error(violation);
72
+ process.exitCode = reported.length === 0 ? 0 : 1;
73
+ }
20
74
  } catch (error) {
21
75
  console.error(error instanceof Error ? error.message : String(error));
22
76
  process.exitCode = 1;
@@ -0,0 +1,15 @@
1
+ // src/shared/platform-variants/PlatformVariantsConfig.ts
2
+ const DEFAULT_PLATFORMS = [
3
+ "web",
4
+ "ios",
5
+ "android",
6
+ "native"
7
+ ];
8
+ // src/shared/platform-variants/platformBase.ts
9
+ function platformBase(fileName, platforms = DEFAULT_PLATFORMS) {
10
+ const parts = fileName.split(".");
11
+ const platform = parts.at(-2);
12
+ if (parts.length < 3 || platform === void 0 || !platforms.includes(platform)) return fileName;
13
+ return [...parts.slice(0, -2), parts.at(-1)].join(".");
14
+ }
15
+ export { platformBase as t };
@@ -1 +1 @@
1
- export declare function sharedViolations(root: string): Promise<string[]>;
1
+ export declare function sharedViolations(root: string, platforms?: readonly string[]): Promise<string[]>;
@@ -1,6 +1,6 @@
1
- import { n as cruiseImports, t as sliceViolations } from "./sliceViolations-DojT6WkL.js";
1
+ import { n as cruiseImports, t as sliceViolations } from "./sliceViolations-BfTZYfD3.js";
2
2
  // src/sharedViolations.ts
3
- async function sharedViolations(root) {
4
- return sliceViolations(root, await cruiseImports(root));
3
+ async function sharedViolations(root, platforms) {
4
+ return sliceViolations(root, await cruiseImports(root), platforms);
5
5
  }
6
6
  export { sharedViolations };
@@ -1,4 +1,5 @@
1
- import { dirname, normalize } from "node:path";
1
+ import { t as platformBase } from "./platformBase-iFIwMidD.js";
2
+ import { basename, dirname, normalize } from "node:path";
2
3
  import { existsSync } from "node:fs";
3
4
  import { cruise } from "dependency-cruiser";
4
5
  import extractDepcruiseOptions from "dependency-cruiser/config-utl/extract-depcruise-options";
@@ -90,6 +91,17 @@ function sharedConsumerViolations(checkedFolder, modules) {
90
91
  return [violation(shown(source), shown(slice.owner), shown(slot))];
91
92
  });
92
93
  }
94
+ // src/features/shared-consumers/lib/variantLinks.ts
95
+ function variantLinks(files, platforms) {
96
+ const firsts = /* @__PURE__ */ new Map();
97
+ return [...files].flatMap((file) => {
98
+ const unit = `${dirname(file)}/${platformBase(basename(file), platforms)}`;
99
+ const first = firsts.get(unit);
100
+ if (first !== void 0) return [[file, first]];
101
+ firsts.set(unit, file);
102
+ return [];
103
+ });
104
+ }
93
105
  // src/features/shared-consumers/lib/sliceGroupViolations.ts
94
106
  function sliceFolders(root, modules) {
95
107
  const folders = /* @__PURE__ */ new Map();
@@ -99,8 +111,11 @@ function sliceFolders(root, modules) {
99
111
  }
100
112
  return folders;
101
113
  }
102
- function linkedGroups(modules, folders) {
103
- const parents = new Map([...folders.keys()].map((file) => [file, file]));
114
+ function importLinks(modules, folders) {
115
+ return modules.flatMap(({ source, imports }) => imports.filter((target) => folders.has(source) && folders.get(target) === folders.get(source)).map((target) => [source, target]));
116
+ }
117
+ function linkedGroups(files, links) {
118
+ const parents = new Map([...files].map((file) => [file, file]));
104
119
  function head(file) {
105
120
  const parent = parents.get(file) ?? file;
106
121
  if (parent === file) return file;
@@ -108,10 +123,7 @@ function linkedGroups(modules, folders) {
108
123
  parents.set(file, found);
109
124
  return found;
110
125
  }
111
- for (const { source, imports } of modules) {
112
- const folder = folders.get(source);
113
- for (const target of imports) if (folder !== void 0 && folders.get(target) === folder) parents.set(head(source), head(target));
114
- }
126
+ for (const [from, to] of links) parents.set(head(from), head(to));
115
127
  return head;
116
128
  }
117
129
  function groupsBySlice(folders, head) {
@@ -123,17 +135,18 @@ function groupsBySlice(folders, head) {
123
135
  }
124
136
  return slices;
125
137
  }
126
- function sliceGroupViolations(checkedFolder, modules) {
138
+ function sliceGroupViolations(checkedFolder, modules, platforms) {
127
139
  const { root, shown } = checkedPaths(checkedFolder);
128
140
  const folders = sliceFolders(root, modules);
129
- return [...groupsBySlice(folders, linkedGroups(modules, folders))].flatMap(([folder, groups]) => {
141
+ const links = [...importLinks(modules, folders), ...variantLinks(folders.keys(), platforms)];
142
+ return [...groupsBySlice(folders, linkedGroups(folders.keys(), links))].flatMap(([folder, groups]) => {
130
143
  if (groups.size < 2) return [];
131
144
  const listed = [...groups.values()].map((files) => `(${files.join(", ")})`).join(" ");
132
145
  return [`${shown(folder)} holds ${groups.size} groups of files that never import each other ${listed}: split it into one slice per group`];
133
146
  });
134
147
  }
135
148
  // src/features/shared-consumers/lib/sliceViolations.ts
136
- function sliceViolations(checkedFolder, modules) {
137
- return [...sharedConsumerViolations(checkedFolder, modules), ...sliceGroupViolations(checkedFolder, modules)];
149
+ function sliceViolations(checkedFolder, modules, platforms) {
150
+ return [...sharedConsumerViolations(checkedFolder, modules), ...sliceGroupViolations(checkedFolder, modules, platforms)];
138
151
  }
139
152
  export { cruiseImports as n, sliceViolations as t };
@@ -1,3 +1,4 @@
1
+ import { t as platformBase } from "./platformBase-iFIwMidD.js";
1
2
  import { basename, dirname, join, relative } from "node:path";
2
3
  import { readdirSync } from "node:fs";
3
4
  // src/features/tree-violations/TreeViolationsConfig.ts
@@ -184,17 +185,18 @@ function groupViolations(name, folderName, listing, categoryFolders) {
184
185
  const holdsFilesOnly = categoryFolders.has(folderName) && listing.folders.size === 0;
185
186
  return FILE_GROUPS.flatMap(({ folder, belongs, appliesIn }) => {
186
187
  if (!categoryFolders.has(folder) || !appliesIn(folderName)) return [];
187
- const loose = listing.files.filter(belongs);
188
+ const loose = listing.files.filter((file) => belongs(listing.baseOf(file)));
188
189
  if (loose.length === 0 || holdsFilesOnly && loose.length === listing.files.length) return [];
189
190
  if (listing.folders.has(folder)) return [`${name} has a ${folder}/ folder: move ${loose.join(", ")} into it`];
190
- if (loose.length === 1) return [];
191
+ if (new Set(loose.map(listing.baseOf)).size === 1) return [];
191
192
  return [`${name} holds ${loose.length} ${folder} files (${loose.join(", ")}): move them into ${folder}/`];
192
193
  });
193
194
  }
194
- function folderListing(entries) {
195
+ function folderListing(entries, platforms) {
195
196
  return {
196
197
  files: entries.filter((entry) => entry.isFile()).map((entry) => entry.name).toSorted(),
197
- folders: new Set(entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name))
198
+ folders: new Set(entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name)),
199
+ baseOf: (fileName) => platformBase(fileName, platforms)
198
200
  };
199
201
  }
200
202
  function shapeViolations(name, count, isCategory) {
@@ -202,20 +204,23 @@ function shapeViolations(name, count, isCategory) {
202
204
  if (count === 1 && isCategory) return [`${name} holds a single child: move it up one level and delete the folder`];
203
205
  return [];
204
206
  }
205
- function folderViolations(folder, name, categoryFolders, check) {
207
+ function folderViolations(folder, name, scan, check) {
206
208
  const children = readdirSync(folder, { withFileTypes: true }).filter((entry) => !TEST_FILE.test(entry.name));
207
- const violations = shapeViolations(name, children.length, categoryFolders.has(basename(folder)));
208
- const listing = folderListing(children);
209
+ const listing = folderListing(children, scan.platforms);
210
+ const violations = shapeViolations(name, new Set(listing.files.map(listing.baseOf)).size + children.length - listing.files.length, scan.categories.has(basename(folder)));
209
211
  if (check === "slices") return [...violations, ...sliceFileViolations(name, listing.files)];
210
212
  if (check === "none") return violations;
211
- return [...violations, ...groupViolations(name, basename(folder), listing, categoryFolders)];
213
+ return [...violations, ...groupViolations(name, basename(folder), listing, scan.categories)];
212
214
  }
213
215
  function treeViolations(root, categoryFolders = DEFAULT_CATEGORY_FOLDERS, options = {}) {
214
- const categories = new Set(categoryFolders);
216
+ const scan = {
217
+ categories: new Set(categoryFolders),
218
+ platforms: options.platforms
219
+ };
215
220
  function walk(folder, layer) {
216
221
  const name = relative(join(root, ".."), folder);
217
- return [...folderViolations(folder, name, categories, filesCheck(layer, folder === root && options.rootEntries === true)), ...readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
218
- const child = childLayer(layer, `${name}/${entry.name}`, categories);
222
+ return [...folderViolations(folder, name, scan, filesCheck(layer, folder === root && options.rootEntries === true)), ...readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
223
+ const child = childLayer(layer, `${name}/${entry.name}`, scan.categories);
219
224
  return [...child.violations, ...walk(join(folder, entry.name), child.layer)];
220
225
  })];
221
226
  }
@@ -1,5 +1,6 @@
1
1
  type TreeOptions = {
2
2
  rootEntries?: boolean;
3
+ platforms?: readonly string[] | undefined;
3
4
  };
4
5
  export declare function treeViolations(root: string, categoryFolders?: readonly string[], options?: TreeOptions): string[];
5
6
  export {};
@@ -1 +1 @@
1
- export { t as treeViolations } from "./treeViolations-CEQ5ks7L.js";
1
+ export { t as treeViolations } from "./treeViolations-DV1n3hcr.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brutalway/check-tree",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
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 a slice of shared/ used by a single feature, no slice whose files never import each other.",
5
5
  "keywords": [
6
6
  "lint",
@@ -36,7 +36,7 @@
36
36
  "typecheck": "tsc -p .",
37
37
  "lint": "oxlint --type-aware src oxlint.config.ts tsdown.config.ts",
38
38
  "deps": "depcruise --output-type err-long src",
39
- "tree": "node src/checkTree.ts src --root-entries",
39
+ "tree": "node src/checkTree.ts src",
40
40
  "duplicates": "jscpd src",
41
41
  "check": "prettier --check . && npm run typecheck && npm run lint && npm run deps && npm run tree && npm run duplicates && npm run unused",
42
42
  "test": "node --test 'src/**/*.test.ts'",
@@ -44,7 +44,7 @@
44
44
  "unused": "knip"
45
45
  },
46
46
  "devDependencies": {
47
- "@brutalway/dependency-cruiser-config": "0.5.0",
47
+ "@brutalway/dependency-cruiser-config": "0.10.0",
48
48
  "@brutalway/oxlint-config-node": "0.2.1",
49
49
  "@brutalway/oxlint-config-node-test": "0.1.0",
50
50
  "@brutalway/prettier-config": "0.3.0",
@@ -64,6 +64,9 @@
64
64
  "#src/*": "./src/*"
65
65
  },
66
66
  "prettier": "@brutalway/prettier-config",
67
+ "check-tree": {
68
+ "rootEntries": true
69
+ },
67
70
  "allowScripts": {
68
71
  "@swc/core": false
69
72
  },