unknot 0.1.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/dist/report.js ADDED
@@ -0,0 +1,58 @@
1
+ import { describe } from "./rules/types.js";
2
+ export const FORMATS = ['text', 'json', 'sarif', 'github'];
3
+ const paint = (on) => (on ? (c, s) => `\u001b[${c}m${s}\u001b[0m` : (_, s) => s);
4
+ function place(at) {
5
+ const m = /^(.*?):(\d+)$/.exec(at);
6
+ return m ? { file: m[1], line: Number(m[2]) } : { file: at, line: 1 };
7
+ }
8
+ function block(f, label, tint, color) {
9
+ return [`${color(tint, `${label}[${f.rule}]`)}: ${f.title}`, ` --> ${f.at}`, ...f.notes.map((n) => ` = note: ${n}`), ...f.body.map((b) => ` ${b}`), ''].join('\n');
10
+ }
11
+ export function render(format, verdict, rules, summary) {
12
+ if (format === 'json') {
13
+ const tag = (list, status) => list.map((f) => ({ ...f, status }));
14
+ return JSON.stringify({ files: summary.files, findings: [...tag(verdict.fresh, 'new'), ...tag(verdict.unadopted, 'new-rule'), ...tag(verdict.known, 'allowed')], fixed: verdict.fixed }, null, 2);
15
+ }
16
+ if (format === 'sarif') {
17
+ const result = (f, level) => ({
18
+ ruleId: f.rule,
19
+ level,
20
+ message: { text: [f.title, ...f.notes, ...f.body].join('\n') },
21
+ partialFingerprints: { unknot: `${f.rule} ${f.key}` },
22
+ locations: [{ physicalLocation: { artifactLocation: { uri: place(f.at).file }, region: { startLine: place(f.at).line } } }],
23
+ });
24
+ return JSON.stringify({
25
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
26
+ version: '2.1.0',
27
+ runs: [
28
+ {
29
+ tool: { driver: { name: 'unknot', rules: rules.map((r) => ({ id: r.id, shortDescription: { text: describe(r, {}) }, help: { text: r.fix } })) } },
30
+ results: [...verdict.fresh.map((f) => result(f, 'error')), ...verdict.unadopted.map((f) => result(f, 'warning'))],
31
+ },
32
+ ],
33
+ }, null, 2);
34
+ }
35
+ if (format === 'github') {
36
+ const escape = (s) => s.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
37
+ const line = (f, level) => `::${level} file=${place(f.at).file},line=${place(f.at).line},title=unknot ${f.rule}::${escape([f.title, ...f.notes, ...f.body].join('\n'))}`;
38
+ return [...verdict.fresh.map((f) => line(f, 'error')), ...verdict.unadopted.map((f) => line(f, 'warning')), tail(verdict, summary)].join('\n');
39
+ }
40
+ const color = paint(summary.tty);
41
+ return [
42
+ ...verdict.fresh.map((f) => block(f, 'error', 31, color)),
43
+ ...verdict.unadopted.map((f) => block(f, 'new-rule', 36, color)),
44
+ ...(summary.showKnown ? verdict.known.map((f) => block(f, 'allowed', 33, color)) : []),
45
+ tail(verdict, summary),
46
+ ].join('\n');
47
+ }
48
+ function tail(verdict, summary) {
49
+ const byRule = new Map();
50
+ for (const f of verdict.fresh)
51
+ byRule.set(f.rule, (byRule.get(f.rule) ?? 0) + 1);
52
+ const detail = [...byRule].map(([r, n]) => `${r} ${n}`).join(', ');
53
+ return [
54
+ `unknot: ${summary.files} files in ${summary.seconds.toFixed(1)}s, ${verdict.fresh.length} new${detail ? ` (${detail})` : ''}, ${verdict.known.length} allowed`,
55
+ ...(verdict.unadopted.length ? [`unknot: ${verdict.unadopted.length} from rules added since the baseline was written; \`unknot --adopt\` records them as debt`] : []),
56
+ ...(verdict.fixed.length ? [`unknot: ${verdict.fixed.length} allowed entries are fixed; \`unknot --update-allow\` drops them`] : []),
57
+ ].join('\n');
58
+ }
@@ -0,0 +1,124 @@
1
+ import { dirOf, limit, plural } from "./types.js";
2
+ const nameOf = (key) => key.slice(key.indexOf('#') + 1);
3
+ const fileOf = (key) => key.slice(0, key.indexOf('#'));
4
+ function tangles(model) {
5
+ const out = [];
6
+ const seen = new Set();
7
+ for (const [a, refs] of model.classRefs) {
8
+ for (const [b, at] of refs) {
9
+ const back = model.classRefs.get(b)?.get(a);
10
+ if (!back)
11
+ continue;
12
+ const key = [a, b].sort().join(' ~ ');
13
+ if (seen.has(key))
14
+ continue;
15
+ seen.add(key);
16
+ out.push({
17
+ rule: 'tangle',
18
+ key,
19
+ title: `\`${nameOf(a)}\` and \`${nameOf(b)}\` know each other`,
20
+ at: `${at.file}:${at.line}`,
21
+ notes: [`${at.file}:${at.line}: ${nameOf(a)} uses ${nameOf(b)}`, `${back.file}:${back.line}: ${nameOf(b)} uses ${nameOf(a)}`],
22
+ body: [`${nameOf(a)} (${fileOf(a)}) ◀━━▶ ${nameOf(b)} (${fileOf(b)})`],
23
+ });
24
+ }
25
+ }
26
+ return out;
27
+ }
28
+ function fieldLeaks(model, config) {
29
+ const minUsers = limit(config, fieldLeak, 'minUsers');
30
+ const out = [];
31
+ for (const [key, byField] of model.fieldUses) {
32
+ const info = model.classes.get(key);
33
+ if (!info || info.methods === 0)
34
+ continue;
35
+ for (const [field, users] of byField) {
36
+ if (!info.fields.has(field) || users.size < minUsers)
37
+ continue;
38
+ const modules = new Set([...users.keys()].map(dirOf));
39
+ const others = [...byField.keys()].filter((f) => f !== field && info.fields.has(f));
40
+ const kept = [...info.fields.keys()].filter((f) => !byField.has(f));
41
+ out.push({
42
+ rule: 'field-leak',
43
+ key: `${key}.${field}`,
44
+ title: `\`${info.name}.${field}\` is changed outside \`${info.name}\`: ${plural(users.size, 'file', 'files')} in ${plural(modules.size, 'module', 'modules')}`,
45
+ at: `${info.file}:${info.fields.get(field)}`,
46
+ notes: [...users].slice(0, 8).map(([f, line]) => `${f}:${line}`),
47
+ body: [`${info.name}.${field} ◀━ ${[...modules].join(', ')}`, ...(others.length ? [`also changed outside: ${others.join(', ')}`] : []), ...(kept.length ? [`kept: ${kept.join(', ')}`] : [])],
48
+ });
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+ function wideInjections(model, config) {
54
+ const max = limit(config, wideInjection, 'max');
55
+ const seen = new Set();
56
+ const out = [];
57
+ for (const inj of model.injections) {
58
+ if (inj.deps.length <= max || seen.has(inj.key))
59
+ continue;
60
+ seen.add(inj.key);
61
+ out.push({
62
+ rule: 'wide-injection',
63
+ key: inj.key,
64
+ title: `\`${inj.name}\` depends on ${inj.deps.length} collaborators, more than ${max}`,
65
+ at: `${inj.file}:${inj.line}`,
66
+ notes: [],
67
+ body: [`${inj.name} ━▶ ${inj.deps.join(', ')}`],
68
+ });
69
+ }
70
+ return out;
71
+ }
72
+ function forwardRefs(model) {
73
+ const seen = new Set();
74
+ const out = [];
75
+ for (const ref of model.forwardRefs) {
76
+ const key = `${ref.file}#${ref.owner}->${ref.target}`;
77
+ if (seen.has(key))
78
+ continue;
79
+ seen.add(key);
80
+ out.push({
81
+ rule: 'forward-ref',
82
+ key,
83
+ title: `\`${ref.owner}\` reaches \`${ref.target}\` through forwardRef: the two depend on each other`,
84
+ at: `${ref.file}:${ref.line}`,
85
+ notes: [],
86
+ body: [`${ref.owner} ◀━━▶ ${ref.target}`],
87
+ });
88
+ }
89
+ return out;
90
+ }
91
+ const fieldLeak = {
92
+ id: 'field-leak',
93
+ scope: 'TypeScript',
94
+ summary: 'Another file assigns to a public field of a class with behaviour, or mutates the collection it holds (push, set, delete). The class no longer controls its own state. Reading a field is fine, and so is assigning a handler slot such as onmessage.',
95
+ fix: 'Ask what the outsider is trying to do and give the class a method that says it. Fix all leaks of one class together.',
96
+ options: { minUsers: 1 },
97
+ run: fieldLeaks,
98
+ };
99
+ const wideInjection = {
100
+ id: 'wide-injection',
101
+ scope: 'NestJS, Angular, any constructor injection',
102
+ summary: 'A class takes more than {max} collaborators through its constructor or inject(). It is several services sharing one name.',
103
+ fix: 'Group the collaborators by the job they serve and split the class along those jobs; do not hide them behind a facade.',
104
+ options: { max: 9 },
105
+ run: wideInjections,
106
+ };
107
+ export const classRules = [
108
+ {
109
+ id: 'tangle',
110
+ scope: 'TypeScript',
111
+ summary: 'Two classes in different files use each other. Neither can change, move or be tested without the other.',
112
+ fix: 'Pick one owner that calls both, or let one side hand the other a callback or an event; the other side stops knowing about it.',
113
+ run: tangles,
114
+ },
115
+ fieldLeak,
116
+ wideInjection,
117
+ {
118
+ id: 'forward-ref',
119
+ scope: 'NestJS, Angular',
120
+ summary: 'forwardRef() lets two providers or modules in different files depend on each other. It silences the cycle the framework reported instead of removing it.',
121
+ fix: 'Decide which side is lower. Move what both need into a third provider, or let the lower side emit an event the upper side handles.',
122
+ run: forwardRefs,
123
+ },
124
+ ];
@@ -0,0 +1,203 @@
1
+ import { dirOf, plural, SEPARATOR } from "./types.js";
2
+ const nested = (a, b) => a === b || a.startsWith(b + '/') || b.startsWith(a + '/') || a === '.' || b === '.';
3
+ function stronglyConnected(nodes, edges) {
4
+ let index = 0;
5
+ const idx = new Map();
6
+ const low = new Map();
7
+ const stack = [];
8
+ const onStack = new Set();
9
+ const out = [];
10
+ for (const start of nodes) {
11
+ if (idx.has(start))
12
+ continue;
13
+ const work = [];
14
+ const enter = (v) => {
15
+ idx.set(v, index);
16
+ low.set(v, index++);
17
+ stack.push(v);
18
+ onStack.add(v);
19
+ work.push({ v, next: (edges.get(v) ?? new Set()).values() });
20
+ };
21
+ enter(start);
22
+ while (work.length) {
23
+ const top = work[work.length - 1];
24
+ const step = top.next.next();
25
+ if (!step.done) {
26
+ const w = step.value;
27
+ if (!idx.has(w))
28
+ enter(w);
29
+ else if (onStack.has(w))
30
+ low.set(top.v, Math.min(low.get(top.v), idx.get(w)));
31
+ continue;
32
+ }
33
+ work.pop();
34
+ const parent = work[work.length - 1];
35
+ if (parent)
36
+ low.set(parent.v, Math.min(low.get(parent.v), low.get(top.v)));
37
+ if (low.get(top.v) !== idx.get(top.v))
38
+ continue;
39
+ const comp = [];
40
+ let w;
41
+ do {
42
+ w = stack.pop();
43
+ onStack.delete(w);
44
+ comp.push(w);
45
+ } while (w !== top.v);
46
+ if (comp.length > 1)
47
+ out.push(comp.sort());
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+ function layering(comp, links) {
53
+ const out = new Map(comp.map((n) => [n, 0]));
54
+ const into = new Map(comp.map((n) => [n, 0]));
55
+ const from = new Map();
56
+ const to = new Map();
57
+ for (const l of links) {
58
+ out.set(l.a, out.get(l.a) + l.files.length);
59
+ into.set(l.b, into.get(l.b) + l.files.length);
60
+ from.set(l.a, [...(from.get(l.a) ?? []), l]);
61
+ to.set(l.b, [...(to.get(l.b) ?? []), l]);
62
+ }
63
+ const left = new Set(comp);
64
+ const low = [];
65
+ const high = [];
66
+ while (left.size) {
67
+ let sink;
68
+ let source;
69
+ let lightest;
70
+ for (const n of left) {
71
+ if (out.get(n) === 0) {
72
+ sink = n;
73
+ break;
74
+ }
75
+ if (!source && into.get(n) === 0)
76
+ source = n;
77
+ if (!lightest || out.get(n) - into.get(n) < out.get(lightest) - into.get(lightest))
78
+ lightest = n;
79
+ }
80
+ const pick = sink ?? source ?? lightest;
81
+ if (!sink && source)
82
+ high.unshift(pick);
83
+ else
84
+ low.push(pick);
85
+ left.delete(pick);
86
+ for (const l of from.get(pick) ?? [])
87
+ if (left.has(l.b))
88
+ into.set(l.b, into.get(l.b) - l.files.length);
89
+ for (const l of to.get(pick) ?? [])
90
+ if (left.has(l.a))
91
+ out.set(l.a, out.get(l.a) - l.files.length);
92
+ }
93
+ return [...low, ...high];
94
+ }
95
+ function moduleCycles(model) {
96
+ const edges = new Map();
97
+ const via = new Map();
98
+ for (const [from, targets] of model.imports) {
99
+ for (const to of targets) {
100
+ const a = dirOf(from);
101
+ const b = dirOf(to);
102
+ if (nested(a, b))
103
+ continue;
104
+ if (!edges.has(a))
105
+ edges.set(a, new Set());
106
+ edges.get(a).add(b);
107
+ const k = `${a}\u0000${b}`;
108
+ if (!via.has(k))
109
+ via.set(k, []);
110
+ via.get(k).push(`${from} -> ${to}`);
111
+ }
112
+ }
113
+ const nodes = [...new Set([...edges.keys(), ...[...edges.values()].flatMap((s) => [...s])])].sort();
114
+ return stronglyConnected(nodes, edges).map((comp) => {
115
+ const inside = new Set(comp);
116
+ const links = comp.flatMap((a) => [...(edges.get(a) ?? [])].filter((b) => inside.has(b)).map((b) => ({ a, b, files: via.get(`${a}\u0000${b}`) ?? [] })));
117
+ const order = layering(comp, links);
118
+ const rank = new Map(order.map((n, i) => [n, i]));
119
+ const back = links.filter((l) => rank.get(l.a) < rank.get(l.b)).sort((x, y) => x.files.length - y.files.length);
120
+ return {
121
+ rule: 'module-cycle',
122
+ key: comp.join(SEPARATOR),
123
+ title: `${plural(comp.length, 'module', 'modules')} import each other; ${plural(back.reduce((n, l) => n + l.files.length, 0), 'import goes', 'imports go')} against the layers`,
124
+ at: back[0].files[0].split(' -> ')[0],
125
+ notes: back.flatMap((l) => l.files.map((f) => `upward import: ${f}`)).slice(0, 12),
126
+ body: [`layers, lowest first: ${order.join(' ◀ ')}`],
127
+ };
128
+ });
129
+ }
130
+ function shortestLoop(comp, edges) {
131
+ const inside = new Set(comp);
132
+ let best = null;
133
+ for (const start of comp.slice(0, 200)) {
134
+ const prev = new Map();
135
+ const queue = [start];
136
+ search: for (let i = 0; i < queue.length; i++) {
137
+ const v = queue[i];
138
+ for (const w of edges.get(v) ?? []) {
139
+ if (!inside.has(w))
140
+ continue;
141
+ if (w === start) {
142
+ const loop = [v];
143
+ while (loop[0] !== start)
144
+ loop.unshift(prev.get(loop[0]));
145
+ if (!best || loop.length < best.length)
146
+ best = loop;
147
+ break search;
148
+ }
149
+ if (!prev.has(w)) {
150
+ prev.set(w, v);
151
+ queue.push(w);
152
+ }
153
+ }
154
+ }
155
+ if (best?.length === 2)
156
+ break;
157
+ }
158
+ return best ?? comp;
159
+ }
160
+ function importCycles(model) {
161
+ const out = [];
162
+ for (const comp of stronglyConnected([...model.files].sort(), model.imports)) {
163
+ const inside = new Set(comp);
164
+ const folders = new Map();
165
+ for (const from of comp) {
166
+ for (const to of model.imports.get(from) ?? []) {
167
+ if (!inside.has(to) || nested(dirOf(from), dirOf(to)))
168
+ continue;
169
+ if (!folders.has(dirOf(from)))
170
+ folders.set(dirOf(from), new Set());
171
+ folders.get(dirOf(from)).add(dirOf(to));
172
+ }
173
+ }
174
+ if (stronglyConnected([...folders.keys()], folders).length)
175
+ continue;
176
+ const loop = shortestLoop(comp, model.imports);
177
+ out.push({
178
+ rule: 'import-cycle',
179
+ key: comp.join(SEPARATOR),
180
+ title: `${plural(comp.length, 'file', 'files')} import each other`,
181
+ at: loop[0],
182
+ notes: loop.map((f, i) => `${f} imports ${loop[(i + 1) % loop.length]}`),
183
+ body: comp.length > loop.length ? [`in the cycle: ${comp.slice(0, 7).join(', ')}${comp.length > 7 ? `, and ${comp.length - 7} more` : ''}`] : [],
184
+ });
185
+ }
186
+ return out;
187
+ }
188
+ export const graphRules = [
189
+ {
190
+ id: 'module-cycle',
191
+ scope: 'TypeScript',
192
+ summary: 'Folders import each other at runtime. The finding orders them into layers and names the imports that go upward.',
193
+ fix: 'Decide which module is the lower layer, then remove the named upward imports: move the shared piece down or invert the call.',
194
+ run: moduleCycles,
195
+ },
196
+ {
197
+ id: 'import-cycle',
198
+ scope: 'TypeScript',
199
+ summary: 'Files import each other at runtime in a loop that no folder cycle explains: files of one module, or a loop through a parent folder. None of them can be loaded, read or tested alone.',
200
+ fix: 'Find what both files need and give it one owner: a third file below both, or merge the two if they are one thing.',
201
+ run: importCycles,
202
+ },
203
+ ];
@@ -0,0 +1,28 @@
1
+ import { enabled, SetupError } from "../config.js";
2
+ import { classRules } from "./classes.js";
3
+ import { graphRules } from "./graph.js";
4
+ import { reactRules } from "./react.js";
5
+ import { shapeRules } from "./shape.js";
6
+ export const RULES = [...graphRules, ...classRules, ...shapeRules, ...reactRules];
7
+ export function runRules(model, config) {
8
+ return RULES.filter((rule) => enabled(config, rule.id))
9
+ .flatMap((rule) => rule.run(model, config))
10
+ .sort((a, b) => a.rule.localeCompare(b.rule) || a.key.localeCompare(b.key));
11
+ }
12
+ export function checkRules(config) {
13
+ for (const [id, setting] of Object.entries(config.rules ?? {})) {
14
+ const rule = RULES.find((r) => r.id === id);
15
+ if (!rule)
16
+ throw new SetupError(`.unknot.json "rules": unknown rule ${id}`);
17
+ if (typeof setting === 'boolean')
18
+ continue;
19
+ if (!setting || typeof setting !== 'object')
20
+ throw new SetupError(`.unknot.json "rules": ${id} must be false or an object of options`);
21
+ for (const [name, value] of Object.entries(setting)) {
22
+ if (!rule.options || !(name in rule.options))
23
+ throw new SetupError(`.unknot.json "rules": ${id} has no option ${name}${rule.options ? ` (it has ${Object.keys(rule.options).join(', ')})` : ''}`);
24
+ if (typeof value !== 'number')
25
+ throw new SetupError(`.unknot.json "rules": ${id}.${name} must be a number`);
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,63 @@
1
+ import { limit, plural } from "./types.js";
2
+ function propDrilling(model, config) {
3
+ const min = limit(config, drilling, 'minComponents');
4
+ const drilled = (component, prop) => {
5
+ const use = model.components.get(component)?.props.get(prop);
6
+ return use && !use.used && use.passes.length ? use : undefined;
7
+ };
8
+ const continued = new Set();
9
+ for (const [key, info] of model.components) {
10
+ for (const [prop] of info.props)
11
+ for (const pass of drilled(key, prop)?.passes ?? [])
12
+ if (drilled(pass.child, pass.attr))
13
+ continued.add(`${pass.child}.${pass.attr}`);
14
+ }
15
+ const longest = (component, prop, seen) => {
16
+ const use = drilled(component, prop);
17
+ const id = `${component}.${prop}`;
18
+ if (!use || seen.has(id))
19
+ return [];
20
+ seen.add(id);
21
+ let rest = [];
22
+ let chosen = use.passes[0];
23
+ for (const pass of use.passes) {
24
+ const found = longest(pass.child, pass.attr, seen);
25
+ if (found.length > rest.length) {
26
+ rest = found;
27
+ chosen = pass;
28
+ }
29
+ }
30
+ seen.delete(id);
31
+ return [{ component, prop, line: chosen.line, to: chosen.child }, ...rest];
32
+ };
33
+ const out = [];
34
+ for (const [key, info] of model.components) {
35
+ for (const [prop] of info.props) {
36
+ if (!drilled(key, prop) || continued.has(`${key}.${prop}`))
37
+ continue;
38
+ const chain = longest(key, prop, new Set());
39
+ if (chain.length < min)
40
+ continue;
41
+ const end = chain[chain.length - 1].to;
42
+ const names = [...chain.map((h) => model.components.get(h.component).name), end.slice(end.indexOf('#') + 1)];
43
+ out.push({
44
+ rule: 'prop-drilling',
45
+ key: `${key}.${prop}`,
46
+ title: `\`${prop}\` passes through ${plural(chain.length, 'component', 'components')} that never use it`,
47
+ at: `${info.file}:${chain[0].line}`,
48
+ notes: chain.map((h) => `${model.components.get(h.component).file}:${h.line}: ${model.components.get(h.component).name} only hands \`${h.prop}\` down`),
49
+ body: [names.join(' ━▶ ')],
50
+ });
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+ const drilling = {
56
+ id: 'prop-drilling',
57
+ scope: 'React, Preact, Solid (JSX)',
58
+ summary: 'A prop travels through {minComponents} or more components that only hand it to a child. Every layer on the way has to know a value it does not use.',
59
+ fix: 'Let the component that owns the value render the one that needs it (pass it as children), or put the value in a context or store the consumer reads itself.',
60
+ options: { minComponents: 3 },
61
+ run: propDrilling,
62
+ };
63
+ export const reactRules = [drilling];
@@ -0,0 +1,74 @@
1
+ import { dirOf, limit } from "./types.js";
2
+ function shallowModules(model, config) {
3
+ const min = limit(config, shallowModule, 'minForwards');
4
+ const out = [];
5
+ for (const [file, list] of model.forwards) {
6
+ if (list.length < min)
7
+ continue;
8
+ out.push({
9
+ rule: 'shallow-module',
10
+ key: file,
11
+ title: `\`${file}\` has ${list.length} functions that only pass their arguments on`,
12
+ at: `${file}:${list[0].line}`,
13
+ notes: list.slice(0, 8).map((f) => `${file}:${f.line}: ${f.name} ━▶ ${f.target}`),
14
+ body: ['each one adds a name to learn and hides nothing'],
15
+ });
16
+ }
17
+ return out;
18
+ }
19
+ const FLAT_BY_CONVENTION = /(^|\/)(migrations|components\/ui)$/;
20
+ function wideDirectories(model, config) {
21
+ const max = limit(config, wideDirectory, 'max');
22
+ const members = new Map();
23
+ for (const file of model.files) {
24
+ let child = file;
25
+ for (let dir = dirOf(file);; child = dir, dir = dirOf(dir)) {
26
+ if (!members.has(dir))
27
+ members.set(dir, new Set());
28
+ members.get(dir).add(child);
29
+ if (dir === '.')
30
+ break;
31
+ }
32
+ }
33
+ const out = [];
34
+ for (const [dir, set] of members) {
35
+ if (set.size <= max || FLAT_BY_CONVENTION.test(dir))
36
+ continue;
37
+ out.push({ rule: 'wide-directory', key: dir, title: `\`${dir}/\` is wide: it holds ${set.size} files and directories, more than ${max}`, at: [...set].filter((m) => model.files.has(m)).sort()[0] ?? dir, notes: [], body: [] });
38
+ }
39
+ return out;
40
+ }
41
+ function longFiles(model, config) {
42
+ const max = limit(config, longFile, 'max');
43
+ const out = [];
44
+ for (const [file, lines] of model.lines) {
45
+ if (lines > max)
46
+ out.push({ rule: 'long-file', key: file, title: `\`${file}\` is long: it has ${lines} lines, more than ${max}`, at: `${file}:1`, notes: [], body: [] });
47
+ }
48
+ return out;
49
+ }
50
+ const shallowModule = {
51
+ id: 'shallow-module',
52
+ scope: 'TypeScript',
53
+ summary: 'A file has {minForwards} or more functions or methods that only pass their own arguments to a function of another module. Decorated methods (controllers, resolvers) and methods an implemented interface or an abstract base class requires do not count. A class counts only when at least half of its public methods pass through.',
54
+ fix: 'Call the target directly, or give the wrapper real work: one call that says what the caller wants.',
55
+ options: { minForwards: 3 },
56
+ run: shallowModules,
57
+ };
58
+ const wideDirectory = {
59
+ id: 'wide-directory',
60
+ scope: 'layout',
61
+ summary: 'A directory holds more than {max} source files and subdirectories. Nobody can hold its contents in mind, so it has stopped being a module. Migrations and generated components/ui folders are flat by convention and do not count.',
62
+ fix: 'Find the two or three things the directory is about and give each its own folder with a narrow entry point.',
63
+ options: { max: 40 },
64
+ run: wideDirectories,
65
+ };
66
+ const longFile = {
67
+ id: 'long-file',
68
+ scope: 'layout',
69
+ summary: 'A source file has more than {max} lines of code. Blank lines, comments, data tables and dictionaries are not counted.',
70
+ fix: 'Find the separate concepts living in the file and move each behind its own small interface; do not cut the file at arbitrary lines.',
71
+ options: { max: 1500 },
72
+ run: longFiles,
73
+ };
74
+ export const shapeRules = [shallowModule, wideDirectory, longFile];
@@ -0,0 +1,14 @@
1
+ export const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
2
+ export const dirOf = (file) => {
3
+ const cut = file.lastIndexOf('/');
4
+ return cut < 0 ? '.' : file.slice(0, cut);
5
+ };
6
+ export const SEPARATOR = ' <-> ';
7
+ export function limit(config, rule, name) {
8
+ const own = config.rules?.[rule.id];
9
+ const value = typeof own === 'object' ? own[name] : undefined;
10
+ return typeof value === 'number' ? value : rule.options[name];
11
+ }
12
+ export function describe(rule, config) {
13
+ return rule.summary.replace(/\{(\w+)\}/g, (_, name) => String(limit(config, rule, name)));
14
+ }
package/dist/score.js ADDED
@@ -0,0 +1,34 @@
1
+ export const WEIGHTS = {
2
+ 'module-cycle': 5,
3
+ 'import-cycle': 3,
4
+ tangle: 3,
5
+ 'field-leak': 3,
6
+ 'forward-ref': 3,
7
+ 'wide-injection': 2,
8
+ 'shallow-module': 2,
9
+ 'prop-drilling': 2,
10
+ 'long-file': 1,
11
+ 'wide-directory': 1,
12
+ };
13
+ const PRIOR_FILES = 300;
14
+ const GRADES = [
15
+ ['A', 18, 'brightgreen'],
16
+ ['B', 27, 'green'],
17
+ ['C', 36, 'yellow'],
18
+ ['D', 48, 'orange'],
19
+ ['F', Infinity, 'red'],
20
+ ];
21
+ export function score(findings, files) {
22
+ const counted = new Map(findings.map((f) => [f.rule === 'field-leak' ? `${f.rule} ${f.key.slice(0, f.key.lastIndexOf('.'))}` : `${f.rule} ${f.key}`, f.rule]));
23
+ const weight = [...counted.values()].reduce((sum, rule) => sum + (WEIGHTS[rule] ?? 1), 0);
24
+ const knots = Math.round((weight / (files + PRIOR_FILES)) * 10000) / 10;
25
+ const grade = GRADES.find(([, limit]) => knots <= limit)[0];
26
+ return { grade, knots, findings: findings.length, files };
27
+ }
28
+ export function scoreLine(s) {
29
+ return `unknot score: ${s.grade} ${s.knots} knots per 1000 files (${s.findings} findings in ${s.files} files)`;
30
+ }
31
+ export function badge(s) {
32
+ const color = GRADES.find(([grade]) => grade === s.grade)[2];
33
+ return `[![unknot: ${s.grade}](https://img.shields.io/badge/unknot-${s.grade}-${color})](https://github.com/PatternVoid/unknot)`;
34
+ }
package/dist/sfc.js ADDED
@@ -0,0 +1,33 @@
1
+ const SFC = /\.(vue|svelte|astro)$/;
2
+ const VIRTUAL = /\.(vue|svelte|astro)\.tsx?$/;
3
+ const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
4
+ const FRONTMATTER = /^(\s*---[^\n]*\n)([\s\S]*?)\n---/;
5
+ export const isSfc = (file) => SFC.test(file);
6
+ export const isVirtual = (file) => VIRTUAL.test(file);
7
+ export const realName = (file) => (VIRTUAL.test(file) ? file.replace(/\.tsx?$/, '') : file);
8
+ const blank = (text) => text.replace(/[^\n]/g, ' ');
9
+ export function scriptOf(file, text) {
10
+ if (file.endsWith('.astro')) {
11
+ const m = FRONTMATTER.exec(text);
12
+ if (!m)
13
+ return { code: blank(text), tsx: false };
14
+ const start = m[1].length;
15
+ return { code: blank(text.slice(0, start)) + m[2] + blank(text.slice(start + m[2].length)) + '\nexport default {} as any;', tsx: false };
16
+ }
17
+ let code = '';
18
+ let last = 0;
19
+ let tsx = false;
20
+ for (const m of text.matchAll(SCRIPT)) {
21
+ if (/\bsrc\s*=/.test(m[1]))
22
+ continue;
23
+ if (/lang\s*=\s*["'](tsx|jsx)["']/.test(m[1]))
24
+ tsx = true;
25
+ const start = m.index + m[0].indexOf('>') + 1;
26
+ code += blank(text.slice(last, start)) + m[2];
27
+ last = start + m[2].length;
28
+ }
29
+ code += blank(text.slice(last));
30
+ if (!/\bexport\s+default\b/.test(code))
31
+ code += '\nexport default {} as any;';
32
+ return { code, tsx };
33
+ }