@brutalway/check-tree 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,21 +13,33 @@ 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
16
+ ### Set the options in package.json
17
17
 
18
- ```sh
19
- npx check-tree src --categories components,hooks,utils
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.
27
39
 
28
- ```sh
29
- npx check-tree src --root-entries
30
- ```
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.
31
43
 
32
44
  ### Keep the violations of an existing tree
33
45
 
@@ -53,7 +65,7 @@ import { treeViolations } from '@brutalway/check-tree/treeViolations';
53
65
  const violations = treeViolations('src');
54
66
  ```
55
67
 
56
- 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:
57
69
 
58
70
  ```ts
59
71
  import { sharedViolations } from '@brutalway/check-tree/sharedViolations';
@@ -102,15 +114,20 @@ So a feature with two components puts them in `components/`, and a `components/`
102
114
 
103
115
  Test files (`*.test.ts`, `*.test.tsx`) are not counted.
104
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
+
105
119
  ### Output
106
120
 
107
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.
108
122
 
109
123
  ### Options
110
124
 
111
- | Option | Default |
112
- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
113
- | folder | `src` |
114
- | `--categories <list>` | `components`, `orchestrators`, `presenters`, `hooks`, `styles`, `types`, `configs`, `stores`, `routes`, `services`, `queries`, `keys`, `schemas`, `clients`, `workers`, `lib` |
115
- | `--root-entries` | off |
116
- | `--write-known-violations` | 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,15 +1,16 @@
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-B4iDNwD2.js";
4
4
  import { resolve } from "node:path";
5
5
  import { parseArgs } from "node:util";
6
6
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
7
7
  // src/features/known-violations/KnownViolationsConfig.ts
8
8
  const KNOWN_VIOLATIONS_FILE = ".check-tree-known-violations.json";
9
- // src/features/known-violations/knownViolations.ts
9
+ // src/shared/string-lists/isStringList.ts
10
10
  function isStringList(value) {
11
11
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
12
12
  }
13
+ // src/features/known-violations/knownViolations.ts
13
14
  function readKnownViolations(file) {
14
15
  if (!existsSync(file)) return [];
15
16
  const parsed = JSON.parse(readFileSync(file, "utf8"));
@@ -24,19 +25,46 @@ function unknownViolations(violations, file) {
24
25
  function writeKnownViolations(violations, file) {
25
26
  writeFileSync(file, `${JSON.stringify(violations.toSorted(), void 0, 2)}\n`);
26
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
+ }
27
46
  // src/checkTree.ts
28
47
  const { values, positionals } = parseArgs({
29
48
  allowPositionals: true,
30
49
  options: {
31
50
  categories: { type: "string" },
51
+ platforms: { type: "string" },
32
52
  "root-entries": { type: "boolean" },
33
53
  "write-known-violations": { type: "boolean" }
34
54
  }
35
55
  });
36
56
  const folder = positionals[0] ?? "src";
37
- const categories = values.categories?.split(",").map((category) => category.trim());
57
+ function listFlag(flag) {
58
+ return flag?.split(",").map((entry) => entry.trim());
59
+ }
38
60
  try {
39
- const violations = [...treeViolations(resolve(folder), categories, { rootEntries: values["root-entries"] === true }), ...sliceViolations(folder, await cruiseImports(folder))];
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)];
40
68
  if (values["write-known-violations"] === true) writeKnownViolations(violations, KNOWN_VIOLATIONS_FILE);
41
69
  else {
42
70
  const reported = unknownViolations(violations, KNOWN_VIOLATIONS_FILE);
@@ -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-B4iDNwD2.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";
@@ -45,13 +46,19 @@ function slotOf(owner, importer) {
45
46
  const slice = SLICE.exec(importer.slice(owner.length + 1));
46
47
  return slice === null ? owner : `${owner}/${slice[0]}`;
47
48
  }
48
- function importersByModule(modules) {
49
+ function unitOf(path, platforms) {
50
+ return `${dirname(path)}/${platformBase(basename(path), platforms)}`;
51
+ }
52
+ function importersByUnit(modules, platforms) {
49
53
  const importers = /* @__PURE__ */ new Map();
50
- for (const { source, imports } of modules) for (const target of imports) importers.set(target, [...importers.get(target) ?? [], source]);
54
+ for (const { source, imports } of modules) for (const target of imports) {
55
+ const unit = unitOf(target, platforms);
56
+ importers.set(unit, [...importers.get(unit) ?? [], source]);
57
+ }
51
58
  return importers;
52
59
  }
53
- function consumerSlots(modules) {
54
- const importers = importersByModule(modules);
60
+ function consumerSlots(modules, platforms) {
61
+ const importers = importersByUnit(modules, platforms);
55
62
  const slotsByModule = /* @__PURE__ */ new Map();
56
63
  return function slots(path, slice) {
57
64
  const key = `${slice.folder}:${path}`;
@@ -59,7 +66,7 @@ function consumerSlots(modules) {
59
66
  if (known !== void 0) return known;
60
67
  const found = /* @__PURE__ */ new Set();
61
68
  slotsByModule.set(key, found);
62
- for (const importer of importers.get(path) ?? []) if (importer.startsWith(`${slice.folder}/`)) for (const slot of slots(importer, slice)) found.add(slot);
69
+ for (const importer of importers.get(unitOf(path, platforms)) ?? []) if (importer.startsWith(`${slice.folder}/`)) for (const slot of slots(importer, slice)) found.add(slot);
63
70
  else found.add(slotOf(slice.owner, importer));
64
71
  return found;
65
72
  };
@@ -78,9 +85,9 @@ function violation(path, owner, slot) {
78
85
  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}`;
