@zgeoff/oxlint-config 0.4.0 → 0.5.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
@@ -10,12 +10,13 @@ that loosens either comment rule.
10
10
 
11
11
  The plugin's other rules each check one convention. `zgeoff/function-verb` bans the vague and
12
12
  near-synonym verbs of the shared function-naming rules, `zgeoff/verb-contract` checks the promise
13
- each role-table verb makes, `zgeoff/test-beside-module` keeps each test file beside the module it
14
- tests, `zgeoff/import-zones` fails an import that crosses a module boundary the repo declares,
15
- `zgeoff/no-restricted-words` keeps the words in its `words` option out of a path's text,
16
- `zgeoff/no-abbreviated-names` reports each abbreviated value name it lists with its full word,
17
- `zgeoff/no-file-snapshot` bans file snapshots, `zgeoff/setup-test-only` keeps a test file's module
18
- level to `setupTest()` and its tests, and `zgeoff/no-class` bans every class but a custom error.
13
+ each role-table verb makes, `zgeoff/module-order` keeps a file in the shared module order,
14
+ `zgeoff/test-beside-module` keeps each test file beside the module it tests, `zgeoff/import-zones`
15
+ fails an import that crosses a module boundary the repo declares, `zgeoff/no-restricted-words` keeps
16
+ the words in its `words` option out of a path's text, `zgeoff/no-abbreviated-names` reports each
17
+ abbreviated value name it lists with its full word, `zgeoff/no-file-snapshot` bans file snapshots,
18
+ `zgeoff/setup-test-only` keeps a test file's module level to `setupTest()` and its tests, and
19
+ `zgeoff/no-class` bans every class but a custom error.
19
20
 
20
21
  ## Usage
21
22
 
@@ -88,6 +89,33 @@ reads declared return types, since it runs without type information. It runs thr
88
89
  A test in this package reads the role table in the shared code-style skill and fails when the
89
90
  skill's no-I/O verbs and the rule's differ in either direction.
90
91
 
92
+ ## `zgeoff/module-order`
93
+
94
+ The rule checks the module order of the shared code-style skill in each file with a primary export.
95
+ The primary export is the default export, else the export whose name the file name kebab-cases, else
96
+ the file's only exported function or const. A file without one, such as a test file, passes. The
97
+ rule reports three breaks:
98
+
99
+ - **A helper first.** A private function sits above the primary export.
100
+ - **A helper out of composition order.** The helpers below the primary export follow it depth-first,
101
+ each in the order its first reference appears.
102
+ - **A declaration away from its first use.** A const, type alias, interface or enum sits below its
103
+ first use, or a helper sits between it and that use. A declaration the primary export uses may sit
104
+ just above it.
105
+
106
+ The config's `import/first` rule reports an import after other code, so this rule leaves imports
107
+ alone. The rule leaves a const unchecked when a helper that runs as the module loads reads it,
108
+ because the const has to sit above the code that calls that helper.
109
+
110
+ `--fix` moves each declaration it can move without a change in behaviour, with the comments above
111
+ it, in one pass. A function declaration is hoisted and a type has no value, so both always move. A
112
+ const moves only when every use sits in a function body that runs after the module loads, and its
113
+ value is static. A static value runs no code and reads nothing that load-time code can change: a
114
+ literal, a function, an array, object, `new Set`, `new Map` or `new RegExp` over static values, or
115
+ an operator or template over primitive values, with an import only as a copied value. Any other
116
+ const stays where it is, and the rule still reports it. The fix makes no change when a move would
117
+ put a statement that ends without a semicolon before one that opens with a bracket or an operator.
118
+
91
119
  ## `zgeoff/no-jsdoc` and `zgeoff/max-consecutive-line-comments`
92
120
 
93
121
  A comment holds only what neither the code, a type, a test name, nor the subsystem doc can hold: the
