@zgeoff/oxlint-config 0.8.6 → 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
@@ -80,6 +80,9 @@ The plugin is addressable on its own at `@zgeoff/oxlint-config/plugin` for confi
80
80
  [require functions](../../docs/architecture/oxlint-config.md#require-functions).
81
81
  - Import boundaries: `zgeoff/import-zones` fails an import that crosses a declared zone boundary.
82
82
  See [import zones](../../docs/architecture/oxlint-config-import-zones.md).
83
+ - Feature folders: `zgeoff/feature-folders` caps the loose modules at the root of a package's
84
+ `src/`, and keeps shared code in `src/utils/`. See
85
+ [feature folders](../../docs/architecture/oxlint-config-feature-folders.md).
83
86
 
84
87
  ## Configuration
85
88
 
@@ -0,0 +1,5 @@
1
+ const extensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
2
+
3
+ export default function buildImportSettings(root) {
4
+ return { root, extensions, conditions: new Set(['default']), workspaces: [] };
5
+ }
@@ -0,0 +1,41 @@
1
+ import { resolve } from 'node:path';
2
+
3
+ export default function collectEntryTargets(directory, manifest) {
4
+ const targets = [
5
+ manifest.main,
6
+ manifest.module,
7
+ ...collectStringLeaves(manifest.bin),
8
+ ...collectStringLeaves(manifest.exports),
9
+ ...Object.values(manifest.scripts ?? {}).flatMap((script) => collectScriptPaths(script)),
10
+ ];
11
+
12
+ return new Set(
13
+ targets
14
+ .filter((target) => typeof target === 'string' && !target.includes('*'))
15
+ .map((target) => resolve(directory, target)),
16
+ );
17
+ }
18
+
19
+ function collectStringLeaves(value) {
20
+ if (typeof value === 'string') {
21
+ return [value];
22
+ }
23
+
24
+ if (typeof value !== 'object' || value === null) {
25
+ return [];
26
+ }
27
+
28
+ return Object.values(value).flatMap((leaf) => collectStringLeaves(leaf));
29
+ }
30
+
31
+ function collectScriptPaths(script) {
32
+ if (typeof script !== 'string') {
33
+ return [];
34
+ }
35
+
36
+ return script
37
+ .split(/\s+/u)
38
+ .map((word) => word.replaceAll(/["']/gu, ''))
39
+ .map((word) => word.slice(word.lastIndexOf('=') + 1))
40
+ .filter((word) => word !== '');
41
+ }
@@ -0,0 +1,173 @@
1
+ import { basename, join, posix, relative, sep } from 'node:path';
2
+ import buildImportSettings from './build-import-settings.js';
3
+ import findFeatureFolder from './find-feature-folder.js';
4
+ import pickFolderKind from './pick-folder-kind.js';
5
+ import pickLooseModuleMessage from './pick-loose-module-message.js';
6
+ import readLooseModules from './read-loose-modules.js';
7
+ import readStalePending from './read-stale-pending.js';
8
+ import resolveImportTarget from './resolve-import-target.js';
9
+ import resolveRepoRoot from './resolve-repo-root.js';
10
+ import resolveSourcePackage from './resolve-source-package.js';
11
+
12
+ const looseModuleLimit = 8;
13
+
14
+ const capLine = `{{source}} holds {{count}} loose modules, and the limit is ${looseModuleLimit}. Group them into one folder per thing the package does:`;
15
+
16
+ const exampleTree = `
17
+
18
+ src/
19
+ index.ts cli.ts index.ts, types.ts, constants.ts and the files package.json names stay
20
+ invoices/ create-invoice.ts format-invoice-total.ts
21
+ payments/ charge-card.ts refund-payment.ts
22
+ utils/ to-cents.ts code that several folders share`;
23
+
24
+ // a report on one file per repo shows once per run, and an editor's
25
+ // language server keeps it on that file across edits
26
+ const anchorFiles = new Map();
27
+
28
+ const featureFolders = {
29
+ meta: {
30
+ type: 'suggestion',
31
+ messages: {
32
+ capExample: `${capLine}${exampleTree}`,
33
+ cap: capLine,
34
+ synonym: '{{folder}} is a shared folder under another name; rename it to src/utils/.',
35
+ utilsImport:
36
+ '{{from}} imports {{to}}, and utils/ sits below every feature folder. Move {{target}} into utils/, or move {{module}} into {{feature}}/.',
37
+ pendingPasses:
38
+ '`{{entry}}` in the `pending` option of zgeoff/feature-folders now passes the rule; remove it from `pending`.',
39
+ pendingMissing:
40
+ '`{{entry}}` in the `pending` option of zgeoff/feature-folders names no package; remove it from `pending`.',
41
+ },
42
+ schema: [
43
+ {
44
+ type: 'object',
45
+ properties: { pending: { type: 'array', items: { type: 'string' } } },
46
+ additionalProperties: false,
47
+ },
48
+ ],
49
+ },
50
+ create(context) {
51
+ const filename = context.physicalFilename;
52
+ const root = resolveRepoRoot(filename) ?? context.cwd;
53
+ const pending = (context.options[0]?.pending ?? []).map((entry) => toPendingPath(entry));
54
+ const sourcePackage = resolveSourcePackage(filename);
55
+ const isChecked =
56
+ sourcePackage !== null && !pending.includes(toRootPath(root, sourcePackage.directory));
57
+
58
+ if (!anchorFiles.has(root)) {
59
+ anchorFiles.set(root, filename);
60
+ }
61
+
62
+ const file = { context, filename, root, sourcePackage };
63
+ const visitors =
64
+ isChecked && pickFolderKind(sourcePackage.path.split('/')[0]) === 'utils'
65
+ ? buildUtilsVisitors(file)
66
+ : {};
67
+
68
+ return {
69
+ ...visitors,
70
+ Program(program) {
71
+ const start = program.body[0]?.loc.start ?? { line: 1, column: 0 };
72
+ const at = { loc: { start, end: start } };
73
+
74
+ if (anchorFiles.get(root) === filename) {
75
+ for (const stale of readStalePending(root, pending, looseModuleLimit)) {
76
+ context.report({ ...at, messageId: stale.messageId, data: { entry: stale.entry } });
77
+ }
78
+ }
79
+
80
+ if (isChecked) {
81
+ checkLooseModule(file, at);
82
+ checkSynonymFolder(file, at);
83
+ }
84
+ },
85
+ };
86
+ },
87
+ };
88
+
89
+ export default featureFolders;
90
+
91
+ function toPendingPath(entry) {
92
+ return posix.normalize(entry).replace(/(?<=.)\/+$/u, '');
93
+ }
94
+
95
+ function toRootPath(root, path) {
96
+ return relative(root, path).split(sep).join('/') || '.';
97
+ }
98
+
99
+ function buildUtilsVisitors(file) {
100
+ const settings = buildImportSettings(file.root);
101
+ const check = (node) => {
102
+ if (node.source?.type === 'Literal' && typeof node.source.value === 'string') {
103
+ checkUtilsImport(file, { node, specifier: node.source.value, settings });
104
+ }
105
+ };
106
+
107
+ return {
108
+ ImportDeclaration: check,
109
+ ExportNamedDeclaration: check,
110
+ ExportAllDeclaration: check,
111
+ ImportExpression: check,
112
+ };
113
+ }
114
+
115
+ function checkUtilsImport(file, imported) {
116
+ const target = resolveImportTarget(file.filename, imported.specifier, imported.settings);
117
+ const source = join(file.sourcePackage.directory, 'src');
118
+
119
+ if (target.kind !== 'file') {
120
+ return;
121
+ }
122
+
123
+ const feature = findFeatureFolder(source, target.path);
124
+
125
+ if (feature === null) {
126
+ return;
127
+ }
128
+
129
+ file.context.report({
130
+ node: imported.node,
131
+ messageId: 'utilsImport',
132
+ data: {
133
+ from: toRootPath(file.root, file.filename),
134
+ to: `src/${toRootPath(source, target.path)}`,
135
+ target: basename(target.path),
136
+ module: basename(file.filename),
137
+ feature,
138
+ },
139
+ });
140
+ }
141
+
142
+ function checkLooseModule(file, at) {
143
+ if (file.sourcePackage.path.includes('/')) {
144
+ return;
145
+ }
146
+
147
+ const modules = readLooseModules(file.sourcePackage);
148
+ const messageID = pickLooseModuleMessage(modules, basename(file.filename), looseModuleLimit);
149
+
150
+ if (messageID === null) {
151
+ return;
152
+ }
153
+
154
+ const source = `${toRootPath(file.root, join(file.sourcePackage.directory, 'src'))}/`;
155
+
156
+ file.context.report({
157
+ ...at,
158
+ messageId: messageID,
159
+ data: { source, count: String(modules.length) },
160
+ });
161
+ }
162
+
163
+ function checkSynonymFolder(file, at) {
164
+ const [folder] = file.sourcePackage.path.split('/');
165
+
166
+ if (!file.sourcePackage.path.includes('/') || pickFolderKind(folder) !== 'synonym') {
167
+ return;
168
+ }
169
+
170
+ const path = toRootPath(file.root, join(file.sourcePackage.directory, 'src', folder));
171
+
172
+ file.context.report({ ...at, messageId: 'synonym', data: { folder: `${path}/` } });
173
+ }
@@ -0,0 +1,18 @@
1
+ import { isAbsolute, relative, sep } from 'node:path';
2
+ import pickFolderKind from './pick-folder-kind.js';
3
+
4
+ export default function findFeatureFolder(source, target) {
5
+ const path = relative(source, target);
6
+ const segments = path.split(sep);
7
+
8
+ if (
9
+ isAbsolute(path) ||
10
+ segments.length < 2 ||
11
+ segments[0] === '..' ||
12
+ pickFolderKind(segments[0]) !== 'feature'
13
+ ) {
14
+ return null;
15
+ }
16
+
17
+ return segments[0];
18
+ }
package/oxlintrc.json CHANGED
@@ -42,6 +42,7 @@
42
42
  "zgeoff/no-test-sleep": "error",
43
43
  "zgeoff/no-require": "error",
44
44
  "zgeoff/test-shape": "error",
45
+ "zgeoff/feature-folders": "error",
45
46
 
46
47
  // name a value for what it holds, in full words: one letter only for a
47
48
  // coordinate, zod's `z`, Bun's shell `$` or an unread `_` placeholder, and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/oxlint-config",
3
- "version": "0.8.6",
3
+ "version": "0.10.0",
4
4
  "description": "Shareable oxlint config: strict categories, house-style rules, and a custom JS plugin",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -59,6 +59,17 @@
59
59
  "get-zone-options.js",
60
60
  "make-glob-matcher.js",
61
61
  "resolve-import-target.js",
62
+ "feature-folders.js",
63
+ "pick-folder-kind.js",
64
+ "pick-loose-module-message.js",
65
+ "collect-entry-targets.js",
66
+ "read-loose-modules.js",
67
+ "resolve-source-package.js",
68
+ "find-feature-folder.js",
69
+ "build-import-settings.js",
70
+ "read-stale-pending.js",
71
+ "read-package-manifest.js",
72
+ "read-module-paths.js",
62
73
  "index.js"
63
74
  ],
64
75
  "type": "module",
@@ -83,8 +94,9 @@
83
94
  },
84
95
  "devDependencies": {
85
96
  "@types/bun": "1.4.4",
86
- "@zgeoff/rig": "0.1.6",
87
- "@zgeoff/testing": "0.2.1",
97
+ "@zgeoff/rig": "0.2.1",
98
+ "@zgeoff/std": "0.4.3",
99
+ "@zgeoff/testing": "0.3.0",
88
100
  "tsrs": "0.18.0-ts7.1.0-dev.20260929",
89
101
  "typescript": "7.0.2"
90
102
  },
@@ -0,0 +1,13 @@
1
+ const folderKinds = new Map([
2
+ ['utils', 'utils'],
3
+ ['test-utils', 'exempt'],
4
+ ['generated', 'exempt'],
5
+ ['lib', 'synonym'],
6
+ ['shared', 'synonym'],
7
+ ['helpers', 'synonym'],
8
+ ['common', 'synonym'],
9
+ ]);
10
+
11
+ export default function pickFolderKind(name) {
12
+ return folderKinds.get(name) ?? 'feature';
13
+ }
@@ -0,0 +1,7 @@
1
+ export default function pickLooseModuleMessage(modules, name, limit) {
2
+ if (modules.length <= limit || !modules.includes(name)) {
3
+ return null;
4
+ }
5
+
6
+ return modules[0] === name ? 'capExample' : 'cap';
7
+ }
package/plugin.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';
2
2
  // oxlint-disable-next-line zgeoff/no-require -- only resolves rig's path from the repo root; an import loads it
3
3
  import { createRequire } from 'node:module';
4
4
  import { join } from 'node:path';
5
+ import featureFolders from './feature-folders.js';
5
6
  import functionVerb from './function-verb.js';
6
7
  import importZones from './import-zones.js';
7
8
  import maxConsecutiveLineComments from './max-consecutive-line-comments.js';
@@ -131,6 +132,7 @@ const plugin = {
131
132
  'no-require': noRequire,
132
133
  'test-shape': testShape,
133
134
  'import-zones': importZones,
135
+ 'feature-folders': featureFolders,
134
136
  },
135
137
  };
136
138
 
@@ -0,0 +1,22 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import collectEntryTargets from './collect-entry-targets.js';
4
+ import readModulePaths from './read-module-paths.js';
5
+
6
+ export default function readLooseModules(sourcePackage) {
7
+ const targets = collectEntryTargets(sourcePackage.directory, sourcePackage.manifest);
8
+ const entries = readdirSync(join(sourcePackage.directory, 'src'), { withFileTypes: true });
9
+
10
+ return readModulePaths(entries)
11
+ .filter((path) => !targets.has(path) && isCountedModule(basename(path)))
12
+ .map((path) => basename(path))
13
+ .toSorted();
14
+ }
15
+
16
+ const declarationPattern = /\.d\.[cm]?ts$/u;
17
+ const testPattern = /\.(?:test|bench|spec)\.[cm]?[jt]sx?$/u;
18
+ const exemptPattern = /^(?:index|types|constants)\.[cm]?[jt]sx?$/u;
19
+
20
+ function isCountedModule(name) {
21
+ return !declarationPattern.test(name) && !testPattern.test(name) && !exemptPattern.test(name);
22
+ }
@@ -0,0 +1,12 @@
1
+ import { statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ const modulePattern = /\.[cm]?[jt]sx?$/u;
5
+
6
+ // takes readdir entries and follows a symlink, so a linked module counts as the file it points at
7
+ export default function readModulePaths(entries) {
8
+ return entries
9
+ .filter((entry) => modulePattern.test(entry.name))
10
+ .map((entry) => join(entry.parentPath, entry.name))
11
+ .filter((path) => statSync(path, { throwIfNoEntry: false })?.isFile() ?? false);
12
+ }
@@ -0,0 +1,14 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ // a manifest that does not parse to an object names no entry files, and lint goes on; the package
5
+ // manager reports the broken file itself
6
+ export default function readPackageManifest(directory) {
7
+ try {
8
+ const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
9
+
10
+ return typeof manifest === 'object' && manifest !== null ? manifest : {};
11
+ } catch {
12
+ return {};
13
+ }
14
+ }
@@ -0,0 +1,72 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import buildImportSettings from './build-import-settings.js';
4
+ import findFeatureFolder from './find-feature-folder.js';
5
+ import pickFolderKind from './pick-folder-kind.js';
6
+ import readLooseModules from './read-loose-modules.js';
7
+ import readModulePaths from './read-module-paths.js';
8
+ import readPackageManifest from './read-package-manifest.js';
9
+ import resolveImportTarget from './resolve-import-target.js';
10
+
11
+ export default function readStalePending(root, pending, limit) {
12
+ return pending.flatMap((entry) => {
13
+ const directory = join(root, entry);
14
+
15
+ if (!existsSync(join(directory, 'package.json'))) {
16
+ return [{ entry, messageId: 'pendingMissing' }];
17
+ }
18
+
19
+ return probePackagePassing(root, directory, limit)
20
+ ? [{ entry, messageId: 'pendingPasses' }]
21
+ : [];
22
+ });
23
+ }
24
+
25
+ function probePackagePassing(root, directory, limit) {
26
+ const source = join(directory, 'src');
27
+
28
+ if (!existsSync(source)) {
29
+ return true;
30
+ }
31
+
32
+ const manifest = readPackageManifest(directory);
33
+ const synonyms = readdirSync(source, { withFileTypes: true }).filter(
34
+ (entry) => entry.isDirectory() && pickFolderKind(entry.name) === 'synonym',
35
+ );
36
+
37
+ return (
38
+ readLooseModules({ directory, manifest }).length <= limit &&
39
+ !synonyms.some((folder) => readFolderModules(join(source, folder.name)).length > 0) &&
40
+ !probeUtilsFeatureImport(root, source)
41
+ );
42
+ }
43
+
44
+ function readFolderModules(folder) {
45
+ return existsSync(folder)
46
+ ? readModulePaths(readdirSync(folder, { recursive: true, withFileTypes: true }))
47
+ : [];
48
+ }
49
+
50
+ // a text scan stands in for the parse that only the linted file gets: comments go first, so a
51
+ // specifier that only a string holds is the one case that keeps the entry
52
+ const commentPattern =
53
+ /(?<text>"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')|\/\/[^\n]*|\/\*[\s\S]*?\*\//gu;
54
+ const specifierPattern =
55
+ /(?:\bfrom|\bimport)\s*\(?\s*(?<quote>["'])(?<specifier>[^"'\n]+)\k<quote>/gu;
56
+
57
+ function probeUtilsFeatureImport(root, source) {
58
+ const settings = buildImportSettings(root);
59
+
60
+ return readFolderModules(join(source, 'utils')).some((filename) => {
61
+ const text = readFileSync(filename, 'utf8').replaceAll(
62
+ commentPattern,
63
+ (...match) => match.at(-1).text ?? '',
64
+ );
65
+
66
+ return [...text.matchAll(specifierPattern)].some((match) => {
67
+ const target = resolveImportTarget(filename, match.groups.specifier, settings);
68
+
69
+ return target.kind === 'file' && findFeatureFolder(source, target.path) !== null;
70
+ });
71
+ });
72
+ }
@@ -1,13 +1,14 @@
1
- import { existsSync, readFileSync, statSync } from 'node:fs';
1
+ import { existsSync, statSync } from 'node:fs';
2
2
  import { isBuiltin } from 'node:module';
3
3
  import { dirname, join, resolve } from 'node:path';
4
+ import readPackageManifest from './read-package-manifest.js';
4
5
 
5
6
  export default function resolveImportTarget(filename, specifier, settings) {
6
7
  if (isPathSpecifier(specifier)) {
7
8
  return toTarget(resolveImportedFile(filename, toFileSpecifier(specifier), settings.extensions));
8
9
  }
9
10
 
10
- const manifest = readPackageManifest(dirname(filename), settings.root);
11
+ const manifest = resolveNearestManifest(dirname(filename), settings.root);
11
12
 
12
13
  return resolveManifestTarget(manifest, specifier, settings);
13
14
  }
@@ -54,7 +55,7 @@ function toFileSpecifier(specifier) {
54
55
 
55
56
  const manifests = new Map();
56
57
 
57
- function readPackageManifest(directory, root) {
58
+ function resolveNearestManifest(directory, root) {
58
59
  if (manifests.has(directory)) {
59
60
  return manifests.get(directory);
60
61
  }
@@ -64,9 +65,9 @@ function readPackageManifest(directory, root) {
64
65
  let manifest = null;
65
66
 
66
67
  if (existsSync(path)) {
67
- manifest = { directory, ...JSON.parse(readFileSync(path, 'utf8')) };
68
+ manifest = { directory, ...readPackageManifest(directory) };
68
69
  } else if (directory !== root && parent !== directory) {
69
- manifest = readPackageManifest(parent, root);
70
+ manifest = resolveNearestManifest(parent, root);
70
71
  }
71
72
 
72
73
  manifests.set(directory, manifest);
@@ -0,0 +1,25 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, join, relative, sep } from 'node:path';
3
+ import readPackageManifest from './read-package-manifest.js';
4
+
5
+ // the package is the nearest folder above the file whose `src/` holds it, so a `package.json` inside
6
+ // `src/`, such as one that sets `type`, does not stand in for the package
7
+ export default function resolveSourcePackage(filename) {
8
+ let directory = dirname(filename);
9
+
10
+ while (true) {
11
+ const path = relative(join(directory, 'src'), filename).split(sep).join('/');
12
+
13
+ if (!path.startsWith('../') && existsSync(join(directory, 'package.json'))) {
14
+ return { directory, manifest: readPackageManifest(directory), path };
15
+ }
16
+
17
+ const parent = dirname(directory);
18
+
19
+ if (parent === directory) {
20
+ return null;
21
+ }
22
+
23
+ directory = parent;
24
+ }
25
+ }
@@ -12,7 +12,7 @@ export default function buildTestBesideModule(rigLanes) {
12
12
  type: 'problem',
13
13
  messages: {
14
14
  missing:
15
- 'Move this test beside the module it tests: no `{{name}}.<ext>` sits in this directory. A flow across several packages belongs in `integration/`, and a test that drives the built product in `e2e/`, at the repo root or an app root.',
15
+ 'Move this test beside the module it tests: no `{{name}}.<ext>` sits in this directory. A test that runs the built program belongs in `e2e/` of the package that builds it, and an evaluation in `evals/` of the package whose code it scores.',
16
16
  rigLanes:
17
17
  'Declare lanes in rig.config.ts only: this repo has one, and the `lanes` option here would give the lanes a second source.',
18
18
  },