79
86
  return `${path} is only used by ${slot}: move it into ${slot}`;
80
87
  }
81
- function sharedConsumerViolations(checkedFolder, modules) {
88
+ function sharedConsumerViolations(checkedFolder, modules, platforms) {
82
89
  const { root, shown } = checkedPaths(checkedFolder);
83
- const slots = consumerSlots(modules);
90
+ const slots = consumerSlots(modules, platforms);
84
91
  return modules.flatMap(({ source }) => {
85
92
  const slice = sliceOf(source);
86
93
  if (slice === void 0 || TEST_CODE.test(source) || !source.startsWith(`${root}/`)) return [];
@@ -90,6 +97,17 @@ function sharedConsumerViolations(checkedFolder, modules) {
90
97
  return [violation(shown(source), shown(slice.owner), shown(slot))];
91
98
  });
92
99
  }
100
+ // src/features/shared-consumers/lib/variantLinks.ts
101
+ function variantLinks(files, platforms) {
102
+ const firsts = /* @__PURE__ */ new Map();
103
+ return [...files].flatMap((file) => {
104
+ const unit = `${dirname(file)}/${platformBase(basename(file), platforms)}`;
105
+ const first = firsts.get(unit);
106
+ if (first !== void 0) return [[file, first]];
107
+ firsts.set(unit, file);
108
+ return [];
109
+ });
110
+ }
93
111
  // src/features/shared-consumers/lib/sliceGroupViolations.ts
94
112
  function sliceFolders(root, modules) {
95
113
  const folders = /* @__PURE__ */ new Map();
@@ -99,8 +117,11 @@ function sliceFolders(root, modules) {
99
117
  }
100
118
  return folders;
101
119
  }
102
- function linkedGroups(modules, folders) {
103
- const parents = new Map([...folders.keys()].map((file) => [file, file]));
120
+ function importLinks(modules, folders) {
121
+ return modules.flatMap(({ source, imports }) => imports.filter((target) => folders.has(source) && folders.get(target) === folders.get(source)).map((target) => [source, target]));
122
+ }
123
+ function linkedGroups(files, links) {
124
+ const parents = new Map([...files].map((file) => [file, file]));
104
125
  function head(file) {
105
126
  const parent = parents.get(file) ?? file;
106
127
  if (parent === file) return file;
@@ -108,10 +129,7 @@ function linkedGroups(modules, folders) {
108
129
  parents.set(file, found);
109
130
  return found;
110
131
  }
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
- }
132
+ for (const [from, to] of links) parents.set(head(from), head(to));
115
133
  return head;
116
134
  }
117
135
  function groupsBySlice(folders, head) {
@@ -123,17 +141,18 @@ function groupsBySlice(folders, head) {
123
141
  }
124
142
  return slices;
125
143
  }
126
- function sliceGroupViolations(checkedFolder, modules) {
144
+ function sliceGroupViolations(checkedFolder, modules, platforms) {
127
145
  const { root, shown } = checkedPaths(checkedFolder);
128
146
  const folders = sliceFolders(root, modules);
129
- return [...groupsBySlice(folders, linkedGroups(modules, folders))].flatMap(([folder, groups]) => {
147
+ const links = [...importLinks(modules, folders), ...variantLinks(folders.keys(), platforms)];
148
+ return [...groupsBySlice(folders, linkedGroups(folders.keys(), links))].flatMap(([folder, groups]) => {
130
149
  if (groups.size < 2) return [];
131
150
  const listed = [...groups.values()].map((files) => `(${files.join(", ")})`).join(" ");
132
151
  return [`${shown(folder)} holds ${groups.size} groups of files that never import each other ${listed}: split it into one slice per group`];
133
152
  });
134
153
  }
135
154
  // src/features/shared-consumers/lib/sliceViolations.ts
136
- function sliceViolations(checkedFolder, modules) {
137
- return [...sharedConsumerViolations(checkedFolder, modules), ...sliceGroupViolations(checkedFolder, modules)];
155
+ function sliceViolations(checkedFolder, modules, platforms) {
156
+ return [...sharedConsumerViolations(checkedFolder, modules, platforms), ...sliceGroupViolations(checkedFolder, modules, platforms)];
138
157
  }
139
158
  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.9.0",
3
+ "version": "0.10.1",
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'",
@@ -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
  },