@@ -0,0 +1,262 @@
1
+ import isStaticValue from './is-static-value.js';
2
+
3
+ // one fix that moves every safe declaration the reports name, since oxlint
4
+ // fixes a file in one pass; `moved` holds the reported entries it moves, and
5
+ // `fix` is null when nothing can move
6
+ export default function buildModuleOrderFix(context, layout) {
7
+ const names = collectNames(context);
8
+ const reported = new Set(layout.reports.map((report) => report.entry));
9
+ const stacks = new Map();
10
+ const helpers = [];
11
+ const declarations = [];
12
+
13
+ for (const report of layout.reports) {
14
+ const entry = report.entry;
15
+
16
+ if (entry.kind === 'supporting' && isSafeToMove(entry, names)) {
17
+ declarations.push(entry);
18
+ }
19
+
20
+ if (entry.kind === 'function' && layout.ranks.has(entry) && !entry.isOverloaded) {
21
+ stacks.set(entry, collectStack(entry, layout, { reported, names }));
22
+ helpers.push(entry);
23
+ }
24
+ }
25
+
26
+ const order = buildOrder(layout, { helpers, declarations, stacks });
27
+ const isUnchanged = order.every((entry, index) => entry === layout.entries[index]);
28
+
29
+ if (isUnchanged || isJoiningStatements(context.sourceCode.text, order)) {
30
+ return { fix: null, moved: new Set() };
31
+ }
32
+
33
+ const [range, text] = renderOrder(context, layout.entries, order);
34
+
35
+ return {
36
+ fix: (fixer) => fixer.replaceTextRange(range, text),
37
+ moved: new Set([...helpers, ...declarations]),
38
+ };
39
+ }
40
+
41
+ // every name the file binds at its top level, so that a value can tell an
42
+ // import or a global from a local
43
+ function collectNames(context) {
44
+ const programScope = context.sourceCode.getScope(context.sourceCode.ast);
45
+ const scope = programScope.childScopes.find((child) => child.type === 'module') ?? programScope;
46
+ const imports = new Set();
47
+ const locals = new Set();
48
+
49
+ for (const variable of scope.variables) {
50
+ const isImport = variable.defs.some((definition) => definition.type === 'ImportBinding');
51
+
52
+ (isImport ? imports : locals).add(variable.name);
53
+ }
54
+
55
+ return { imports, locals };
56
+ }
57
+
58
+ // a type always moves safely; a const moves only when every use sits in a
59
+ // function body that runs after the module loads, and its value is static
60
+ function isSafeToMove(entry, names) {
61
+ const type = entry.declaration.type;
62
+
63
+ if (type === 'TSTypeAliasDeclaration' || type === 'TSInterfaceDeclaration') {
64
+ return true;
65
+ }
66
+
67
+ if (type !== 'VariableDeclaration') {
68
+ return false;
69
+ }
70
+
71
+ const isUsedAfterLoad = entry.references.every(
72
+ (reference) =>
73
+ reference.source === entry ||
74
+ (reference.source !== null && !reference.source.isLive && !reference.isLoadTime),
75
+ );
76
+
77
+ return isUsedAfterLoad && isStaticValue(entry.declaration.declarations[0].init, names);
78
+ }
79
+
80
+ // the unreported consts and types whose home is the helper, which sit above
81
+ // it and move with it when they move safely; a function declaration is
82
+ // hoisted, so the helper itself always moves
83
+ function collectStack(helper, layout, context) {
84
+ return layout.entries.filter(
85
+ (entry) =>
86
+ entry.kind === 'supporting' &&
87
+ layout.homes.get(entry) === helper &&
88
+ !context.reported.has(entry) &&
89
+ isSafeToMove(entry, context.names),
90
+ );
91
+ }
92
+
93
+ // each moving helper, with its stack, goes directly after the entry before it
94
+ // in the main order; then each moving const or type goes directly above the
95
+ // first entry in its home's block that uses it
96
+ function buildOrder(layout, moves) {
97
+ const moving = new Set([
98
+ ...moves.helpers.flatMap((helper) => [...moves.stacks.get(helper), helper]),
99
+ ...moves.declarations,
100
+ ]);
101
+ const order = layout.entries.filter((entry) => !moving.has(entry));
102
+ const helpers = moves.helpers.toSorted(
103
+ (first, second) => layout.ranks.get(first) - layout.ranks.get(second),
104
+ );
105
+
106
+ for (const helper of helpers) {
107
+ const previous = layout.mainOrder[layout.ranks.get(helper) - 1];
108
+
109
+ order.splice(findInsertAfter(order, previous), 0, ...moves.stacks.get(helper), helper);
110
+ }
111
+
112
+ const placed = new Set();
113
+
114
+ const place = (entry) => {
115
+ if (placed.has(entry)) {
116
+ return;
117
+ }
118
+
119
+ placed.add(entry);
120
+
121
+ const users = layout.collectBlockUsers(entry);
122
+
123
+ for (const user of users) {
124
+ if (moves.declarations.includes(user)) {
125
+ place(user);
126
+ }
127
+ }
128
+
129
+ const positions = users.map((user) => order.indexOf(user)).filter((index) => index !== -1);
130
+
131
+ order.splice(Math.min(...positions), 0, entry);
132
+ };
133
+
134
+ for (const entry of moves.declarations) {
135
+ place(entry);
136
+ }
137
+
138
+ return order;
139
+ }
140
+
141
+ // the position directly after `previous`, past an `export default` that
142
+ // names it
143
+ function findInsertAfter(order, previous) {
144
+ const at = order.indexOf(previous) + 1;
145
+ const next = order[at];
146
+ const isExportOfPrevious =
147
+ next !== undefined &&
148
+ next.statement.type === 'ExportDefaultDeclaration' &&
149
+ next.declaration.type === 'Identifier' &&
150
+ next.declaration.name === previous.name;
151
+
152
+ return isExportOfPrevious ? at + 1 : at;
153
+ }
154
+
155
+ // a statement that ends without a semicolon runs on into a next statement
156
+ // that opens with a bracket or an operator, so the fix never puts one there
157
+ function isJoiningStatements(text, order) {
158
+ return order.some(
159
+ (entry, index) =>
160
+ index > 0 &&
161
+ order[index - 1].index !== entry.index - 1 &&
162
+ !isTerminated(text, order[index - 1]) &&
163
+ /^[([`+\-/<]/u.test(text[entry.statement.range[0]]),
164
+ );
165
+ }
166
+
167
+ const blockDeclarationTypes = new Set([
168
+ 'FunctionDeclaration',
169
+ 'ClassDeclaration',
170
+ 'TSInterfaceDeclaration',
171
+ 'TSEnumDeclaration',
172
+ 'TSModuleDeclaration',
173
+ ]);
174
+
175
+ function isTerminated(text, entry) {
176
+ return (
177
+ text[entry.statement.range[1] - 1] === ';' || blockDeclarationTypes.has(entry.declaration.type)
178
+ );
179
+ }
180
+
181
+ // the range from the first entry that moves to the last, and its new text;
182
+ // an entry keeps the blank lines before it while the entry before it stays
183
+ function renderOrder(context, entries, order) {
184
+ const text = context.sourceCode.text;
185
+ const chunks = collectChunks(context, entries);
186
+ const first = entries.findIndex((entry, index) => order[index] !== entry);
187
+ const last = entries.findLastIndex((entry, index) => order[index] !== entry);
188
+ const parts = [];
189
+
190
+ for (let index = first; index <= last; index++) {
191
+ const chunk = chunks[order[index].index];
192
+
193
+ if (index > first) {
194
+ const isSamePrevious = order[index - 1].index === order[index].index - 1;
195
+ const gap = isSamePrevious
196
+ ? text.slice(chunks[order[index].index - 1].end, chunk.start)
197
+ : '\n\n';
198
+
199
+ parts.push(gap);
200
+ }
201
+
202
+ parts.push(text.slice(chunk.start, chunk.end));
203
+ }
204
+
205
+ return [[chunks[first].start, chunks[last].end], parts.join('')];
206
+ }
207
+
208
+ // each statement's text, with the comments on the lines above it and a
209
+ // comment that ends its last line; the first statement leaves a file header
210
+ // that a blank line parts from it, such as a disable directive, in place
211
+ function collectChunks(context, entries) {
212
+ const text = context.sourceCode.text;
213
+ const comments = context.sourceCode.getAllComments();
214
+
215
+ return entries.map((entry, index) => {
216
+ const [statementStart, statementEnd] = entry.statement.range;
217
+ const nextStart = entries[index + 1]?.statement.range[0] ?? text.length;
218
+ const trailing = comments.findLast(
219
+ (comment) =>
220
+ comment.range[0] >= statementEnd &&
221
+ comment.range[1] <= nextStart &&
222
+ !text.slice(statementEnd, comment.range[0]).includes('\n'),
223
+ );
224
+ const end = trailing?.range[1] ?? statementEnd;
225
+
226
+ if (index === 0) {
227
+ return { start: findAdjacentCommentsStart(text, comments, statementStart), end };
228
+ }
229
+
230
+ const [, previousEnd] = entries[index - 1].statement.range;
231
+ const leading = comments.find(
232
+ (comment) =>
233
+ comment.range[0] >= previousEnd &&
234
+ comment.range[1] <= statementStart &&
235
+ text.slice(previousEnd, comment.range[0]).includes('\n'),
236
+ );
237
+
238
+ return { start: leading?.range[0] ?? statementStart, end };
239
+ });
240
+ }
241
+
242
+ // the start of the run of comments directly above `start`, with no blank
243
+ // line inside it
244
+ function findAdjacentCommentsStart(text, comments, start) {
245
+ let current = start;
246
+
247
+ for (const comment of comments.toReversed()) {
248
+ const gap = text.slice(comment.range[1], current);
249
+
250
+ if (comment.range[1] > current) {
251
+ continue;
252
+ }
253
+
254
+ if (gap.trim() !== '' || gap.split('\n').length > 2) {
255
+ break;
256
+ }
257
+
258
+ current = comment.range[0];
259
+ }
260
+
261
+ return current;
262
+ }
@@ -0,0 +1,213 @@
1
+ // one entry per top-level statement, linked to the entries it references;
2
+ // `kind` is 'import', 'function' for a function declaration, 'supporting'
3
+ // for a const, type alias, interface or enum, and 'other' for the rest
4
+ export default function collectModuleEntries(context, program) {
5
+ const overloaded = new Set();
6
+ const entries = program.body.map((statement, index) => {
7
+ const exportKind = pickExportKind(statement);
8
+ const declaration = exportKind === null ? statement : statement.declaration;
9
+
10
+ if (declaration.type === 'TSDeclareFunction' && declaration.id !== null) {
11
+ overloaded.add(declaration.id.name);
12
+ }
13
+
14
+ return { index, statement, declaration, exportKind, ...pickKind(statement, declaration) };
15
+ });
16
+
17
+ const listed = new Set(
18
+ program.body
19
+ .filter((statement) => statement.type === 'ExportNamedDeclaration' && isExportOnly(statement))
20
+ .flatMap((statement) => statement.specifiers.map((specifier) => specifier.local.name)),
21
+ );
22
+
23
+ for (const entry of entries) {
24
+ entry.isOverloaded = entry.kind === 'function' && overloaded.has(entry.name);
25
+
26
+ if (entry.exportKind === null && listed.has(entry.name)) {
27
+ entry.exportKind = 'named';
28
+ }
29
+ }
30
+
31
+ linkReferences(context, program, entries);
32
+ markLiveEntries(entries);
33
+
34
+ return entries;
35
+ }
36
+
37
+ function pickExportKind(statement) {
38
+ if (statement.type === 'ExportDefaultDeclaration') {
39
+ return 'default';
40
+ }
41
+
42
+ return statement.type === 'ExportNamedDeclaration' && statement.declaration !== null
43
+ ? 'named'
44
+ : null;
45
+ }
46
+
47
+ function pickKind(statement, declaration) {
48
+ const links = { uses: [], users: new Set(), references: [] };
49
+
50
+ if (statement.type === 'ImportDeclaration') {
51
+ return { kind: 'import', name: null, nameNode: statement, ...links };
52
+ }
53
+
54
+ if (declaration.type === 'FunctionDeclaration' && declaration.id === null) {
55
+ return { kind: 'function', name: 'default', nameNode: statement, ...links };
56
+ }
57
+
58
+ // a default export of an expression, such as an object, binds no name
59
+ if (statement.type === 'ExportDefaultDeclaration' && declaration.type !== 'FunctionDeclaration') {
60
+ return { kind: 'other', name: 'default', nameNode: statement, ...links };
61
+ }
62
+
63
+ const name = findDeclarationName(declaration);
64
+
65
+ if (name === null) {
66
+ return { kind: 'other', name: null, nameNode: statement, ...links };
67
+ }
68
+
69
+ const kind = declaration.type === 'FunctionDeclaration' ? 'function' : 'supporting';
70
+
71
+ return { kind, name: name.name, nameNode: name, ...links };
72
+ }
73
+
74
+ // the name a declaration binds: a function, a const with one plain binding,
75
+ // a type alias, an interface or an enum
76
+ function findDeclarationName(declaration) {
77
+ if (
78
+ declaration.type === 'FunctionDeclaration' ||
79
+ declaration.type === 'TSTypeAliasDeclaration' ||
80
+ declaration.type === 'TSInterfaceDeclaration' ||
81
+ declaration.type === 'TSEnumDeclaration'
82
+ ) {
83
+ return declaration.id;
84
+ }
85
+
86
+ if (declaration.type !== 'VariableDeclaration' || declaration.kind !== 'const') {
87
+ return null;
88
+ }
89
+
90
+ const [declarator, ...rest] = declaration.declarations;
91
+ const isPlain =
92
+ rest.length === 0 && declarator.id.type === 'Identifier' && declarator.init !== null;
93
+
94
+ return isPlain ? declarator.id : null;
95
+ }
96
+
97
+ function isExportOnly(statement) {
98
+ return (
99
+ (statement.type === 'ExportDefaultDeclaration' &&
100
+ statement.declaration.type === 'Identifier') ||
101
+ (statement.type === 'ExportNamedDeclaration' &&
102
+ statement.declaration === null &&
103
+ statement.source === null)
104
+ );
105
+ }
106
+
107
+ // fills each entry's `uses` and `users` from the file's top-level scope, and
108
+ // its `references`: each identifier that names it, the entry that holds it,
109
+ // and whether it runs as the module loads
110
+ function linkReferences(context, program, entries) {
111
+ const programScope = context.sourceCode.getScope(program);
112
+ const scope = programScope.childScopes.find((child) => child.type === 'module') ?? programScope;
113
+ const findEntry = (position) =>
114
+ entries.find(
115
+ (entry) => entry.statement.range[0] <= position && position < entry.statement.range[1],
116
+ );
117
+
118
+ for (const variable of scope.variables) {
119
+ const [definition] = variable.defs;
120
+ const target = definition === undefined ? undefined : findEntry(definition.name.range[0]);
121
+
122
+ if (target === undefined || target.kind === 'import') {
123
+ continue;
124
+ }
125
+
126
+ for (const reference of variable.references) {
127
+ const identifier = reference.identifier;
128
+ const source = findEntry(identifier.range[0]) ?? null;
129
+
130
+ target.references.push({ identifier, source, isLoadTime: isLoadTime(identifier) });
131
+
132
+ if (source !== null && source !== target) {
133
+ source.uses.push({ target, position: identifier.range[0] });
134
+ target.users.add(source);
135
+ }
136
+ }
137
+ }
138
+
139
+ for (const entry of entries) {
140
+ entry.uses.sort((first, second) => first.position - second.position);
141
+ }
142
+ }
143
+
144
+ // a reference runs as the module loads unless a function body wraps it; a
145
+ // function with a call above it, such as a `.map` callback or the function in
146
+ // `(() => value).call()`, may run at once, so it wraps nothing
147
+ function isLoadTime(identifier) {
148
+ const ancestors = [];
149
+
150
+ for (let node = identifier.parent; node.type !== 'Program'; node = node.parent) {
151
+ ancestors.push(node);
152
+ }
153
+
154
+ return !ancestors.some(
155
+ (node, index) =>
156
+ isFunctionNode(node) &&
157
+ !ancestors.slice(index + 1).some((ancestor) => isInvocation(ancestor)),
158
+ );
159
+ }
160
+
161
+ function isFunctionNode(node) {
162
+ return (
163
+ node.type === 'FunctionDeclaration' ||
164
+ node.type === 'FunctionExpression' ||
165
+ node.type === 'ArrowFunctionExpression'
166
+ );
167
+ }
168
+
169
+ function isInvocation(node) {
170
+ return (
171
+ node.type === 'CallExpression' ||
172
+ node.type === 'NewExpression' ||
173
+ node.type === 'TaggedTemplateExpression'
174
+ );
175
+ }
176
+
177
+ // an entry is live when code that runs as the module loads may call into it;
178
+ // a load-time reference outside an export list makes its target live, and a
179
+ // live entry makes everything it references live
180
+ function markLiveEntries(entries) {
181
+ const live = new Set();
182
+ const pending = [];
183
+
184
+ for (const target of entries) {
185
+ const isSeed = target.references.some(
186
+ (reference) =>
187
+ reference.isLoadTime &&
188
+ reference.source !== null &&
189
+ reference.source !== target &&
190
+ !isExportOnly(reference.source.statement),
191
+ );
192
+
193
+ if (isSeed) {
194
+ live.add(target);
195
+ pending.push(target);
196
+ }
197
+ }
198
+
199
+ while (pending.length > 0) {
200
+ const entry = pending.pop();
201
+
202
+ for (const use of entry.uses) {
203
+ if (!live.has(use.target)) {
204
+ live.add(use.target);
205
+ pending.push(use.target);
206
+ }
207
+ }
208
+ }
209
+
210
+ for (const entry of entries) {
211
+ entry.isLive = live.has(entry);
212
+ }
213
+ }
@@ -0,0 +1,116 @@
1
+ const valueGlobals = new Set(['undefined', 'NaN', 'Infinity']);
2
+
3
+ const valueConstructors = new Set(['Set', 'Map', 'WeakSet', 'WeakMap', 'RegExp']);
4
+
5
+ // a function value is made, not run, so its body never counts
6
+ const checks = {
7
+ Literal: () => true,
8
+ FunctionExpression: () => true,
9
+ ArrowFunctionExpression: () => true,
10
+ Identifier: (value, names, canCopyImport) =>
11
+ (valueGlobals.has(value.name) && !names.locals.has(value.name)) ||
12
+ (canCopyImport && names.imports.has(value.name)),
13
+ TemplateLiteral: (value, names) =>
14
+ value.expressions.every((expression) => isPrimitiveValue(expression, names)),
15
+ ArrayExpression: (value, names) =>
16
+ value.elements.every((element) => element === null || isStaticElement(element, names)),
17
+ ObjectExpression: (value, names) =>
18
+ value.properties.every((property) => isStaticProperty(property, names)),
19
+ UnaryExpression: (value, names) =>
20
+ value.operator !== 'delete' && isPrimitiveValue(value.argument, names),
21
+ BinaryExpression: (value, names) =>
22
+ isPrimitiveValue(value.left, names) && isPrimitiveValue(value.right, names),
23
+ LogicalExpression: (value, names, canCopyImport) =>
24
+ isStaticValue(value.left, names, canCopyImport) &&
25
+ isStaticValue(value.right, names, canCopyImport),
26
+ ConditionalExpression: (value, names, canCopyImport) =>
27
+ isStaticValue(value.test, names, false) &&
28
+ isStaticValue(value.consequent, names, canCopyImport) &&
29
+ isStaticValue(value.alternate, names, canCopyImport),
30
+ NewExpression: (value, names) =>
31
+ value.callee.type === 'Identifier' &&
32
+ valueConstructors.has(value.callee.name) &&
33
+ !names.locals.has(value.callee.name) &&
34
+ value.arguments.every((argument) => isStaticArgument(argument, names)),
35
+ };
36
+
37
+ // a value that runs no code and reads nothing that load-time code can change,
38
+ // so it is the same wherever it sits; an import stands only where its value
39
+ // is copied, such as an array element, and never where it is read through
40
+ export default function isStaticValue(node, names, canCopyImport = true) {
41
+ const value = unwrapExpression(node);
42
+ const check = checks[value.type];
43
+
44
+ return check === undefined ? false : check(value, names, canCopyImport);
45
+ }
46
+
47
+ const wrapperTypes = new Set([
48
+ 'TSAsExpression',
49
+ 'TSSatisfiesExpression',
50
+ 'TSNonNullExpression',
51
+ 'TSTypeAssertion',
52
+ 'ParenthesizedExpression',
53
+ ]);
54
+
55
+ // a type assertion or parentheses leave the value as it is
56
+ function unwrapExpression(node) {
57
+ let current = node;
58
+
59
+ while (wrapperTypes.has(current.type)) {
60
+ current = current.expression;
61
+ }
62
+
63
+ return current;
64
+ }
65
+
66
+ const primitiveTypes = new Set([
67
+ 'Literal',
68
+ 'Identifier',
69
+ 'TemplateLiteral',
70
+ 'UnaryExpression',
71
+ 'BinaryExpression',
72
+ ]);
73
+
74
+ // an operator or a template turns an object into a primitive through its
75
+ // `valueOf` or `toString`, which can read anything, so it takes only values
76
+ // that are primitive already
77
+ function isPrimitiveValue(node, names) {
78
+ const value = unwrapExpression(node);
79
+
80
+ return primitiveTypes.has(value.type) && isStaticValue(value, names, false);
81
+ }
82
+
83
+ function isStaticElement(element, names) {
84
+ return element.type === 'SpreadElement'
85
+ ? isLiteralSpread(element, names)
86
+ : isStaticValue(element, names);
87
+ }
88
+
89
+ // a spread runs an iterator or reads properties, so it spreads only a literal
90
+ function isLiteralSpread(element, names) {
91
+ const argument = element.type === 'SpreadElement' ? unwrapExpression(element.argument) : null;
92
+
93
+ return (
94
+ argument !== null &&
95
+ (argument.type === 'ArrayExpression' || argument.type === 'ObjectExpression') &&
96
+ isStaticValue(argument, names)
97
+ );
98
+ }
99
+
100
+ function isStaticProperty(property, names) {
101
+ if (property.type === 'SpreadElement') {
102
+ return isLiteralSpread(property, names);
103
+ }
104
+
105
+ return (
106
+ (!property.computed || isStaticValue(property.key, names, false)) &&
107
+ isStaticValue(property.value, names)
108
+ );
109
+ }
110
+
111
+ // a constructor reads through its arguments, so an import never stands there
112
+ function isStaticArgument(argument, names) {
113
+ return argument.type === 'SpreadElement'
114
+ ? isLiteralSpread(argument, names)
115
+ : isStaticValue(argument, names, false);
116
+ }
@@ -0,0 +1,307 @@
1
+ import { basename } from 'node:path';
2
+ import buildModuleOrderFix from './build-module-order-fix.js';
3
+ import collectModuleEntries from './collect-module-entries.js';
4
+
5
+ // the code-style module order: the primary export, then its private helpers
6
+ // depth-first, with each const, type or enum directly above its first use
7
+ const moduleOrder = {
8
+ meta: {
9
+ type: 'suggestion',
10
+ fixable: 'code',
11
+ messages: {
12
+ helperFirst:
13
+ "'{{name}}' sits above the primary export '{{primary}}' — move private helpers below it.",
14
+ helperOrder:
15
+ "'{{name}}' breaks composition order — helpers follow the primary export depth-first, so it belongs directly after '{{after}}'.",
16
+ declarationBelowUse:
17
+ "'{{name}}' sits below its first use in '{{user}}' — move it directly above '{{user}}'.",
18
+ declarationAway:
19
+ "'{{name}}' sits away from its first use in '{{user}}' — move it directly above '{{user}}'.",
20
+ declarationLeads:
21
+ "'{{name}}' leads the file, but the primary export does not use it — move it directly above its first use in '{{user}}'.",
22
+ },
23
+ schema: [],
24
+ },
25
+ create(context) {
26
+ return {
27
+ 'Program:exit'(program) {
28
+ checkModule(context, program);
29
+ },
30
+ };
31
+ },
32
+ };
33
+
34
+ export default moduleOrder;
35
+
36
+ function checkModule(context, program) {
37
+ const entries = collectModuleEntries(context, program);
38
+ const primary = findPrimaryExport(entries, context.physicalFilename);
39
+
40
+ if (primary === null) {
41
+ return;
42
+ }
43
+
44
+ const mainOrder = collectMainOrder(primary);
45
+ const ranks = new Map(mainOrder.map((entry, index) => [entry, index]));
46
+ const homes = buildHomes(entries, ranks);
47
+ const layout = {
48
+ entries,
49
+ primary,
50
+ mainOrder,
51
+ ranks,
52
+ homes,
53
+ collectBlockUsers: (entry) => collectBlockUsers(entry, homes),
54
+ };
55
+ const helperReports = collectHelperReports(layout);
56
+ const reports = [...helperReports, ...collectDeclarationReports(layout, helperReports)];
57
+
58
+ if (reports.length === 0) {
59
+ return;
60
+ }
61
+
62
+ const plan = buildModuleOrderFix(context, { ...layout, reports });
63
+
64
+ for (const report of reports) {
65
+ const fix = plan.moved.has(report.entry) ? { fix: plan.fix } : {};
66
+
67
+ context.report({
68
+ node: report.entry.nameNode,
69
+ messageId: report.messageId,
70
+ data: { name: report.entry.name, ...report.data },
71
+ ...fix,
72
+ });
73
+ }
74
+ }
75
+
76
+ // the default export, else the export the file is named for, else the only
77
+ // value the file exports; `export default name` names the declaration of
78
+ // `name`, and a default export of any other expression is the statement
79
+ function findPrimaryExport(entries, filename) {
80
+ const defaultEntry = entries.find((entry) => entry.exportKind === 'default') ?? null;
81
+ const defaultName =
82
+ defaultEntry?.declaration.type === 'Identifier' ? defaultEntry.declaration.name : null;
83
+ const values = entries.filter(
84
+ (entry) =>
85
+ entry.name !== null &&
86
+ (entry.exportKind !== null || entry.name === defaultName) &&
87
+ (entry.kind === 'function' || entry.declaration.type === 'VariableDeclaration'),
88
+ );
89
+
90
+ if (defaultEntry !== null) {
91
+ return values.find((entry) => entry.name === defaultName) ?? defaultEntry;
92
+ }
93
+
94
+ const [fileBase] = basename(filename).split('.');
95
+ const named = values.find((entry) => toKebabCase(entry.name) === fileBase);
96
+ const only = values.length === 1 ? values[0] : null;
97
+
98
+ return named ?? only;
99
+ }
100
+
101
+ // `parseCLIArgs` becomes `parse-cli-args`, as the code-style file names read
102
+ function toKebabCase(name) {
103
+ return name
104
+ .replaceAll(/(?<before>[a-z\d])(?<after>[A-Z])/gu, '$<before>-$<after>')
105
+ .replaceAll(/(?<before>[A-Z]+)(?<after>[A-Z][a-z])/gu, '$<before>-$<after>')
106
+ .toLowerCase();
107
+ }
108
+
109
+ // the primary export, then each private helper it reaches, depth-first in the
110
+ // order each one is first referenced; a const or type passes its references
111
+ // through, so a helper that only a const names still has a place
112
+ function collectMainOrder(primary) {
113
+ const order = [primary];
114
+ const seen = new Set([primary]);
115
+
116
+ const visit = (entry) => {
117
+ for (const use of entry.uses) {
118
+ if (seen.has(use.target)) {
119
+ continue;
120
+ }
121
+
122
+ seen.add(use.target);
123
+
124
+ if (isHelper(use.target)) {
125
+ order.push(use.target);
126
+ visit(use.target);
127
+ } else if (use.target.kind === 'supporting') {
128
+ visit(use.target);
129
+ }
130
+ }
131
+ };
132
+
133
+ visit(primary);
134
+
135
+ return order;
136
+ }
137
+
138
+ function isHelper(entry) {
139
+ return entry.kind === 'function' && entry.exportKind === null;
140
+ }
141
+
142
+ // the main-order entry each const or type belongs above: the earliest one
143
+ // that uses it, directly or through another const or type
144
+ function buildHomes(entries, ranks) {
145
+ const homes = new Map();
146
+ const visiting = new Set();
147
+
148
+ const findHome = (entry) => {
149
+ if (homes.has(entry) || visiting.has(entry)) {
150
+ return homes.get(entry) ?? null;
151
+ }
152
+
153
+ visiting.add(entry);
154
+
155
+ let home = null;
156
+
157
+ for (const user of entry.users) {
158
+ const candidate = ranks.has(user) ? user : findSupportingHome(user);
159
+
160
+ if (candidate !== null && (home === null || ranks.get(candidate) < ranks.get(home))) {
161
+ home = candidate;
162
+ }
163
+ }
164
+
165
+ visiting.delete(entry);
166
+ homes.set(entry, home);
167
+
168
+ return home;
169
+ };
170
+
171
+ const findSupportingHome = (user) => (user.kind === 'supporting' ? findHome(user) : null);
172
+
173
+ for (const entry of entries) {
174
+ if (entry.kind === 'supporting' && !ranks.has(entry)) {
175
+ findHome(entry);
176
+ }
177
+ }
178
+
179
+ return homes;
180
+ }
181
+
182
+ // the users of `entry` in its home's block: the home itself and each const
183
+ // or type with the same home
184
+ function collectBlockUsers(entry, homes) {
185
+ const home = homes.get(entry);
186
+
187
+ return [...entry.users].filter((user) => user === home || homes.get(user) === home);
188
+ }
189
+
190
+ // a helper above the primary export, and a helper below it that breaks the
191
+ // depth-first order; the longest run already in order stays, so each report
192
+ // names one helper to move
193
+ function collectHelperReports(layout) {
194
+ const primary = layout.primary;
195
+ const reports = [];
196
+
197
+ for (const entry of layout.entries) {
198
+ if (isHelper(entry) && entry.index < primary.index) {
199
+ reports.push({ entry, messageId: 'helperFirst', data: { primary: primary.name } });
200
+ }
201
+ }
202
+
203
+ const mainOrder = layout.mainOrder;
204
+ const ranks = layout.ranks;
205
+ const below = mainOrder
206
+ .filter((entry) => entry.index > primary.index)
207
+ .toSorted((first, second) => first.index - second.index);
208
+ const kept = collectLongestRun(below.map((entry) => ranks.get(entry)));
209
+
210
+ for (const [position, entry] of below.entries()) {
211
+ if (!kept.has(position)) {
212
+ const after = mainOrder[ranks.get(entry) - 1].name;
213
+
214
+ reports.push({ entry, messageId: 'helperOrder', data: { after } });
215
+ }
216
+ }
217
+
218
+ return reports;
219
+ }
220
+
221
+ // the positions of one longest increasing run in `values`
222
+ function collectLongestRun(values) {
223
+ const lengths = values.map(() => 1);
224
+ const previous = values.map(() => -1);
225
+
226
+ for (let current = 0; current < values.length; current++) {
227
+ for (let earlier = 0; earlier < current; earlier++) {
228
+ if (values[earlier] < values[current] && lengths[earlier] + 1 > lengths[current]) {
229
+ lengths[current] = lengths[earlier] + 1;
230
+ previous[current] = earlier;
231
+ }
232
+ }
233
+ }
234
+
235
+ const kept = new Set();
236
+ let position = lengths.indexOf(Math.max(...lengths));
237
+
238
+ while (position !== -1) {
239
+ kept.add(position);
240
+ position = previous[position];
241
+ }
242
+
243
+ return kept;
244
+ }
245
+
246
+ // a const or type sits above every use in its home's block, with no helper
247
+ // that stays between it and its home; a const that a live function reads
248
+ // stays unchecked, since below the primary export it could be read unset
249
+ function collectDeclarationReports(layout, helperReports) {
250
+ const homes = layout.homes;
251
+ const moving = new Set(helperReports.map((report) => report.entry));
252
+ const staying = layout.mainOrder.filter((entry) => !moving.has(entry));
253
+ const reports = [];
254
+
255
+ for (const entry of layout.entries) {
256
+ const home = homes.get(entry) ?? null;
257
+
258
+ if (home === null || (hasValue(entry) && isReadByLiveFunction(entry))) {
259
+ continue;
260
+ }
261
+
262
+ const users = collectBlockUsers(entry, homes);
263
+ const usersAbove = [...users, home].filter((user) => user.index < entry.index);
264
+ const isAbove = usersAbove.length === 0;
265
+ const named = isAbove ? users : usersAbove;
266
+ const firstUser = named.reduce((first, user) => (user.index < first.index ? user : first));
267
+ const hasHelperBetween = staying.some(
268
+ (main) => main.index > entry.index && main.index < home.index,
269
+ );
270
+
271
+ if (!isAbove || hasHelperBetween) {
272
+ const messageId = pickDeclarationMessage({ entry, home, primary: layout.primary, isAbove });
273
+
274
+ reports.push({ entry, messageId, data: { user: firstUser.name } });
275
+ }
276
+ }
277
+
278
+ return reports;
279
+ }
280
+
281
+ // a type has no value to read unset, so it is always checked
282
+ function hasValue(entry) {
283
+ const type = entry.declaration.type;
284
+
285
+ return type !== 'TSTypeAliasDeclaration' && type !== 'TSInterfaceDeclaration';
286
+ }
287
+
288
+ function isReadByLiveFunction(entry) {
289
+ return entry.references.some(
290
+ (reference) =>
291
+ reference.source !== null &&
292
+ reference.source !== entry &&
293
+ reference.source.isLive &&
294
+ !reference.isLoadTime,
295
+ );
296
+ }
297
+
298
+ function pickDeclarationMessage(placement) {
299
+ if (!placement.isAbove) {
300
+ return 'declarationBelowUse';
301
+ }
302
+
303
+ const isLeading =
304
+ placement.home !== placement.primary && placement.entry.index < placement.primary.index;
305
+
306
+ return isLeading ? 'declarationLeads' : 'declarationAway';
307
+ }
package/oxlintrc.json CHANGED
@@ -32,6 +32,7 @@
32
32
  "zgeoff/no-comment-rule-override": "error",
33
33
  "zgeoff/function-verb": "error",
34
34
  "zgeoff/verb-contract": "error",
35
+ "zgeoff/module-order": "error",
35
36
  "zgeoff/test-beside-module": "error",
36
37
  "zgeoff/no-file-snapshot": "error",
37
38
  "zgeoff/setup-test-only": "error",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/oxlint-config",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Shareable oxlint config: strict categories, house-style rules, and a custom JS plugin",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -13,6 +13,10 @@
13
13
  "plugin.js",
14
14
  "function-verb.js",
15
15
  "verb-contract.js",
16
+ "module-order.js",
17
+ "collect-module-entries.js",
18
+ "build-module-order-fix.js",
19
+ "is-static-value.js",
16
20
  "find-function-name.js",
17
21
  "is-verb-match.js",
18
22
  "no-restricted-words.js",
package/plugin.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import functionVerb from './function-verb.js';
2
2
  import importZones from './import-zones.js';
3
3
  import maxConsecutiveLineComments from './max-consecutive-line-comments.js';
4
+ import moduleOrder from './module-order.js';
4
5
  import noAbbreviatedNames from './no-abbreviated-names.js';
5
6
  import noClass from './no-class.js';
6
7
  import noCommentRuleOverride from './no-comment-rule-override.js';
@@ -112,6 +113,7 @@ const plugin = {
112
113
  'no-comment-rule-override': noCommentRuleOverride,
113
114
  'function-verb': functionVerb,
114
115
  'verb-contract': verbContract,
116
+ 'module-order': moduleOrder,
115
117
  'no-restricted-words': noRestrictedWords,
116
118
  'no-abbreviated-names': noAbbreviatedNames,
117
119
  'test-beside-module': testBesideModule,
@@ -2,7 +2,9 @@ import { readdirSync, statSync } from 'node:fs';
2
2
  import { basename, dirname, join, relative, sep } from 'node:path';
3
3
  import resolveRepoRoot from './resolve-repo-root.js';
4
4
 
5
- const testFilePattern = /^(?<base>.+)\.test\.tsx?$/u;
5
+ // a browser suite (`<name>.browser.test.ts`) tests the same module as
6
+ // `<name>.test.ts`, and the suffix lets a runner put it in its own lane
7
+ const testFilePattern = /^(?<base>.+?)(?:\.browser)?\.test\.tsx?$/u;
6
8
 
7
9
  // suites that run the whole program have no single module to sit beside
8
10
  const exemptRootDirs = new Set(['e2e', 'evals']);