@tcy/eslint-rules 1.11.0 → 1.12.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.
Files changed (44) hide show
  1. package/README.md +26 -0
  2. package/coverage/clover.xml +140 -4
  3. package/coverage/coverage-final.json +1 -0
  4. package/coverage/lcov-report/index.html +19 -19
  5. package/coverage/lcov-report/src/array-elements-per-line.js.html +1 -1
  6. package/coverage/lcov-report/src/back/back.js.html +1 -1
  7. package/coverage/lcov-report/src/back/http.js.html +1 -1
  8. package/coverage/lcov-report/src/back/index.html +1 -1
  9. package/coverage/lcov-report/src/back/recommended.js.html +1 -1
  10. package/coverage/lcov-report/src/bin/eslint-cache-guard.js.html +1 -1
  11. package/coverage/lcov-report/src/bin/index.html +1 -1
  12. package/coverage/lcov-report/src/client/client.js.html +5 -2
  13. package/coverage/lcov-report/src/client/index.html +1 -1
  14. package/coverage/lcov-report/src/client/recommended.js.html +1 -1
  15. package/coverage/lcov-report/src/consistent-const-scoping.js.html +1 -1
  16. package/coverage/lcov-report/src/decorator-type-enforcement.js.html +1 -1
  17. package/coverage/lcov-report/src/enforce-tailwind-important.js.html +1 -1
  18. package/coverage/lcov-report/src/export-specifiers-per-line.js.html +1 -1
  19. package/coverage/lcov-report/src/import-specifiers-per-line.js.html +1 -1
  20. package/coverage/lcov-report/src/index.html +24 -9
  21. package/coverage/lcov-report/src/index.js.html +1 -1
  22. package/coverage/lcov-report/src/jsx-boolean-shorthand.js.html +1 -1
  23. package/coverage/lcov-report/src/jsx-expression-string-literals.js.html +1 -1
  24. package/coverage/lcov-report/src/jsx-ref-string-exists.js.html +1 -1
  25. package/coverage/lcov-report/src/no-static-key-in-map.js.html +1 -1
  26. package/coverage/lcov-report/src/no-unused-setup-return.js.html +1009 -0
  27. package/coverage/lcov-report/src/no-v-model-on-prop.js.html +1 -1
  28. package/coverage/lcov-report/src/plugin.js.html +8 -2
  29. package/coverage/lcov-report/src/recommended.js.html +1 -1
  30. package/coverage/lcov-report/src/require-fragment-key.js.html +1 -1
  31. package/coverage/lcov-report/src/route-dto-required.js.html +1 -1
  32. package/coverage/lcov-report/src/v-model-name-match.js.html +1 -1
  33. package/coverage/lcov-report/src/vuejs-define-component.js.html +1 -1
  34. package/coverage/lcov-report/src/vuejs-define-workspace.js.html +1 -1
  35. package/coverage/lcov.info +317 -0
  36. package/decl/back/back.d.ts +42 -0
  37. package/decl/client/client.d.ts +43 -0
  38. package/decl/no-unused-setup-return.d.ts +64 -0
  39. package/decl/plugin.d.ts +42 -0
  40. package/package.json +2 -2
  41. package/src/client/client.js +1 -0
  42. package/src/no-unused-setup-return.js +308 -0
  43. package/src/plugin.js +2 -0
  44. package/tests/no-unused-setup-return.spec.js +88 -0
