@decohere/ci-tools 0.0.1-dev.20261122.356 → 0.0.1-dev.20261122.362
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decohere/ci-tools",
|
|
3
|
-
"version": "0.0.1-dev.20261122.
|
|
3
|
+
"version": "0.0.1-dev.20261122.362",
|
|
4
4
|
"description": "CI utility scripts for badge generation, coverage reporting, pages artifact assembly, and GitHub API tooling",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"typescript",
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Measures how far Decohere's code is from ADR 0027: per package, how many times each rule is
|
|
3
|
+
* broken, with where. Reads each package's `src/` with the TypeScript compiler's parser (no
|
|
4
|
+
* type-check), and its spec files wherever they are.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { basename, join, relative } from "node:path";
|
|
8
|
+
import ts from "typescript";
|
|
9
|
+
|
|
10
|
+
/** The roles a file's name may end in, from ADR 0027. */
|
|
11
|
+
export const ROLES = new Set([
|
|
12
|
+
"entity",
|
|
13
|
+
"value",
|
|
14
|
+
"service",
|
|
15
|
+
"strategy",
|
|
16
|
+
"factory",
|
|
17
|
+
"repository",
|
|
18
|
+
"port",
|
|
19
|
+
"adapter",
|
|
20
|
+
"provider",
|
|
21
|
+
"plugin",
|
|
22
|
+
"controller",
|
|
23
|
+
"handler",
|
|
24
|
+
"command",
|
|
25
|
+
"action",
|
|
26
|
+
"decorator",
|
|
27
|
+
"event",
|
|
28
|
+
"error",
|
|
29
|
+
"const",
|
|
30
|
+
"config",
|
|
31
|
+
"module",
|
|
32
|
+
"model",
|
|
33
|
+
"mapping",
|
|
34
|
+
"contract",
|
|
35
|
+
"registry",
|
|
36
|
+
"builder",
|
|
37
|
+
"host",
|
|
38
|
+
"cases",
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/** The rules counted, and what each count means. */
|
|
42
|
+
export const RULES = {
|
|
43
|
+
looseFunctions:
|
|
44
|
+
"exported loose functions (not a plugin factory, decorator, define… helper or is/has predicate)",
|
|
45
|
+
namespaceObjects: "namespace objects (export const x = { fn, … })",
|
|
46
|
+
severalClasses: "files with several classes",
|
|
47
|
+
bannedNames: ".types.ts, .store.ts and utils/helpers/common/shared/misc files",
|
|
48
|
+
noRole: "files with no role suffix",
|
|
49
|
+
envReads: "process.env reads outside config and the package's bins",
|
|
50
|
+
specsAway: "spec files not beside their code (outside src/)",
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const BANNED = /(^|[.-])(utils?|helpers?|common|shared|misc)([.-]|$)|\.(types|store)$/;
|
|
54
|
+
const SPEC = /\.(spec|test)\.(ts|mts|mjs|js)$/;
|
|
55
|
+
|
|
56
|
+
export class CodeDesign {
|
|
57
|
+
/** @param {string} root the workspace root */
|
|
58
|
+
constructor(root) {
|
|
59
|
+
this.root = root;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @returns {Record<string, Record<string, { count: number, where: string[] }>>} per package, per rule
|
|
64
|
+
*/
|
|
65
|
+
measure() {
|
|
66
|
+
/** @type {Record<string, Record<string, { count: number, where: string[] }>>} */
|
|
67
|
+
const result = {};
|
|
68
|
+
for (const { name, dir, bins } of this.packages()) {
|
|
69
|
+
const tally = Object.fromEntries(
|
|
70
|
+
Object.keys(RULES).map((rule) => [
|
|
71
|
+
rule,
|
|
72
|
+
{ count: 0, where: /** @type {string[]} */ ([]) },
|
|
73
|
+
]),
|
|
74
|
+
);
|
|
75
|
+
const add = (rule, where) => {
|
|
76
|
+
tally[rule].count++;
|
|
77
|
+
tally[rule].where.push(where);
|
|
78
|
+
};
|
|
79
|
+
for (const file of this.files(dir)) {
|
|
80
|
+
const rel = relative(this.root, file);
|
|
81
|
+
if (SPEC.test(file)) {
|
|
82
|
+
if (!relative(dir, file).startsWith("src/")) add("specsAway", rel);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (
|
|
86
|
+
!relative(dir, file).startsWith("src/") ||
|
|
87
|
+
!/\.(ts|mts)$/.test(file) ||
|
|
88
|
+
file.endsWith(".d.ts")
|
|
89
|
+
) {
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
this.measureFile(file, rel, name, bins, add);
|
|
93
|
+
}
|
|
94
|
+
result[name] = Object.fromEntries(Object.entries(tally).filter(([, t]) => t.count > 0));
|
|
95
|
+
}
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @private */
|
|
100
|
+
measureFile(file, rel, name, bins, add) {
|
|
101
|
+
const text = readFileSync(file, "utf8");
|
|
102
|
+
const base = basename(file).replace(/\.(ts|mts)$/, "");
|
|
103
|
+
if (BANNED.test(base)) add("bannedNames", rel);
|
|
104
|
+
const role = base.split(".");
|
|
105
|
+
if (base !== "index" && (role.length < 2 || !ROLES.has(role.at(-1)))) add("noRole", rel);
|
|
106
|
+
const env = text.match(/process\.env\b/g)?.length ?? 0;
|
|
107
|
+
if (env > 0 && name !== "config" && !bins.has(relative(this.root, file))) {
|
|
108
|
+
for (let i = 0; i < env; i++) add("envReads", rel);
|
|
109
|
+
}
|
|
110
|
+
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
111
|
+
let classes = 0;
|
|
112
|
+
for (const statement of source.statements) {
|
|
113
|
+
if (ts.isClassDeclaration(statement)) classes++;
|
|
114
|
+
if (!isExported(statement)) continue;
|
|
115
|
+
if (ts.isFunctionDeclaration(statement)) {
|
|
116
|
+
const fn = statement.name?.text ?? "default";
|
|
117
|
+
if (!isAllowedFunction(fn, statement)) add("looseFunctions", `${rel}: ${fn}`);
|
|
118
|
+
}
|
|
119
|
+
if (ts.isVariableStatement(statement)) {
|
|
120
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
121
|
+
const init = declaration.initializer;
|
|
122
|
+
const variable = declaration.name.getText();
|
|
123
|
+
if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
|
|
124
|
+
if (!isAllowedFunction(variable, init))
|
|
125
|
+
add("looseFunctions", `${rel}: ${variable}`);
|
|
126
|
+
} else if (init && ts.isObjectLiteralExpression(init) && holdsFunctions(init)) {
|
|
127
|
+
add("namespaceObjects", `${rel}: ${variable}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (classes > 1) add("severalClasses", rel);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** @private Every package under projects/, with the source files its bins start from. */
|
|
136
|
+
packages() {
|
|
137
|
+
/** @type {{ name: string, dir: string, bins: Set<string> }[]} */
|
|
138
|
+
const found = [];
|
|
139
|
+
const visit = (dir) => {
|
|
140
|
+
for (const entry of readdirSync(dir)) {
|
|
141
|
+
if (entry === "node_modules" || entry === "__fixtures__" || entry === "dist") continue;
|
|
142
|
+
const path = join(dir, entry);
|
|
143
|
+
if (!statSync(path).isDirectory()) continue;
|
|
144
|
+
if (!existsSync(join(path, "package.json"))) {
|
|
145
|
+
visit(path);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const manifest = JSON.parse(readFileSync(join(path, "package.json"), "utf8"));
|
|
149
|
+
const bin =
|
|
150
|
+
typeof manifest.bin === "string"
|
|
151
|
+
? [manifest.bin]
|
|
152
|
+
: Object.values(manifest.bin ?? {});
|
|
153
|
+
const bins = new Set(
|
|
154
|
+
bin.map((target) =>
|
|
155
|
+
relative(
|
|
156
|
+
this.root,
|
|
157
|
+
join(
|
|
158
|
+
path,
|
|
159
|
+
String(target)
|
|
160
|
+
.replace(/^\.\/(es6|dist\/[^/]+)\//, "")
|
|
161
|
+
.replace(/\.js$/, ".ts"),
|
|
162
|
+
),
|
|
163
|
+
),
|
|
164
|
+
),
|
|
165
|
+
);
|
|
166
|
+
found.push({
|
|
167
|
+
name: String(manifest.name).replace(/^@decohere\//, ""),
|
|
168
|
+
dir: path,
|
|
169
|
+
bins,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
visit(join(this.root, "projects"));
|
|
174
|
+
return found.sort((a, b) => a.name.localeCompare(b.name));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** @private */
|
|
178
|
+
files(dir) {
|
|
179
|
+
/** @type {string[]} */
|
|
180
|
+
const out = [];
|
|
181
|
+
const visit = (current) => {
|
|
182
|
+
for (const entry of readdirSync(current)) {
|
|
183
|
+
if (["node_modules", "dist", "e2e", "__fixtures__"].includes(entry)) continue;
|
|
184
|
+
const path = join(current, entry);
|
|
185
|
+
if (statSync(path).isDirectory()) {
|
|
186
|
+
// A nested package is measured on its own.
|
|
187
|
+
if (path !== dir && existsSync(join(path, "package.json"))) continue;
|
|
188
|
+
visit(path);
|
|
189
|
+
} else out.push(path);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
visit(dir);
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @param {ts.Statement} statement */
|
|
198
|
+
function isExported(statement) {
|
|
199
|
+
return (
|
|
200
|
+
ts.canHaveModifiers(statement) &&
|
|
201
|
+
(ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Plugin factories, decorators, define… helpers and is/has predicates are the loose functions
|
|
207
|
+
* ADR 0027 keeps.
|
|
208
|
+
*
|
|
209
|
+
* @param {string} name
|
|
210
|
+
* @param {ts.FunctionLikeDeclaration} fn
|
|
211
|
+
*/
|
|
212
|
+
function isAllowedFunction(name, fn) {
|
|
213
|
+
if (/^(is|has)[A-Z]/.test(name) || /^define[A-Z]/.test(name)) return true;
|
|
214
|
+
const returns = fn.type?.getText() ?? "";
|
|
215
|
+
if (/Plugin\b|Decorator\b/.test(returns)) return true;
|
|
216
|
+
const body = fn.body?.getText() ?? "";
|
|
217
|
+
// A factory returning `(builder) => …`, or a decorator returning `(target…) => …`.
|
|
218
|
+
return /return \(?(builder|target|_target)\b/.test(body);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** @param {ts.ObjectLiteralExpression} object */
|
|
222
|
+
function holdsFunctions(object) {
|
|
223
|
+
return object.properties.some(
|
|
224
|
+
(p) =>
|
|
225
|
+
ts.isShorthandPropertyAssignment(p) ||
|
|
226
|
+
ts.isMethodDeclaration(p) ||
|
|
227
|
+
(ts.isPropertyAssignment(p) &&
|
|
228
|
+
(ts.isArrowFunction(p.initializer) || ts.isFunctionExpression(p.initializer))),
|
|
229
|
+
);
|
|
230
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pnpm design:check`: measures the code against ADR 0027 and compares each package's counts with
|
|
3
|
+
* the committed baseline. A count above it fails; a count below it fails too, until the baseline
|
|
4
|
+
* is lowered with `--update`, so it can never rise back. `--update` writes today's counts.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
import { CodeDesign, RULES } from "./code-design.service.mjs";
|
|
10
|
+
|
|
11
|
+
export const BASELINE = "projects/ci-tools/src/design/baseline.json";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {{ argv?: string[], root?: string, log?: (line: string) => void }} [options]
|
|
15
|
+
* @returns {number} exit code
|
|
16
|
+
*/
|
|
17
|
+
export function runDesignCheck(options = {}) {
|
|
18
|
+
const { values } = parseArgs({
|
|
19
|
+
args: options.argv ?? process.argv.slice(2),
|
|
20
|
+
options: { update: { type: "boolean", default: false } },
|
|
21
|
+
});
|
|
22
|
+
const root = options.root ?? process.cwd();
|
|
23
|
+
const log = options.log ?? ((line) => process.stdout.write(`${line}\n`));
|
|
24
|
+
const measured = new CodeDesign(root).measure();
|
|
25
|
+
const counts = Object.fromEntries(
|
|
26
|
+
Object.entries(measured).map(([pkg, rules]) => [
|
|
27
|
+
pkg,
|
|
28
|
+
Object.fromEntries(Object.entries(rules).map(([rule, { count }]) => [rule, count])),
|
|
29
|
+
]),
|
|
30
|
+
);
|
|
31
|
+
const path = join(root, BASELINE);
|
|
32
|
+
|
|
33
|
+
if (values.update) {
|
|
34
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
35
|
+
// Two spaces, as Prettier formats JSON here, so an update changes only the counts.
|
|
36
|
+
writeFileSync(path, `${JSON.stringify(counts, null, 2)}\n`);
|
|
37
|
+
log(`design: wrote the baseline (${total(counts)} breaks of ADR 0027 in all).`);
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @type {Record<string, Record<string, number>>} */
|
|
42
|
+
const baseline = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
|
|
43
|
+
const rose = [];
|
|
44
|
+
const fell = [];
|
|
45
|
+
for (const pkg of new Set([...Object.keys(counts), ...Object.keys(baseline)])) {
|
|
46
|
+
for (const rule of Object.keys(RULES)) {
|
|
47
|
+
const now = counts[pkg]?.[rule] ?? 0;
|
|
48
|
+
const was = baseline[pkg]?.[rule] ?? 0;
|
|
49
|
+
if (now > was) {
|
|
50
|
+
// The baseline keeps counts, not places, so the new ones are somewhere in this list.
|
|
51
|
+
const where = measured[pkg][rule].where;
|
|
52
|
+
rose.push(
|
|
53
|
+
`design: ${pkg} ${RULES[rule]} ${was} → ${now} (+${now - was}), among:\n ${where.join("\n ")}`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
if (now < was) fell.push(`design: ${pkg} ${RULES[rule]} ${was} → ${now}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
log(`design: ${total(counts)} breaks of ADR 0027 (docs/adr/0027-code-design.md).`);
|
|
61
|
+
if (rose.length > 0) {
|
|
62
|
+
log(rose.join("\n"));
|
|
63
|
+
log(
|
|
64
|
+
"Rules broken more than the baseline allows. Fix the code; ADR 0027 says how it should be.",
|
|
65
|
+
);
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
if (fell.length > 0) {
|
|
69
|
+
log(fell.join("\n"));
|
|
70
|
+
log(
|
|
71
|
+
"Fewer breaks than the baseline: lower it, so they can't come back: pnpm design:check --update",
|
|
72
|
+
);
|
|
73
|
+
return 1;
|
|
74
|
+
}
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** @param {Record<string, Record<string, number>>} counts */
|
|
79
|
+
function total(counts) {
|
|
80
|
+
return Object.values(counts).reduce(
|
|
81
|
+
(sum, rules) => sum + Object.values(rules).reduce((a, b) => a + b, 0),
|
|
82
|
+
0,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { vol } from "memfs";
|
|
2
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
3
|
+
import { BASELINE, runDesignCheck } from "../../src/design/design-check.command.mjs";
|
|
4
|
+
|
|
5
|
+
const root = "/workspace";
|
|
6
|
+
|
|
7
|
+
/** A workspace with one package, `http`, holding these files under projects/http. */
|
|
8
|
+
function seed(files, baseline) {
|
|
9
|
+
vol.fromJSON({
|
|
10
|
+
[`${root}/projects/http/package.json`]: JSON.stringify({ name: "@decohere/http" }),
|
|
11
|
+
...Object.fromEntries(
|
|
12
|
+
Object.entries(files).map(([path, text]) => [`${root}/projects/http/${path}`, text]),
|
|
13
|
+
),
|
|
14
|
+
...(baseline ? { [`${root}/${BASELINE}`]: JSON.stringify(baseline) } : {}),
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function run(argv = []) {
|
|
19
|
+
const lines = [];
|
|
20
|
+
const code = runDesignCheck({ argv, root, log: (line) => lines.push(line) });
|
|
21
|
+
return { code, output: lines.join("\n") };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const CLEAN = {
|
|
25
|
+
"src/index.ts": 'export * from "./routing/router.service.js";\n',
|
|
26
|
+
"src/routing/router.service.ts": "export class RouterService {}\n",
|
|
27
|
+
"src/routing/router.service.spec.ts": "it('routes', () => {});\n",
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
afterEach(() => vol.reset());
|
|
31
|
+
|
|
32
|
+
describe("design:check", () => {
|
|
33
|
+
it("passes code that keeps ADR 0027, with no baseline", () => {
|
|
34
|
+
seed(CLEAN);
|
|
35
|
+
expect(run()).toEqual({ code: 0, output: expect.stringContaining("design: 0 breaks") });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("fails a new loose function, naming where it is", () => {
|
|
39
|
+
seed(
|
|
40
|
+
{
|
|
41
|
+
...CLEAN,
|
|
42
|
+
"src/routing/route-path.value.ts": "export function toPath(p: string) { return p; }\n",
|
|
43
|
+
},
|
|
44
|
+
{ http: {} },
|
|
45
|
+
);
|
|
46
|
+
const { code, output } = run();
|
|
47
|
+
expect(code).toBe(1);
|
|
48
|
+
expect(output).toContain("http exported loose functions");
|
|
49
|
+
expect(output).toContain("0 → 1 (+1), among:");
|
|
50
|
+
expect(output).toContain("projects/http/src/routing/route-path.value.ts: toPath");
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("counts each rule ADR 0027 sets", () => {
|
|
54
|
+
seed({
|
|
55
|
+
"src/index.ts": "",
|
|
56
|
+
"src/path.util.ts": "export const x = 1;\n",
|
|
57
|
+
"src/query.types.ts": "export type Q = {};\n",
|
|
58
|
+
"src/router.ts": "export class A {}\nexport class B {}\nconst e = process.env.X;\n",
|
|
59
|
+
"src/aliases.service.ts": "function a() {}\nexport const aliases = { a };\n",
|
|
60
|
+
"tests/router.spec.ts": "it('x', () => {});\n",
|
|
61
|
+
});
|
|
62
|
+
run(["--update"]);
|
|
63
|
+
const written = String(vol.readFileSync(`${root}/${BASELINE}`));
|
|
64
|
+
// As Prettier formats JSON in this repo, so an update changes only the counts.
|
|
65
|
+
expect(written).toMatch(/^\{\n {2}"http": \{\n {4}"/);
|
|
66
|
+
expect(JSON.parse(written)).toEqual({
|
|
67
|
+
http: {
|
|
68
|
+
bannedNames: 2,
|
|
69
|
+
noRole: 3,
|
|
70
|
+
severalClasses: 1,
|
|
71
|
+
envReads: 1,
|
|
72
|
+
namespaceObjects: 1,
|
|
73
|
+
specsAway: 1,
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("keeps plugin factories, decorators, define helpers and predicates", () => {
|
|
79
|
+
seed({
|
|
80
|
+
...CLEAN,
|
|
81
|
+
"src/http.plugin.ts": [
|
|
82
|
+
"export function http(): BuilderPlugin { return (builder) => {}; }",
|
|
83
|
+
"export function injectRouter(): ParameterDecorator { return (target) => {}; }",
|
|
84
|
+
"export function defineRoute(r: unknown) { return r; }",
|
|
85
|
+
"export const isRoute = (r: unknown) => r != null;",
|
|
86
|
+
].join("\n"),
|
|
87
|
+
});
|
|
88
|
+
expect(run().code).toBe(0);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("asks for the baseline to be lowered when a count falls, so it can't rise again", () => {
|
|
92
|
+
seed(CLEAN, { http: { looseFunctions: 3 } });
|
|
93
|
+
const { code, output } = run();
|
|
94
|
+
expect(code).toBe(1);
|
|
95
|
+
expect(output).toContain("http exported loose functions");
|
|
96
|
+
expect(output).toContain("pnpm design:check --update");
|
|
97
|
+
|
|
98
|
+
run(["--update"]);
|
|
99
|
+
expect(run().code).toBe(0);
|
|
100
|
+
});
|
|
101
|
+
});
|