@@ -0,0 +1,308 @@
1
+ // Disallow a key returned by a composition function (`useXxx.ts`) or by the `setup` of `Component.ts`
2
+ // that nothing else of the component reads:
3
+ //
4
+ // Component.ts defineComponent + setup, spreads the composables in a single object
5
+ // useComponent.ts composable ← the rule runs here, on the returned object
6
+ // Component.ts the `setup` returned object is checked too
7
+ // useComponent2.ts other composable
8
+ // useRender.tsx render, reads the keys through `c.key`
9
+ //
10
+ // A returned key is used when its name is found in another file of the same directory (or of its
11
+ // sub-directories, a child can read it through the context type): the render,
12
+ // `Component.ts` or another composable (`useGridConfig(p, { columnFilteredName })`). A key used only
13
+ // by a composable is not reported, it can be a value shared between compositions, not rendered.
14
+ //
15
+ // The check is by name, on purpose: it can miss an unused key sharing its name with something else,
16
+ // but never reports a used one. `ref="name"` is a use too.
17
+ //
18
+ // The directory is skipped when:
19
+ // - it has no `Component.ts` (a file calling `defineComponent`) importing the composable:
20
+ // a composable shared by many components, or used through inject / by a parent
21
+ // - a render file spreads (`...c`), or passes the whole context to a function (`foo(c)`) that
22
+ // can't be resolved (relative import): any key can be read. A resolved function is searched too
23
+
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+
27
+ export default {
28
+ meta: {
29
+ type: 'suggestion',
30
+ docs: {
31
+ description: 'Disallow a key returned by a composable that is not used by the component (render or other compositions).',
32
+ },
33
+ messages: {
34
+ unused: '"{{name}}" is returned by the setup but not used by the render or by another composition of the component.',
35
+ },
36
+ schema: [{
37
+ type: 'object',
38
+ properties: {
39
+ // keys that are never reported
40
+ ignore: { type: 'array', items: { type: 'string' } },
41
+ },
42
+ additionalProperties: false,
43
+ }],
44
+ },
45
+
46
+ create(context) {
47
+ const filename = context.filename ?? context.getFilename();
48
+
49
+ // `Component.ts` (`setup`) or a composable (`useXxx.ts`, default export)
50
+ const isComposable = isComposableFile(filename);
51
+ if (!isComposable && !isComponentFileName(filename)) return {};
52
+
53
+ const { ignore = [] } = context.options[0] || {};
54
+
55
+ const siblings = readSiblings(filename);
56
+ if (!siblings) return {};
57
+
58
+ // the composable is part of the setup of the component of its directory,
59
+ // otherwise it is shared (inject, parent, ...) and the keys are read from elsewhere
60
+ const base = path.basename(filename).replace(EXT, '');
61
+ if (isComposable) {
62
+ const component = siblings.find((s) => !s.inner && isComponentFile(s));
63
+ if (!component || !new RegExp(`from\\s+['"]\\./${escapeRegExp(base)}['"]`).test(component.text)) return {};
64
+ } else if (!/\bdefineComponent\s*\(/.test(context.sourceCode.text)) {
65
+ return {};
66
+ }
67
+ const isTarget = (fn, names) => (isComposable ? isExported(fn, names) : isSetup(fn));
68
+
69
+ const texts = siblings.map((s) => s.text);
70
+
71
+ // the render passes its whole context: `...c` hides the keys that are read, `foo(c)` is
72
+ // resolved and the file of `foo` is searched too (not resolvable: every key can be used)
73
+ for (const s of siblings) {
74
+ if (!s.isRender || s.inner) continue;
75
+
76
+ const { spread, callees } = getWholeContextUsage(s.text);
77
+ if (spread) return {};
78
+
79
+ for (const callee of callees) {
80
+ const imported = readImported(callee, s.text, path.dirname(filename));
81
+ if (imported === null) return {};
82
+ texts.push(imported);
83
+ }
84
+ }
85
+
86
+ // function stack, only the exported function counts
87
+ const stack = [];
88
+ const enter = (node) => { stack.push(node); };
89
+ const leave = () => { stack.pop(); };
90
+
91
+ const exportedNames = new Set();
92
+
93
+ return {
94
+ Program(program) {
95
+ for (const node of program.body) {
96
+ if (node.type === 'ExportDefaultDeclaration' && node.declaration.type === 'Identifier') {
97
+ exportedNames.add(node.declaration.name);
98
+ }
99
+ }
100
+ },
101
+
102
+ FunctionDeclaration: enter,
103
+ 'FunctionDeclaration:exit': leave,
104
+ FunctionExpression: enter,
105
+ 'FunctionExpression:exit': leave,
106
+ ArrowFunctionExpression(node) {
107
+ enter(node);
108
+ // `=> ({ a, b })`
109
+ if (node.body.type === 'ObjectExpression' && isTarget(node, exportedNames)) {
110
+ check(context, node.body, texts, ignore);
111
+ }
112
+ },
113
+ 'ArrowFunctionExpression:exit': leave,
114
+
115
+ ReturnStatement(node) {
116
+ if (node.argument?.type !== 'ObjectExpression') return;
117
+ const fn = stack[stack.length - 1];
118
+ if (!fn || !isTarget(fn, exportedNames)) return;
119
+ check(context, node.argument, texts, ignore);
120
+ },
121
+ };
122
+ },
123
+ };
124
+
125
+ // ─── helpers ────────────────────────────────────────────────────────────────
126
+
127
+ const EXT = /\.(ts|tsx|js|jsx)$/;
128
+
129
+ /** `useXxx.ts`, but not the render function */
130
+ export const isComposableFile = (filename) => {
131
+ const base = path.basename(filename);
132
+ return /^use[A-Z].*\.(ts|js)$/.test(base) && !/^useRender\./.test(base) && !/\.(spec|test)\./.test(base);
133
+ };
134
+
135
+ const isComponentFile = (sibling) => !sibling.isComposable && /\bdefineComponent\s*\(/.test(sibling.text);
136
+
137
+ const cache = new Map();
138
+
139
+ /** Other files of the directory, `null` if it can't be read */
140
+ const readSiblings = (filename) => {
141
+ const dir = path.dirname(filename);
142
+ let names;
143
+ try {
144
+ names = fs.readdirSync(dir, { withFileTypes: true });
145
+ } catch {
146
+ return null;
147
+ }
148
+
149
+ const result = [];
150
+ walk(dir, filename, 0, result);
151
+ return result;
152
+ };
153
+
154
+ const MAX_DEPTH = 4;
155
+
156
+ // files of the directory, `inner` the ones of its sub-directories: a child component can read
157
+ // the keys through the context type
158
+ const walk = (dir, self, depth, result) => {
159
+ let entries;
160
+ try {
161
+ entries = fs.readdirSync(dir, { withFileTypes: true });
162
+ } catch {
163
+ return;
164
+ }
165
+
166
+ for (const entry of entries) {
167
+ const file = path.join(dir, entry.name);
168
+
169
+ if (entry.isDirectory()) {
170
+ if (depth < MAX_DEPTH && entry.name !== 'node_modules') walk(file, self, depth + 1, result);
171
+ continue;
172
+ }
173
+
174
+ const { name } = entry;
175
+ if (file === self || !EXT.test(name) || /\.(spec|test)\./.test(name) || /\.d\.ts$/.test(name)) continue;
176
+
177
+ try {
178
+ const { mtimeMs } = fs.statSync(file);
179
+ const hit = cache.get(file);
180
+ if (hit?.mtimeMs === mtimeMs) {
181
+ result.push(hit.sibling);
182
+ continue;
183
+ }
184
+
185
+ const sibling = {
186
+ name,
187
+ inner: depth > 0,
188
+ isRender: /^useRender\./.test(name),
189
+ isComposable: /^use[A-Z]/.test(name),
190
+ text: stripComments(fs.readFileSync(file, 'utf8')),
191
+ };
192
+ cache.set(file, { mtimeMs, sibling });
193
+ result.push(sibling);
194
+ } catch {
195
+ // unreadable file, ignored
196
+ }
197
+ }
198
+ };
199
+
200
+ export const stripComments = (text) => text
201
+ .replace(/\/\*[\s\S]*?\*\//g, '')
202
+ .replace(/(^|[^:'"`])\/\/.*$/gm, '$1');
203
+
204
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
205
+
206
+ /** `name` found as a whole word in one of the texts */
207
+ export const isUsed = (name, texts) => {
208
+ const re = new RegExp(`(?<![\\w$])${escapeRegExp(name)}(?![\\w$])`);
209
+ return texts.some((t) => re.test(t));
210
+ };
211
+
212
+ /** Name of the first parameter of the render function, `null` if destructured / not found */
213
+ const getContextName = (text) => {
214
+ const m = /(?:function\s*\w*\s*|=\s*)\(\s*(?:\{[^}]*\}|(\w+))\s*(?::[^)]*)?\)/.exec(text);
215
+ return m ? { name: m[1] ?? null, rest: text.slice(m.index + m[0].length) } : null;
216
+ };
217
+
218
+ /**
219
+ * How the render uses its whole context (`c`):
220
+ * - `{ spread: true }` `...c`: any key can be read
221
+ * - `{ callees: [...] }` `foo(a, c)`: the names of the called functions, they read keys of `c`
222
+ */
223
+ export const getWholeContextUsage = (text) => {
224
+ const ctx = getContextName(text);
225
+ if (!ctx?.name) return { spread: false, callees: [] };
226
+
227
+ const n = escapeRegExp(ctx.name);
228
+ if (new RegExp(`\\.\\.\\.${n}(?![\\w$])`).test(ctx.rest)) return { spread: true, callees: [] };
229
+
230
+ const callees = [];
231
+ const call = new RegExp(`([\\w$]+)\\s*\\(([^()]*,\\s*)?${n}\\s*[,)]`, 'g');
232
+ for (const m of ctx.rest.matchAll(call)) callees.push(m[1]);
233
+ // a bare `(c)` / `, c)` not matched above: unknown callee
234
+ const bare = new RegExp(`[(,]\\s*${n}\\s*[,)]`, 'g');
235
+ const unknown = [...ctx.rest.matchAll(bare)].length > callees.length;
236
+ return { spread: unknown, callees };
237
+ };
238
+
239
+ /** `usesWholeContext`: the render hides the keys it reads */
240
+ export const usesWholeContext = (text) => {
241
+ const { spread, callees } = getWholeContextUsage(text);
242
+ return spread || callees.length > 0;
243
+ };
244
+
245
+ const RESOLVE_EXT = ['.ts', '.tsx', '.js', '/index.ts', '/index.tsx', '/index.js'];
246
+
247
+ /** Text of the file imported as `name` with a relative path, `null` if not resolvable */
248
+ export const readImported = (name, text, dir) => {
249
+ const n = escapeRegExp(name);
250
+ const m = new RegExp(`import\\s+${n}\\s+from\\s+['"](\\.[^'"]*)['"]|import\\s*\\{[^}]*\\b${n}\\b[^}]*\\}\\s*from\\s*['"](\\.[^'"]*)['"]`).exec(text);
251
+ const rel = m && (m[1] ?? m[2]);
252
+ if (!rel) return null;
253
+
254
+ for (const ext of RESOLVE_EXT) {
255
+ const file = path.resolve(dir, rel + ext);
256
+ try {
257
+ return stripComments(fs.readFileSync(file, 'utf8'));
258
+ } catch {
259
+ // next candidate
260
+ }
261
+ }
262
+ return null;
263
+ };
264
+
265
+ /** `Component.ts`: not a composable, not the render */
266
+ export const isComponentFileName = (filename) => {
267
+ const base = path.basename(filename);
268
+ return /\.(ts|js)$/.test(base) && !/^use[A-Z]/.test(base) && !/\.(spec|test|d)\./.test(base);
269
+ };
270
+
271
+ /** `const setup = () => {}` or `defineComponent({ setup() {}, setup: () => {} })` */
272
+ const isSetup = (fn) => {
273
+ const { parent } = fn;
274
+ if (parent?.type === 'VariableDeclarator') return parent.id.type === 'Identifier' && parent.id.name === 'setup';
275
+ if (fn.type === 'FunctionDeclaration') return fn.id?.name === 'setup';
276
+ if (parent?.type === 'Property' || parent?.type === 'MethodDefinition') {
277
+ return !parent.computed && parent.key.type === 'Identifier' && parent.key.name === 'setup';
278
+ }
279
+ return false;
280
+ };
281
+
282
+ const isExported = (fn, exportedNames) => {
283
+ const { parent } = fn;
284
+ if (parent?.type === 'ExportDefaultDeclaration') return true;
285
+ if (fn.type === 'FunctionDeclaration' && fn.id && exportedNames.has(fn.id.name)) return true;
286
+ if (parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier' && exportedNames.has(parent.id.name)) {
287
+ return true;
288
+ }
289
+ return false;
290
+ };
291
+
292
+ export const getKeyName = (prop) => {
293
+ if (prop.type !== 'Property' || prop.computed) return null;
294
+ if (prop.key.type === 'Identifier') return prop.key.name;
295
+ if (prop.key.type === 'Literal' && typeof prop.key.value === 'string') return prop.key.value;
296
+ return null;
297
+ };
298
+
299
+ const check = (context, objectNode, texts, ignore) => {
300
+ for (const prop of objectNode.properties) {
301
+ const name = getKeyName(prop);
302
+ if (!name || ignore.includes(name)) continue;
303
+
304
+ if (!isUsed(name, texts)) {
305
+ context.report({ node: prop, messageId: 'unused', data: { name } });
306
+ }
307
+ }
308
+ };
package/src/plugin.js CHANGED
@@ -14,6 +14,7 @@ import requireFragmentKey from './require-fragment-key.js'
14
14
  import noStaticKeyInMap from './no-static-key-in-map.js'
15
15
  import consistentConstScoping from './consistent-const-scoping.js'
16
16
  import noVModelOnProp from './no-v-model-on-prop.js'
17
+ import noUnusedSetupReturn from './no-unused-setup-return.js'
17
18
 
18
19
  export default {
19
20
  'import-specifiers-per-line': importSpecifiersPerLineRule,
@@ -32,4 +33,5 @@ export default {
32
33
  'no-static-key-in-map': noStaticKeyInMap,
33
34
  'consistent-const-scoping': consistentConstScoping,
34
35
  'no-v-model-on-prop': noVModelOnProp,
36
+ 'no-unused-setup-return': noUnusedSetupReturn,
35
37
  }
@@ -0,0 +1,88 @@
1
+ import {
2
+ getKeyName, getWholeContextUsage, isComponentFileName, isComposableFile, isUsed, stripComments, usesWholeContext,
3
+ } from '../src/no-unused-setup-return';
4
+
5
+ describe('GIVEN "no-unused-setup-return" / isComposableFile', () => {
6
+ it.each([
7
+ ['/a/useFoo.ts', true],
8
+ ['/a/useFoo2.ts', true],
9
+ ['/a/useRender.tsx', false],
10
+ ['/a/useFoo.spec.ts', false],
11
+ ['/a/Foo.ts', false],
12
+ ['/a/user.ts', false],
13
+ ])('THEN %s → %s', (file, expected) => {
14
+ expect(isComposableFile(file)).toBe(expected);
15
+ });
16
+ });
17
+
18
+ describe('GIVEN "no-unused-setup-return" / isUsed', () => {
19
+ it.each([
20
+ ['series', 'c.series.value', true],
21
+ ['series', 'const { series } = c;', true],
22
+ ['series', 'c.seriesCount', false],
23
+ ['series', 'c.allseries', false],
24
+ ['series', 'c.$series', false],
25
+ ['grid', '<GGrid ref="grid" />', true],
26
+ ['a.b', 'axb', false],
27
+ ])('THEN %s in %s → %s', (name, text, expected) => {
28
+ expect(isUsed(name, [text])).toBe(expected);
29
+ });
30
+ });
31
+
32
+ describe('GIVEN "no-unused-setup-return" / stripComments', () => {
33
+ it('THEN a commented use does not count', () => {
34
+ const text = stripComments('// c.foo\n/* c.bar */\nc.baz; const u = "http://x";');
35
+ expect(isUsed('foo', [text])).toBe(false);
36
+ expect(isUsed('bar', [text])).toBe(false);
37
+ expect(isUsed('baz', [text])).toBe(true);
38
+ expect(text).toContain('http://x');
39
+ });
40
+ });
41
+
42
+ describe('GIVEN "no-unused-setup-return" / usesWholeContext', () => {
43
+ it.each([
44
+ ['export default function (c: Foo) { return <A {...c} />; }', true],
45
+ ['export default function (c: Foo) { return <A>{render(c)}</A>; }', true],
46
+ ['export default function (c: Foo) { return <A>{render(a, c)}</A>; }', true],
47
+ ['export default function (c: Foo) { return <A v={c.a} />; }', false],
48
+ ['export default function (c: Foo) { return <A v={fn(c.a, c.b)} />; }', false],
49
+ ['export default function ({ a }: Foo) { return <A v={a} />; }', false],
50
+ ])('THEN %s → %s', (text, expected) => {
51
+ expect(usesWholeContext(text)).toBe(expected);
52
+ });
53
+ });
54
+
55
+ describe('GIVEN "no-unused-setup-return" / getKeyName', () => {
56
+ it.each([
57
+ [{ type: 'Property', computed: false, key: { type: 'Identifier', name: 'a' } }, 'a'],
58
+ [{ type: 'Property', computed: false, key: { type: 'Literal', value: 'b' } }, 'b'],
59
+ [{ type: 'Property', computed: true, key: { type: 'Identifier', name: 'c' } }, null],
60
+ [{ type: 'SpreadElement' }, null],
61
+ ])('THEN %j → %s', (prop, expected) => {
62
+ expect(getKeyName(prop)).toBe(expected);
63
+ });
64
+ });
65
+
66
+ describe('GIVEN "no-unused-setup-return" / getWholeContextUsage', () => {
67
+ it.each([
68
+ ['export default function (c: Foo) { return <A {...c} />; }', { spread: true, callees: [] }],
69
+ ['export default function (c: Foo) { return <A>{render(c)}</A>; }', { spread: false, callees: ['render'] }],
70
+ ['export default function (c: Foo) { return <A>{f(value, row, c)}</A>; }', { spread: false, callees: ['f'] }],
71
+ ['export default function (c: Foo) { return <A v={c.a} />; }', { spread: false, callees: [] }],
72
+ ])('THEN %s → %j', (text, expected) => {
73
+ expect(getWholeContextUsage(text)).toEqual(expected);
74
+ });
75
+ });
76
+
77
+ describe('GIVEN "no-unused-setup-return" / isComponentFileName', () => {
78
+ it.each([
79
+ ['/a/DailyPL.ts', true],
80
+ ['/a/WorkspaceFoo.ts', true],
81
+ ['/a/useDailyPL.ts', false],
82
+ ['/a/useRender.tsx', false],
83
+ ['/a/DailyPL.spec.ts', false],
84
+ ['/a/types.d.ts', false],
85
+ ])('THEN %s → %s', (file, expected) => {
86
+ expect(isComponentFileName(file)).toBe(expected);
87
+ });
88
+ });