@adrien-chinour/js-quality 0.0.0-stage → 0.3.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/LICENSE +14 -0
- package/README.md +181 -2
- package/dist/cli.mjs +773 -0
- package/dist/sandbox-build.mjs +56 -0
- package/package.json +56 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
BSD Zero Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Adrien Chinour
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted.
|
|
7
|
+
|
|
8
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
9
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
10
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
11
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
12
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
13
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
|
+
PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,182 @@
|
|
|
1
|
-
#
|
|
1
|
+
# js-quality
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Portes qualité JS/TS que [Vite+](https://viteplus.dev) ne fournit pas, réunies dans un binaire : `jsq`.
|
|
4
|
+
|
|
5
|
+
| Porte | Ce qui est mesuré | Seuil par défaut |
|
|
6
|
+
| -------------------- | ------------------------------------------------------------------------------------------------------ | ---------------- |
|
|
7
|
+
| Complexité cognitive | Complexité de chaque fonction, règle `sonarjs/cognitive-complexity` (définition SonarSource) | 15 au plus |
|
|
8
|
+
| CRAP | `complexité² × (1 − couverture)³ + complexité`, par fonction, couverture lue dans `coverage/lcov.info` | moins de 10 |
|
|
9
|
+
| Duplication | Blocs copiés-collés (jscpd), 40 tokens et 4 lignes au moins | 0 % |
|
|
10
|
+
| Mutation | Score Stryker, tests du projet lancés par Vitest, seuls ceux qui couvrent chaque mutant | 70 % au moins |
|
|
11
|
+
|
|
12
|
+
Format, lint, types et tests restent à Vite+ (`vp check`, `vp test`). `jsq` n'a besoin d'aucune configuration ESLint,
|
|
13
|
+
Stryker ou jscpd dans le projet : tout est embarqué.
|
|
14
|
+
|
|
15
|
+
## Utilisation
|
|
16
|
+
|
|
17
|
+
Paquet npm [`@adrien-chinour/js-quality`](https://www.npmjs.com/package/@adrien-chinour/js-quality), en dépendance de
|
|
18
|
+
dev avec la couverture v8 de Vitest :
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
vp add -D @adrien-chinour/js-quality @vitest/coverage-v8@<version du Vitest de Vite+> vitest@<version du Vitest de Vite+>
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`vitest` se déclare à la version exacte dont dépend `vite-plus` (ligne `vitest` de `vp --version`) : le runner
|
|
25
|
+
Vitest de Stryker, embarqué dans `jsq`, importe `vitest` depuis son propre emplacement, et la déclaration garantit
|
|
26
|
+
qu'il charge celui de Vite+. C'est une dépendance peer facultative de `js-quality`, inutile avec
|
|
27
|
+
`mutation.command`. Les tests continuent d'importer `vite-plus/test`. Le projet garde l'override de `vite` que pose
|
|
28
|
+
`vp create` (`vite@*` vers `@voidzero-dev/vite-plus-core`) : sans lui, `vitest` peut exister en deux copies, et le
|
|
29
|
+
runner échoue sur « Vitest failed to find the current suite ».
|
|
30
|
+
|
|
31
|
+
Aucun script d'installation : `dist/` est construit avant publication, pnpm n'a rien à approuver.
|
|
32
|
+
|
|
33
|
+
`vite.config.ts` doit produire un rapport lcov :
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
test: {
|
|
37
|
+
coverage: { provider: 'v8', reporter: ['text-summary', 'lcov'], include: ['src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}'] },
|
|
38
|
+
},
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Scripts du `package.json` :
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
"qa": "vp check --deny-warnings && vp test run --coverage && jsq check",
|
|
45
|
+
"mutation": "jsq mutation"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Puis `vp run qa` à chaque changement, `vp run mutation` à la recette d'une version.
|
|
49
|
+
|
|
50
|
+
| Commande | Rôle |
|
|
51
|
+
| ----------------------------------- | ------------------------------------------------------------- |
|
|
52
|
+
| `jsq check` | Complexité, CRAP et duplication ; code 1 si une porte échoue |
|
|
53
|
+
| `jsq check --only crap,duplication` | Une partie des portes seulement |
|
|
54
|
+
| `jsq check --write-baseline` | Gèle les violations courantes (voir « Adoption progressive ») |
|
|
55
|
+
| `jsq mutation` | Mutation sur les sources ; code non nul sous le seuil |
|
|
56
|
+
| `jsq mutation --mutate src/a.ts` | Mutation sur quelques fichiers (option répétable) |
|
|
57
|
+
|
|
58
|
+
Codes de sortie : 0 tout passe, 1 une porte échoue, 2 mauvaise utilisation ou erreur.
|
|
59
|
+
|
|
60
|
+
## Configuration
|
|
61
|
+
|
|
62
|
+
Facultative, bloc `jsq` du `package.json`. Valeurs par défaut :
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
"jsq": {
|
|
66
|
+
"src": ["src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"],
|
|
67
|
+
"ignore": ["**/*.d.ts", "**/*.test.*", "**/*.spec.*", "**/node_modules/**", "**/dist/**"],
|
|
68
|
+
"complexity": 15,
|
|
69
|
+
"crap": 10,
|
|
70
|
+
"lcov": "coverage/lcov.info",
|
|
71
|
+
"baseline": "jsq-baseline.json",
|
|
72
|
+
"duplication": { "minTokens": 40, "minLines": 4, "threshold": 0 },
|
|
73
|
+
"mutation": { "break": 70, "mutate": [] }
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`mutation.command` (absent par défaut), pour un projet dont les tests ne passent pas par Vitest : Stryker lance
|
|
78
|
+
alors cette commande pour chaque mutant (runner « command »), sans analyse de couverture par test.
|
|
79
|
+
|
|
80
|
+
Un seuil assoupli se justifie dans le README du projet qui l'assouplit.
|
|
81
|
+
|
|
82
|
+
## Adoption progressive
|
|
83
|
+
|
|
84
|
+
Sur un projet existant, les portes échouent dès le premier lancement. Plutôt que d'assouplir les seuils, on gèle les
|
|
85
|
+
violations existantes, puis on les résorbe :
|
|
86
|
+
|
|
87
|
+
1. `jsq check --write-baseline` écrit `jsq-baseline.json` (option `baseline` du bloc `jsq`, chemin relatif au
|
|
88
|
+
dossier où `jsq` tourne) : chaque violation courante et sa valeur, portes et clés triées. Le fichier se versionne.
|
|
89
|
+
2. `jsq check` passe tant que chaque violation est gelée avec une valeur supérieure ou égale. Il échoue sur une
|
|
90
|
+
violation absente du fichier ou aggravée, en affichant la ligne, la clé et la valeur gelée.
|
|
91
|
+
3. Une entrée gelée qui ne viole plus la porte (fonction corrigée, renommée ou supprimée, clone retiré) est signalée
|
|
92
|
+
par un avertissement, avec le nombre d'entrées et leurs clés ; la porte reste verte. On la retire du fichier, à
|
|
93
|
+
la main ou en relançant `--write-baseline`, dans la même PR que la correction.
|
|
94
|
+
|
|
95
|
+
| Porte | Clé | Valeur gelée |
|
|
96
|
+
| ----------- | ------------------------------------ | ---------------------------------------- |
|
|
97
|
+
| complexity | `src/a.ts:nom` | complexité cognitive |
|
|
98
|
+
| crap | `src/a.ts:nom` | score CRAP arrondi à 2 décimales |
|
|
99
|
+
| duplication | `src/a.ts <> src/b.ts` (paire triée) | nombre de clones entre ces deux fichiers |
|
|
100
|
+
|
|
101
|
+
Une clé ne contient aucun numéro de ligne : ajouter du code au-dessus d'une fonction ou d'un clone ne le dégèle pas.
|
|
102
|
+
Le nom d'une fonction est son identifiant, sinon la variable, la propriété ou la méthode qui la reçoit,
|
|
103
|
+
`<appelant>(callback)` pour une fonction passée en argument (`map(callback)`), `default` pour un export par défaut
|
|
104
|
+
anonyme, `<anonymous>` sinon. Les homonymes d'un fichier sont numérotés dans l'ordre du fichier : `name`, `name#2`…
|
|
105
|
+
Un nouveau clone fait échouer la porte même entre deux fichiers déjà gelés, puisqu'il augmente leur nombre de
|
|
106
|
+
clones. La porte duplication ne gèle des clones que si le taux dépasse `duplication.threshold`.
|
|
107
|
+
|
|
108
|
+
`--write-baseline` réécrit les sections des portes lancées et garde les autres : avec `--only crap`, seule la section
|
|
109
|
+
`crap` change. Il rend toujours 0 ; relire le diff du fichier avant de le versionner, car il gèle aussi une
|
|
110
|
+
violation aggravée.
|
|
111
|
+
|
|
112
|
+
Monorepo : chaque lancement de `jsq` a sa référence, dans le dossier où il tourne.
|
|
113
|
+
|
|
114
|
+
- À la racine, `jsq check --only complexity,duplication` lit et écrit `./jsq-baseline.json` (sections `complexity`
|
|
115
|
+
et `duplication`, clés relatives à la racine : `apps/api/src/a.ts:nom`).
|
|
116
|
+
- Dans chaque paquet, `jsq check --only crap` lit et écrit `<paquet>/jsq-baseline.json` (section `crap`, clés
|
|
117
|
+
relatives au paquet : `src/a.ts:nom`), à côté de son `coverage/lcov.info`.
|
|
118
|
+
|
|
119
|
+
## Notes techniques
|
|
120
|
+
|
|
121
|
+
- La complexité est calculée par la règle SonarJS exécutée dans l'Oxlint de `js-quality` (`jsPlugins`), et les
|
|
122
|
+
bornes de chaque fonction, utilisées par le CRAP, par `oxc-parser` : aucune configuration Oxlint ni ESLint dans le
|
|
123
|
+
projet, aucune dépendance à TypeScript. Oxlint mesure des copies temporaires des sources où `eslint-disable` et
|
|
124
|
+
`oxlint-disable` sont rendus inertes (`eslint_disable`, même longueur) : aucun commentaire ne masque une fonction
|
|
125
|
+
ni ne fait échouer la mesure, et les sources du projet ne sont pas modifiées. Un lancement d'Oxlint coûte environ
|
|
126
|
+
une seconde, quel que soit le nombre de fichiers.
|
|
127
|
+
- La mutation utilise le runner Vitest de Stryker (`@stryker-mutator/vitest-runner`), embarqué dans `jsq` et chargé
|
|
128
|
+
par chemin absolu, avec analyse de couverture par test (`coverageAnalysis: "perTest"`) : chaque mutant ne relance
|
|
129
|
+
que les tests qui le couvrent. Aucune configuration ni dépendance Stryker dans le projet. Stryker lit la
|
|
130
|
+
configuration Vitest du projet (`vite.config.ts`) et pose `STRYKER_MUTATOR_WORKER` dans ses processus.
|
|
131
|
+
- `thresholds.high` vaut 90, ou `mutation.break` s'il est plus haut.
|
|
132
|
+
- Stryker n'ajoute pas `// @ts-nocheck` et ne réécrit pas lui-même les `tsconfig.json`, car il le ferait avec l'API
|
|
133
|
+
JavaScript de TypeScript, que TypeScript 7 n'a plus. `jsq` les réécrit par son propre script (commande de build de
|
|
134
|
+
Stryker) : les chemins `extends`, `references`, `include`, `exclude` et `files` qui sortent du bac à sable
|
|
135
|
+
(`.stryker-tmp/sandbox-…`, deux niveaux plus bas) gagnent deux `../`. Vitest lit ces fichiers : sans la
|
|
136
|
+
réécriture, il échoue dans le bac à sable sur un `tsconfig.json` qui étend un fichier hors du paquet.
|
|
137
|
+
- Ajouter `coverage/` et `.stryker-tmp/` au `.gitignore` du projet.
|
|
138
|
+
|
|
139
|
+
### Monorepo
|
|
140
|
+
|
|
141
|
+
`jsq mutation` se lance dans chaque paquet (`vp run --filter <paquet> mutation`) : Stryker copie le paquet seul,
|
|
142
|
+
et un `tsconfig.json` qui étend un fichier de la racine (`"extends": "../../tsconfig.base.json"`) est réécrit pour
|
|
143
|
+
le retrouver. Les `node_modules` du paquet et de ses parents restent résolus par Node depuis le bac à sable.
|
|
144
|
+
|
|
145
|
+
Le runner « command » (`mutation.command`) relance toute la suite du paquet pour chaque mutant. Sur `apps/api` de
|
|
146
|
+
software-atlas, `src/ssm.ts` (26 mutants) prend 6 s avec le runner Vitest (score 73 %, aucune expiration) et 1 min
|
|
147
|
+
27 s avec `"command": "vp test run"`, où les 26 mutants expirent et comptent comme tués (score 100 %, faux).
|
|
148
|
+
Sous charge, le runner « command » surestime donc le score.
|
|
149
|
+
|
|
150
|
+
## Développement
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
vp install
|
|
154
|
+
vp run qa # js-quality s'applique ses propres portes
|
|
155
|
+
vp run mutation # ou : vp run mutation -- --mutate src/crap.ts
|
|
156
|
+
vp pack # construit dist/cli.mjs
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Publication
|
|
160
|
+
|
|
161
|
+
Versionnage sémantique ; tant que la version est en 0.x, une version mineure peut casser la configuration ou la
|
|
162
|
+
sortie. Publier une version :
|
|
163
|
+
|
|
164
|
+
1. Une PR monte `version` dans `package.json`, puis est fusionnée.
|
|
165
|
+
2. Sur `main` à jour : `git tag v<version> && git push origin v<version>`.
|
|
166
|
+
3. Le workflow `release.yml` vérifie que le tag égale la version, lance `vp run qa`, construit l'archive et la publie
|
|
167
|
+
sur npm par trusted publishing (OIDC, sans jeton), avec attestation de provenance.
|
|
168
|
+
|
|
169
|
+
Mise en place, une seule fois : la première version se publie à la main, puis le paquet déclare le workflow comme
|
|
170
|
+
éditeur de confiance, hors du projet : `npm trust github @adrien-chinour/js-quality --repo adrien-chinour/js-quality
|
|
171
|
+
--file release.yml --allow-publish`, ou sur npmjs.com, _Settings_ du paquet, _Trusted Publisher_. La publication à
|
|
172
|
+
la main passe par npm, pas par `vp pm publish` : le jeton de `vp pm login` est rangé dans
|
|
173
|
+
`~/.config/pnpm/auth.ini`, que npm ne lit pas, et npm refuse d'agir dans le projet (`devEngines` impose pnpm). Le
|
|
174
|
+
compte npm exige la double authentification : passkey, ou jeton granulaire avec _bypass 2FA_, à révoquer ensuite.
|
|
175
|
+
|
|
176
|
+
1. Sur `main` à jour : `vp install`.
|
|
177
|
+
2. Construire l'archive hors du projet : `vp pm pack --pack-destination <dossier>`.
|
|
178
|
+
3. Depuis ce dossier : `npm publish ./<archive>.tgz --access public`.
|
|
179
|
+
|
|
180
|
+
## Licence
|
|
181
|
+
|
|
182
|
+
[0BSD](LICENSE) : usage, copie, modification et distribution libres, sans condition.
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { delimiter, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
import { parseArgs, promisify } from "node:util";
|
|
5
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
6
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { parseSync } from "oxc-parser";
|
|
9
|
+
import { runJscpd } from "jscpd";
|
|
10
|
+
import { glob } from "tinyglobby";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
// src/gates.ts
|
|
13
|
+
const GATES = [
|
|
14
|
+
"complexity",
|
|
15
|
+
"crap",
|
|
16
|
+
"duplication"
|
|
17
|
+
];
|
|
18
|
+
// src/baseline.ts
|
|
19
|
+
function isObject(data) {
|
|
20
|
+
return typeof data === "object" && data !== null && !Array.isArray(data);
|
|
21
|
+
}
|
|
22
|
+
function validateSection(gate, section) {
|
|
23
|
+
if (!GATES.includes(gate)) throw new Error(`unknown gate ${gate}`);
|
|
24
|
+
if (!isObject(section)) throw new Error(`${gate} is not an object`);
|
|
25
|
+
for (const [key, value] of Object.entries(section)) if (typeof value !== "number") throw new Error(`${gate}.${key} is not a number`);
|
|
26
|
+
}
|
|
27
|
+
function validate(data) {
|
|
28
|
+
if (!isObject(data)) throw new Error("not an object");
|
|
29
|
+
for (const [gate, section] of Object.entries(data)) validateSection(gate, section);
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
|
+
/** The baseline at `path`, or undefined when there is none. */
|
|
33
|
+
async function readBaseline(path) {
|
|
34
|
+
let text;
|
|
35
|
+
try {
|
|
36
|
+
text = await readFile(path, "utf8");
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (error.code === "ENOENT") return void 0;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
return validate(JSON.parse(text));
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new Error(`invalid baseline ${path}: ${error.message}`, { cause: error });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Gates in their usual order, keys sorted, empty sections left out: the same text for the same content. */
|
|
48
|
+
function serializeBaseline(baseline) {
|
|
49
|
+
const sections = GATES.flatMap((gate) => {
|
|
50
|
+
const section = baseline[gate] ?? {};
|
|
51
|
+
const keys = Object.keys(section).sort();
|
|
52
|
+
return keys.length === 0 ? [] : [[gate, Object.fromEntries(keys.map((key) => [key, section[key]]))]];
|
|
53
|
+
});
|
|
54
|
+
return `${JSON.stringify(Object.fromEntries(sections), null, 2)}\n`;
|
|
55
|
+
}
|
|
56
|
+
async function writeBaseline(path, baseline) {
|
|
57
|
+
await mkdir(dirname(path), { recursive: true });
|
|
58
|
+
await writeFile(path, serializeBaseline(baseline));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Keys of the current violations that fail (not frozen, or above their frozen value), and frozen keys that no
|
|
62
|
+
* longer violate the gate (fixed or renamed).
|
|
63
|
+
*/
|
|
64
|
+
function compareToBaseline(current, frozen) {
|
|
65
|
+
return {
|
|
66
|
+
failing: Object.keys(current).filter((key) => frozen[key] === void 0 || current[key] > frozen[key]),
|
|
67
|
+
stale: Object.keys(frozen).filter((key) => current[key] === void 0).sort()
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
// src/complexity.ts
|
|
71
|
+
const require$1 = createRequire(import.meta.url);
|
|
72
|
+
const run = promisify(execFile);
|
|
73
|
+
const FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
74
|
+
"FunctionDeclaration",
|
|
75
|
+
"FunctionExpression",
|
|
76
|
+
"ArrowFunctionExpression"
|
|
77
|
+
]);
|
|
78
|
+
const SKIPPED_KEYS = /* @__PURE__ */ new Set([
|
|
79
|
+
"parent",
|
|
80
|
+
"range",
|
|
81
|
+
"comments"
|
|
82
|
+
]);
|
|
83
|
+
function oxlintConfig() {
|
|
84
|
+
return {
|
|
85
|
+
categories: Object.fromEntries([
|
|
86
|
+
"correctness",
|
|
87
|
+
"suspicious",
|
|
88
|
+
"pedantic",
|
|
89
|
+
"style",
|
|
90
|
+
"perf",
|
|
91
|
+
"restriction",
|
|
92
|
+
"nursery"
|
|
93
|
+
].map((category) => [category, "off"])),
|
|
94
|
+
plugins: [],
|
|
95
|
+
jsPlugins: [require$1.resolve("eslint-plugin-sonarjs")],
|
|
96
|
+
rules: { "sonarjs/cognitive-complexity": ["error", 0] },
|
|
97
|
+
options: { respectEslintDisableDirectives: false }
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function isNode(value) {
|
|
101
|
+
return typeof value?.type === "string";
|
|
102
|
+
}
|
|
103
|
+
/** Child nodes of a node, arrays of nodes flattened. */
|
|
104
|
+
function children(node) {
|
|
105
|
+
return Object.entries(node).filter(([key, value]) => !SKIPPED_KEYS.has(key) && typeof value === "object").flatMap(([, value]) => Array.isArray(value) ? value : [value]);
|
|
106
|
+
}
|
|
107
|
+
/** Line (1-based) of each UTF-16 offset, which is what oxc-parser reports. */
|
|
108
|
+
function lineAt(source) {
|
|
109
|
+
const starts = [0];
|
|
110
|
+
for (let index = source.indexOf("\n"); index !== -1; index = source.indexOf("\n", index + 1)) starts.push(index + 1);
|
|
111
|
+
return (offset) => starts.findLastIndex((start) => start <= offset) + 1;
|
|
112
|
+
}
|
|
113
|
+
const WRAPPERS = /* @__PURE__ */ new Set([
|
|
114
|
+
"ParenthesizedExpression",
|
|
115
|
+
"TSAsExpression",
|
|
116
|
+
"TSSatisfiesExpression",
|
|
117
|
+
"TSNonNullExpression",
|
|
118
|
+
"TSTypeAssertion"
|
|
119
|
+
]);
|
|
120
|
+
const KEYED_OWNERS = /* @__PURE__ */ new Set([
|
|
121
|
+
"MethodDefinition",
|
|
122
|
+
"Property",
|
|
123
|
+
"PropertyDefinition"
|
|
124
|
+
]);
|
|
125
|
+
function keyName(key, computed) {
|
|
126
|
+
const node = key;
|
|
127
|
+
if (computed === true || !isNode(node)) return void 0;
|
|
128
|
+
if (node.type === "Identifier" || node.type === "PrivateIdentifier") return node.name;
|
|
129
|
+
return node.type === "Literal" ? String(node.value) : void 0;
|
|
130
|
+
}
|
|
131
|
+
/** `a` for `a`, `c` for `a.b.c`. */
|
|
132
|
+
function lastName(node) {
|
|
133
|
+
if (node.type === "MemberExpression") return keyName(node.property, node.computed);
|
|
134
|
+
return keyName(node, false);
|
|
135
|
+
}
|
|
136
|
+
/** Name a function owes to where it stands: variable, property, method, or callback of a call. */
|
|
137
|
+
function nameFromOwner({ node, child }) {
|
|
138
|
+
switch (node.type) {
|
|
139
|
+
case "VariableDeclarator": return keyName(node.id, false);
|
|
140
|
+
case "AssignmentExpression": return lastName(node.left);
|
|
141
|
+
case "Property":
|
|
142
|
+
case "MethodDefinition":
|
|
143
|
+
case "PropertyDefinition": return keyName(node.key, node.computed);
|
|
144
|
+
case "ExportDefaultDeclaration": return "default";
|
|
145
|
+
case "CallExpression":
|
|
146
|
+
case "NewExpression": {
|
|
147
|
+
const callee = node.arguments.includes(child) ? lastName(node.callee) : void 0;
|
|
148
|
+
return callee === void 0 ? void 0 : `${callee}(callback)`;
|
|
149
|
+
}
|
|
150
|
+
default: return;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function functionName(node, owner) {
|
|
154
|
+
return keyName(node.id, false) ?? (owner && nameFromOwner(owner)) ?? "<anonymous>";
|
|
155
|
+
}
|
|
156
|
+
function collectFunctions(node, owner, line, found) {
|
|
157
|
+
if (FUNCTION_TYPES.has(node.type)) found.push({
|
|
158
|
+
name: functionName(node, owner),
|
|
159
|
+
start: node.start,
|
|
160
|
+
from: owner && KEYED_OWNERS.has(owner.node.type) ? owner.node.start : node.start,
|
|
161
|
+
to: node.end,
|
|
162
|
+
startLine: line(node.start),
|
|
163
|
+
endLine: line(node.end)
|
|
164
|
+
});
|
|
165
|
+
const wrapper = WRAPPERS.has(node.type);
|
|
166
|
+
for (const child of children(node).filter(isNode)) collectFunctions(child, wrapper ? owner : {
|
|
167
|
+
node,
|
|
168
|
+
child
|
|
169
|
+
}, line, found);
|
|
170
|
+
}
|
|
171
|
+
/** Homonyms of a file numbered in source order: `name`, `name#2`… */
|
|
172
|
+
function numberHomonyms(found) {
|
|
173
|
+
const seen = /* @__PURE__ */ new Map();
|
|
174
|
+
return found.sort((a, b) => a.start - b.start).map(({ name, from, to, startLine, endLine }) => {
|
|
175
|
+
const rank = (seen.get(name) ?? 0) + 1;
|
|
176
|
+
seen.set(name, rank);
|
|
177
|
+
return {
|
|
178
|
+
name: rank > 1 ? `${name}#${rank}` : name,
|
|
179
|
+
from,
|
|
180
|
+
to,
|
|
181
|
+
startLine,
|
|
182
|
+
endLine
|
|
183
|
+
};
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
function languageOf(file) {
|
|
187
|
+
const extension = extname(file);
|
|
188
|
+
if (extension === ".tsx") return "tsx";
|
|
189
|
+
return [
|
|
190
|
+
".ts",
|
|
191
|
+
".mts",
|
|
192
|
+
".cts"
|
|
193
|
+
].includes(extension) ? "ts" : "jsx";
|
|
194
|
+
}
|
|
195
|
+
/** Name, offsets and line range of every function of a source; fails on a syntax error. */
|
|
196
|
+
function functionRanges({ file, source }) {
|
|
197
|
+
const { program, errors } = parseSync(file, source, {
|
|
198
|
+
lang: languageOf(file),
|
|
199
|
+
sourceType: "module"
|
|
200
|
+
});
|
|
201
|
+
const line = lineAt(source);
|
|
202
|
+
const [error] = errors;
|
|
203
|
+
if (error) throw new Error(`${file}:${line(error.labels[0]?.start ?? 0)}: ${error.message}`);
|
|
204
|
+
const found = [];
|
|
205
|
+
collectFunctions(program, void 0, line, found);
|
|
206
|
+
return numberHomonyms(found);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The innermost function holding an offset. A line is not enough: a function and its callback often start on
|
|
210
|
+
* the same one (`const f = (xs) => xs.map((x) => …)`).
|
|
211
|
+
*/
|
|
212
|
+
function enclosingFunction(ranges, offset) {
|
|
213
|
+
return ranges.filter((range) => range.from <= offset && offset < range.to).sort((a, b) => a.to - a.from - (b.to - b.from))[0];
|
|
214
|
+
}
|
|
215
|
+
/** UTF-16 offset, which oxc-parser reports, of a UTF-8 byte offset, which Oxlint reports. */
|
|
216
|
+
function utf16Offset(bytes, byteOffset) {
|
|
217
|
+
return bytes.subarray(0, byteOffset).toString("utf8").length;
|
|
218
|
+
}
|
|
219
|
+
function complexityFromMessage(message) {
|
|
220
|
+
const match = /Cognitive Complexity from (\d+)/.exec(message);
|
|
221
|
+
return match ? Number(match[1]) : void 0;
|
|
222
|
+
}
|
|
223
|
+
const DIRECTIVE = /\b(eslint|oxlint)-disable/g;
|
|
224
|
+
function neutraliseDirectives(source) {
|
|
225
|
+
return source.replace(DIRECTIVE, "$1_disable");
|
|
226
|
+
}
|
|
227
|
+
async function runOxlint(directory) {
|
|
228
|
+
const args = [
|
|
229
|
+
join(dirname(require$1.resolve("oxlint/package.json")), "bin", "oxlint"),
|
|
230
|
+
"-c",
|
|
231
|
+
".oxlintrc.json",
|
|
232
|
+
"-f",
|
|
233
|
+
"json",
|
|
234
|
+
"--disable-nested-config",
|
|
235
|
+
"."
|
|
236
|
+
];
|
|
237
|
+
const { stdout } = await run(process.execPath, args, {
|
|
238
|
+
cwd: directory,
|
|
239
|
+
maxBuffer: 268435456
|
|
240
|
+
}).catch((error) => {
|
|
241
|
+
if (error.code === 1 && error.stdout) return { stdout: error.stdout };
|
|
242
|
+
throw new Error(`oxlint failed: ${error.stderr || error.message}`);
|
|
243
|
+
});
|
|
244
|
+
return JSON.parse(stdout);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Name of the copy of the source at `index`: flat, so no `../` leads out of the temporary directory
|
|
248
|
+
* and no path matches a pattern Oxlint skips (`*.min.js`…); its extension sets the language.
|
|
249
|
+
*/
|
|
250
|
+
function copyName(index, file) {
|
|
251
|
+
return `${index}.${languageOf(file)}`;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Copies of the sources, directives neutralised, measured by Oxlint in a temporary directory;
|
|
255
|
+
* diagnostics carry the original path back.
|
|
256
|
+
*/
|
|
257
|
+
async function lintCopies(sources) {
|
|
258
|
+
const directory = await mkdtemp(join(tmpdir(), "jsq-oxlint-"));
|
|
259
|
+
try {
|
|
260
|
+
await writeFile(join(directory, ".oxlintrc.json"), JSON.stringify(oxlintConfig()));
|
|
261
|
+
const original = /* @__PURE__ */ new Map();
|
|
262
|
+
for (const [index, { file, source }] of sources.entries()) {
|
|
263
|
+
original.set(copyName(index, file), file);
|
|
264
|
+
await writeFile(join(directory, copyName(index, file)), neutraliseDirectives(source));
|
|
265
|
+
}
|
|
266
|
+
const report = await runOxlint(directory);
|
|
267
|
+
if (report.number_of_files !== sources.length) throw new Error(`oxlint linted ${report.number_of_files} of ${sources.length} file(s)`);
|
|
268
|
+
return report.diagnostics.map((diagnostic) => {
|
|
269
|
+
const filename = original.get(diagnostic.filename);
|
|
270
|
+
if (filename === void 0) throw new Error(`oxlint reported an unknown file: ${diagnostic.filename}`);
|
|
271
|
+
return {
|
|
272
|
+
...diagnostic,
|
|
273
|
+
filename
|
|
274
|
+
};
|
|
275
|
+
});
|
|
276
|
+
} finally {
|
|
277
|
+
await rm(directory, {
|
|
278
|
+
recursive: true,
|
|
279
|
+
force: true
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function toComplexity(diagnostic, parsed) {
|
|
284
|
+
const file = diagnostic.filename;
|
|
285
|
+
const span = diagnostic.labels[0]?.span;
|
|
286
|
+
const line = span?.line ?? 0;
|
|
287
|
+
const complexity = complexityFromMessage(diagnostic.message);
|
|
288
|
+
if (complexity === void 0 || span === void 0) throw new Error(`${file}:${line}: ${diagnostic.message}`);
|
|
289
|
+
const { bytes, ranges } = parsed.get(file);
|
|
290
|
+
const range = enclosingFunction(ranges, bytes === void 0 ? span.offset : utf16Offset(bytes, span.offset));
|
|
291
|
+
if (range === void 0) return {
|
|
292
|
+
file,
|
|
293
|
+
line,
|
|
294
|
+
complexity,
|
|
295
|
+
name: "<anonymous>",
|
|
296
|
+
startLine: line,
|
|
297
|
+
endLine: line
|
|
298
|
+
};
|
|
299
|
+
return {
|
|
300
|
+
file,
|
|
301
|
+
line,
|
|
302
|
+
complexity,
|
|
303
|
+
name: range.name,
|
|
304
|
+
startLine: range.startLine,
|
|
305
|
+
endLine: range.endLine
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function compareText(a, b) {
|
|
309
|
+
if (a === b) return 0;
|
|
310
|
+
return a < b ? -1 : 1;
|
|
311
|
+
}
|
|
312
|
+
/** Cognitive complexity of every function whose complexity is above 0, in file then line order. */
|
|
313
|
+
async function measureSources(sources) {
|
|
314
|
+
if (sources.length === 0) return [];
|
|
315
|
+
const parsed = new Map(sources.map((source) => [source.file, {
|
|
316
|
+
bytes: Buffer.byteLength(source.source) === source.source.length ? void 0 : Buffer.from(source.source, "utf8"),
|
|
317
|
+
ranges: functionRanges(source)
|
|
318
|
+
}]));
|
|
319
|
+
return (await lintCopies(sources)).map((diagnostic) => toComplexity(diagnostic, parsed)).sort((a, b) => compareText(a.file, b.file) || a.line - b.line);
|
|
320
|
+
}
|
|
321
|
+
async function measureFiles(root, files) {
|
|
322
|
+
return measureSources(await Promise.all(files.map(async (file) => ({
|
|
323
|
+
file,
|
|
324
|
+
source: await readFile(join(root, file), "utf8")
|
|
325
|
+
}))));
|
|
326
|
+
}
|
|
327
|
+
// src/crap.ts
|
|
328
|
+
/** CRAP formula, with cognitive complexity in place of cyclomatic complexity. */
|
|
329
|
+
function crapScore(complexity, coverage) {
|
|
330
|
+
return complexity ** 2 * (1 - coverage) ** 3 + complexity;
|
|
331
|
+
}
|
|
332
|
+
/** Hit count of each line, per source file of an LCOV report, keyed by path relative to the root. */
|
|
333
|
+
function parseLcov(text, root) {
|
|
334
|
+
const files = /* @__PURE__ */ new Map();
|
|
335
|
+
let lines = /* @__PURE__ */ new Map();
|
|
336
|
+
for (const record of text.split("\n")) if (record.startsWith("SF:")) {
|
|
337
|
+
const path = record.slice(3).trim();
|
|
338
|
+
lines = /* @__PURE__ */ new Map();
|
|
339
|
+
files.set(relative(root, isAbsolute(path) ? path : resolve(root, path)), lines);
|
|
340
|
+
} else if (record.startsWith("DA:")) {
|
|
341
|
+
const [line, hits] = record.slice(3).split(",");
|
|
342
|
+
lines.set(Number(line), Number(hits));
|
|
343
|
+
}
|
|
344
|
+
return files;
|
|
345
|
+
}
|
|
346
|
+
/** Share of the instrumented lines hit. A function absent from the report was never loaded: uncovered. */
|
|
347
|
+
function lineCoverage(hits, startLine, endLine) {
|
|
348
|
+
if (!hits) return 0;
|
|
349
|
+
let total = 0;
|
|
350
|
+
let hit = 0;
|
|
351
|
+
for (let line = startLine; line <= endLine; line += 1) {
|
|
352
|
+
const count = hits.get(line);
|
|
353
|
+
if (count === void 0) continue;
|
|
354
|
+
total += 1;
|
|
355
|
+
if (count > 0) hit += 1;
|
|
356
|
+
}
|
|
357
|
+
return total === 0 ? 0 : hit / total;
|
|
358
|
+
}
|
|
359
|
+
function scoreFunctions(functions, lcov) {
|
|
360
|
+
return functions.map((fn) => {
|
|
361
|
+
const coverage = lineCoverage(lcov.get(fn.file), fn.startLine, fn.endLine);
|
|
362
|
+
return {
|
|
363
|
+
...fn,
|
|
364
|
+
coverage,
|
|
365
|
+
crap: crapScore(fn.complexity, coverage)
|
|
366
|
+
};
|
|
367
|
+
}).sort((a, b) => b.crap - a.crap);
|
|
368
|
+
}
|
|
369
|
+
async function readLcov(root, path) {
|
|
370
|
+
let text;
|
|
371
|
+
try {
|
|
372
|
+
text = await readFile(resolve(root, path), "utf8");
|
|
373
|
+
} catch {
|
|
374
|
+
throw new Error(`no coverage report at ${path}: run \`vp test run --coverage\` first`);
|
|
375
|
+
}
|
|
376
|
+
return parseLcov(text, root);
|
|
377
|
+
}
|
|
378
|
+
// src/duplication.ts
|
|
379
|
+
/** jscpd runs with `--absolute`: paths come back relative to the project root. */
|
|
380
|
+
function toReport(raw, root) {
|
|
381
|
+
const location = ({ name, start, end }) => ({
|
|
382
|
+
name: relative(root, name),
|
|
383
|
+
start,
|
|
384
|
+
end
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
clones: raw.duplicates.map((clone) => ({
|
|
388
|
+
first: location(clone.firstFile),
|
|
389
|
+
second: location(clone.secondFile),
|
|
390
|
+
lines: clone.lines,
|
|
391
|
+
tokens: clone.tokens
|
|
392
|
+
})),
|
|
393
|
+
percentage: raw.statistics.total.percentage
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/** Runs jscpd on the given files (relative to the root) and reads its JSON report. */
|
|
397
|
+
async function detectClones(root, files, settings) {
|
|
398
|
+
if (files.length === 0) return {
|
|
399
|
+
clones: [],
|
|
400
|
+
percentage: 0
|
|
401
|
+
};
|
|
402
|
+
const output = await mkdtemp(join(tmpdir(), "jsq-jscpd-"));
|
|
403
|
+
try {
|
|
404
|
+
const args = [
|
|
405
|
+
...files,
|
|
406
|
+
["--min-tokens", String(settings.minTokens)],
|
|
407
|
+
["--min-lines", String(settings.minLines)],
|
|
408
|
+
[
|
|
409
|
+
"--reporters",
|
|
410
|
+
"json",
|
|
411
|
+
"--output",
|
|
412
|
+
output,
|
|
413
|
+
"--no-gitignore",
|
|
414
|
+
"--absolute"
|
|
415
|
+
]
|
|
416
|
+
].flat();
|
|
417
|
+
const result = runJscpd(args, {
|
|
418
|
+
cwd: root,
|
|
419
|
+
encoding: "utf8"
|
|
420
|
+
});
|
|
421
|
+
if (result.error) throw result.error;
|
|
422
|
+
if (result.status !== 0) throw new Error(`jscpd failed: ${result.stderr || result.stdout}`);
|
|
423
|
+
return toReport(JSON.parse(await readFile(join(output, "jscpd-report.json"), "utf8")), root);
|
|
424
|
+
} finally {
|
|
425
|
+
await rm(output, {
|
|
426
|
+
recursive: true,
|
|
427
|
+
force: true
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
/** Same rule as `jscpd --threshold`: fails above the threshold, so 0 forbids any clone. */
|
|
432
|
+
function exceeds(report, threshold) {
|
|
433
|
+
return report.percentage > threshold;
|
|
434
|
+
}
|
|
435
|
+
// src/files.ts
|
|
436
|
+
/** Source files measured by the gates, relative to the root and sorted. */
|
|
437
|
+
async function sourceFiles(root, config) {
|
|
438
|
+
return (await glob(config.src, {
|
|
439
|
+
cwd: root,
|
|
440
|
+
ignore: config.ignore
|
|
441
|
+
})).sort();
|
|
442
|
+
}
|
|
443
|
+
// src/check.ts
|
|
444
|
+
function withoutBaseline(verdict) {
|
|
445
|
+
const count = verdict.violations.length;
|
|
446
|
+
return {
|
|
447
|
+
passed: count === 0,
|
|
448
|
+
summary: count === 0 ? verdict.clean : verdict.failed(count),
|
|
449
|
+
details: verdict.violations.flatMap((violation) => violation.lines)
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
function againstBaseline(verdict, frozen, current) {
|
|
453
|
+
const { failing, stale } = compareToBaseline(current, frozen);
|
|
454
|
+
const failed = new Set(failing);
|
|
455
|
+
const tolerated = verdict.violations.length - failing.length;
|
|
456
|
+
const details = verdict.violations.filter((violation) => failed.has(violation.key)).flatMap(({ key, value, lines: [first, ...rest] }) => {
|
|
457
|
+
return [`${first} ${key}: ${frozen[key] === void 0 ? "not frozen" : `${value} > frozen ${frozen[key]}`}`, ...rest];
|
|
458
|
+
});
|
|
459
|
+
const warnings = stale.length === 0 ? [] : [`! ${stale.length} frozen entry(ies) no longer fail (fixed or renamed): remove them from the baseline`, ...stale.map((key) => ` ${key}`)];
|
|
460
|
+
let summary = verdict.clean;
|
|
461
|
+
if (failing.length > 0) summary = verdict.failed(failing.length) + (tolerated > 0 ? ` (${tolerated} more frozen)` : "");
|
|
462
|
+
else if (tolerated > 0) summary = `${tolerated} ${verdict.what}, all frozen`;
|
|
463
|
+
return {
|
|
464
|
+
passed: failing.length === 0,
|
|
465
|
+
summary,
|
|
466
|
+
details,
|
|
467
|
+
warnings
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
/** Judges the violations of a gate; without baseline, any violation fails it. */
|
|
471
|
+
function judge(verdict, frozen) {
|
|
472
|
+
const violations = Object.fromEntries(verdict.violations.map(({ key, value }) => [key, value]));
|
|
473
|
+
const outcome = frozen === void 0 ? {
|
|
474
|
+
...withoutBaseline(verdict),
|
|
475
|
+
warnings: []
|
|
476
|
+
} : againstBaseline(verdict, frozen, violations);
|
|
477
|
+
return {
|
|
478
|
+
gate: verdict.gate,
|
|
479
|
+
...outcome,
|
|
480
|
+
violations
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
function where(fn) {
|
|
484
|
+
return `${fn.file}:${fn.line}`;
|
|
485
|
+
}
|
|
486
|
+
/** Key of a function in the baseline: no line number, so code added above it does not unfreeze it. */
|
|
487
|
+
function functionKey(fn) {
|
|
488
|
+
return `${fn.file}:${fn.name}`;
|
|
489
|
+
}
|
|
490
|
+
function complexityGate(functions, limit, frozen) {
|
|
491
|
+
const violations = functions.filter((fn) => fn.complexity > limit).sort((a, b) => b.complexity - a.complexity).map((fn) => ({
|
|
492
|
+
key: functionKey(fn),
|
|
493
|
+
value: fn.complexity,
|
|
494
|
+
lines: [`cognitive ${String(fn.complexity).padStart(3)} ${where(fn)}`]
|
|
495
|
+
}));
|
|
496
|
+
const what = `function(s) above cognitive complexity ${limit}`;
|
|
497
|
+
return judge({
|
|
498
|
+
gate: "complexity",
|
|
499
|
+
violations,
|
|
500
|
+
clean: `${functions.length} function(s) measured, none above ${limit}`,
|
|
501
|
+
failed: (count) => `${count} ${what}: split them`,
|
|
502
|
+
what
|
|
503
|
+
}, frozen);
|
|
504
|
+
}
|
|
505
|
+
const round = (score) => Math.round(score * 100) / 100;
|
|
506
|
+
function crapGate(scores, limit, frozen) {
|
|
507
|
+
const violations = scores.filter((score) => score.crap >= limit).map((score) => ({
|
|
508
|
+
key: functionKey(score),
|
|
509
|
+
value: round(score.crap),
|
|
510
|
+
lines: [`crap ${score.crap.toFixed(1).padStart(6)} cognitive ${String(score.complexity).padStart(2)} coverage ${(score.coverage * 100).toFixed(0).padStart(3)}% ${where(score)}`]
|
|
511
|
+
}));
|
|
512
|
+
const what = `function(s) at or above CRAP ${limit}`;
|
|
513
|
+
return judge({
|
|
514
|
+
gate: "crap",
|
|
515
|
+
violations,
|
|
516
|
+
clean: `${scores.length} function(s) scored, none at or above ${limit}`,
|
|
517
|
+
failed: (count) => `${count} ${what}: split them, test them, or both`,
|
|
518
|
+
what
|
|
519
|
+
}, frozen);
|
|
520
|
+
}
|
|
521
|
+
/** Key of a clone in the baseline: its pair of files, in either order and without lines. */
|
|
522
|
+
function pairKey({ first, second }) {
|
|
523
|
+
return [first.name, second.name].sort().join(" <> ");
|
|
524
|
+
}
|
|
525
|
+
/** The clones grouped by pair of files, a violation each, valued by its number of clones. */
|
|
526
|
+
function clonePairs(clones) {
|
|
527
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
528
|
+
for (const clone of clones) {
|
|
529
|
+
const key = pairKey(clone);
|
|
530
|
+
const pair = pairs.get(key) ?? {
|
|
531
|
+
key,
|
|
532
|
+
value: 0,
|
|
533
|
+
lines: []
|
|
534
|
+
};
|
|
535
|
+
pair.value += 1;
|
|
536
|
+
pair.lines.push(`${String(clone.lines).padStart(3)} lines ${clone.first.name}:${clone.first.start}-${clone.first.end} = ${clone.second.name}:${clone.second.start}-${clone.second.end}`);
|
|
537
|
+
pairs.set(key, pair);
|
|
538
|
+
}
|
|
539
|
+
return [...pairs.values()];
|
|
540
|
+
}
|
|
541
|
+
function duplicationGate(report, threshold, frozen) {
|
|
542
|
+
const duplicated = `${report.percentage.toFixed(2)}% duplicated`;
|
|
543
|
+
const above = exceeds(report, threshold);
|
|
544
|
+
return judge({
|
|
545
|
+
gate: "duplication",
|
|
546
|
+
violations: above ? clonePairs(report.clones) : [],
|
|
547
|
+
clean: `${report.clones.length} clone(s), ${duplicated} (limit ${threshold}%)`,
|
|
548
|
+
failed: () => `${duplicated}, above ${threshold}%: extract the shared code`,
|
|
549
|
+
what: `clone pair(s) of files above ${threshold}%`
|
|
550
|
+
}, above ? frozen : void 0);
|
|
551
|
+
}
|
|
552
|
+
/** Runs the selected gates. Complexity is measured once and shared by the complexity and CRAP gates. */
|
|
553
|
+
async function runCheck(root, config, gates, baseline) {
|
|
554
|
+
const frozen = (gate) => baseline === void 0 ? void 0 : baseline[gate] ?? {};
|
|
555
|
+
const files = await sourceFiles(root, config);
|
|
556
|
+
if (files.length === 0) throw new Error(`no source file matches src: ${config.src.join(", ")}`);
|
|
557
|
+
const functions = gates.includes("complexity") || gates.includes("crap") ? await measureFiles(root, files) : [];
|
|
558
|
+
const results = [];
|
|
559
|
+
if (gates.includes("complexity")) results.push(complexityGate(functions, config.complexity, frozen("complexity")));
|
|
560
|
+
if (gates.includes("crap")) results.push(crapGate(scoreFunctions(functions, await readLcov(root, config.lcov)), config.crap, frozen("crap")));
|
|
561
|
+
if (gates.includes("duplication")) results.push(duplicationGate(await detectClones(root, files, config.duplication), config.duplication.threshold, frozen("duplication")));
|
|
562
|
+
return results;
|
|
563
|
+
}
|
|
564
|
+
function formatResults(results) {
|
|
565
|
+
return results.flatMap((result) => [`${result.passed ? "✓" : "✗"} ${result.gate.padEnd(11)} ${result.summary}`, ...[...result.details, ...result.warnings].map((line) => ` ${line}`)]).join("\n");
|
|
566
|
+
}
|
|
567
|
+
// src/config.ts
|
|
568
|
+
const defaults = {
|
|
569
|
+
src: ["src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"],
|
|
570
|
+
ignore: [
|
|
571
|
+
"**/*.d.ts",
|
|
572
|
+
"**/*.test.*",
|
|
573
|
+
"**/*.spec.*",
|
|
574
|
+
"**/node_modules/**",
|
|
575
|
+
"**/dist/**"
|
|
576
|
+
],
|
|
577
|
+
complexity: 15,
|
|
578
|
+
crap: 10,
|
|
579
|
+
lcov: "coverage/lcov.info",
|
|
580
|
+
baseline: "jsq-baseline.json",
|
|
581
|
+
duplication: {
|
|
582
|
+
minTokens: 40,
|
|
583
|
+
minLines: 4,
|
|
584
|
+
threshold: 0
|
|
585
|
+
},
|
|
586
|
+
mutation: {
|
|
587
|
+
break: 70,
|
|
588
|
+
mutate: []
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
/** Merges the optional `jsq` block of the project's package.json over the defaults. */
|
|
592
|
+
function mergeConfig(overrides = {}) {
|
|
593
|
+
return {
|
|
594
|
+
...defaults,
|
|
595
|
+
...overrides,
|
|
596
|
+
duplication: {
|
|
597
|
+
...defaults.duplication,
|
|
598
|
+
...overrides.duplication
|
|
599
|
+
},
|
|
600
|
+
mutation: {
|
|
601
|
+
...defaults.mutation,
|
|
602
|
+
...overrides.mutation
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
async function loadConfig(root) {
|
|
607
|
+
let manifest;
|
|
608
|
+
try {
|
|
609
|
+
manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
|
|
610
|
+
} catch {
|
|
611
|
+
return mergeConfig();
|
|
612
|
+
}
|
|
613
|
+
return mergeConfig(manifest.jsq);
|
|
614
|
+
}
|
|
615
|
+
// src/mutation.ts
|
|
616
|
+
const require = createRequire(import.meta.url);
|
|
617
|
+
/** Script that prepares Stryker's sandbox: next to this module, `.ts` in the sources, `.mjs` once built. */
|
|
618
|
+
const SANDBOX_BUILD = fileURLToPath(new URL(`sandbox-build${extname(import.meta.url)}`, import.meta.url));
|
|
619
|
+
/** A command line as Stryker splits it: on spaces, unless escaped. */
|
|
620
|
+
const commandLine = (...words) => words.map((word) => word.replaceAll(" ", "\\ ")).join(" ");
|
|
621
|
+
/** Files Stryker mutates: the given ones, else the gates' sources minus their ignores. */
|
|
622
|
+
function mutateGlobs(config, only) {
|
|
623
|
+
if (only.length > 0) return only;
|
|
624
|
+
if (config.mutation.mutate.length > 0) return config.mutation.mutate;
|
|
625
|
+
return [...config.src, ...config.ignore.map((glob) => `!${glob}`)];
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* How Stryker runs the tests. By default, the Vitest runner jsq embeds, loaded by absolute path so the project
|
|
629
|
+
* needs no Stryker plugin, with per-test coverage: each mutant runs only the tests that cover it. With
|
|
630
|
+
* `mutation.command`, the command runner runs that command for every mutant, whatever runs the tests.
|
|
631
|
+
*/
|
|
632
|
+
function testRunner(command) {
|
|
633
|
+
if (command) return {
|
|
634
|
+
testRunner: "command",
|
|
635
|
+
commandRunner: { command },
|
|
636
|
+
coverageAnalysis: "off"
|
|
637
|
+
};
|
|
638
|
+
return {
|
|
639
|
+
testRunner: "vitest",
|
|
640
|
+
plugins: [require.resolve("@stryker-mutator/vitest-runner")],
|
|
641
|
+
coverageAnalysis: "perTest"
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
/** Stryker configuration. */
|
|
645
|
+
function strykerConfig(config, only) {
|
|
646
|
+
const { command, break: breaking } = config.mutation;
|
|
647
|
+
return {
|
|
648
|
+
...testRunner(command),
|
|
649
|
+
mutate: mutateGlobs(config, only),
|
|
650
|
+
reporters: ["clear-text", "progress"],
|
|
651
|
+
thresholds: {
|
|
652
|
+
high: Math.max(90, breaking),
|
|
653
|
+
low: breaking,
|
|
654
|
+
break: breaking
|
|
655
|
+
},
|
|
656
|
+
tempDirName: ".stryker-tmp",
|
|
657
|
+
disableTypeChecks: false,
|
|
658
|
+
tsconfigFile: ".jsq-no-tsconfig.json",
|
|
659
|
+
buildCommand: commandLine(process.execPath, SANDBOX_BUILD),
|
|
660
|
+
cleanTempDir: true
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
/** Runs Stryker in the project and returns its exit code (non-zero below the break threshold). */
|
|
664
|
+
async function runMutation(root, config, only) {
|
|
665
|
+
const directory = await mkdtemp(join(tmpdir(), "jsq-stryker-"));
|
|
666
|
+
const configFile = join(directory, "stryker.config.json");
|
|
667
|
+
try {
|
|
668
|
+
await writeFile(configFile, JSON.stringify(strykerConfig(config, only), null, 2));
|
|
669
|
+
const stryker = join(dirname(require.resolve("@stryker-mutator/core/package.json")), "bin", "stryker.js");
|
|
670
|
+
const path = [join(root, "node_modules", ".bin"), process.env.PATH].join(delimiter);
|
|
671
|
+
const result = spawnSync(process.execPath, [
|
|
672
|
+
stryker,
|
|
673
|
+
"run",
|
|
674
|
+
configFile
|
|
675
|
+
], {
|
|
676
|
+
cwd: root,
|
|
677
|
+
stdio: "inherit",
|
|
678
|
+
env: {
|
|
679
|
+
...process.env,
|
|
680
|
+
PATH: path
|
|
681
|
+
}
|
|
682
|
+
});
|
|
683
|
+
if (result.error) throw result.error;
|
|
684
|
+
return result.status ?? 1;
|
|
685
|
+
} finally {
|
|
686
|
+
await rm(directory, {
|
|
687
|
+
recursive: true,
|
|
688
|
+
force: true
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
// src/cli.ts
|
|
693
|
+
const USAGE = `Usage:
|
|
694
|
+
jsq check [--only complexity,crap,duplication] cognitive complexity, CRAP and duplication gates
|
|
695
|
+
jsq check --write-baseline [--only …] freeze the current violations of the gates
|
|
696
|
+
jsq mutation [--mutate <glob>]... mutation testing with Stryker and Vitest
|
|
697
|
+
|
|
698
|
+
Settings: optional "jsq" block of package.json (src, ignore, complexity, crap, lcov, baseline,
|
|
699
|
+
duplication.{minTokens,minLines,threshold}, mutation.{command,break,mutate}).`;
|
|
700
|
+
function parseGates(value) {
|
|
701
|
+
if (value === void 0) return [...GATES];
|
|
702
|
+
const names = value.split(",").map((name) => name.trim());
|
|
703
|
+
const unknown = names.filter((name) => !GATES.includes(name));
|
|
704
|
+
if (unknown.length > 0) throw new Error(`unknown gate(s): ${unknown.join(", ")}`);
|
|
705
|
+
return names;
|
|
706
|
+
}
|
|
707
|
+
/** Rewrites the sections of the selected gates with their current violations; the other sections stay. */
|
|
708
|
+
async function freeze(root, config, gates) {
|
|
709
|
+
const path = resolve(root, config.baseline);
|
|
710
|
+
const results = await runCheck(root, config, gates);
|
|
711
|
+
const fresh = Object.fromEntries(results.map((result) => [result.gate, result.violations]));
|
|
712
|
+
await writeBaseline(path, {
|
|
713
|
+
...await readBaseline(path),
|
|
714
|
+
...fresh
|
|
715
|
+
});
|
|
716
|
+
for (const { gate, violations } of results) {
|
|
717
|
+
const count = Object.keys(violations).length;
|
|
718
|
+
console.log(`${gate.padEnd(11)} ${count} entry(ies) frozen in ${config.baseline}`);
|
|
719
|
+
}
|
|
720
|
+
return 0;
|
|
721
|
+
}
|
|
722
|
+
async function check(root, only, writing) {
|
|
723
|
+
const config = await loadConfig(root);
|
|
724
|
+
const gates = parseGates(only);
|
|
725
|
+
if (writing) return freeze(root, config, gates);
|
|
726
|
+
const results = await runCheck(root, config, gates, await readBaseline(resolve(root, config.baseline)));
|
|
727
|
+
console.log(formatResults(results));
|
|
728
|
+
return results.every((result) => result.passed) ? 0 : 1;
|
|
729
|
+
}
|
|
730
|
+
/** `vp run <script> -- <options>` forwards the `--` as is: one right after the command only separates its options. */
|
|
731
|
+
function withoutSeparator(argv) {
|
|
732
|
+
return argv[1] === "--" ? [argv[0], ...argv.slice(2)] : argv;
|
|
733
|
+
}
|
|
734
|
+
function parseCommand(argv) {
|
|
735
|
+
return parseArgs({
|
|
736
|
+
args: withoutSeparator(argv),
|
|
737
|
+
allowPositionals: true,
|
|
738
|
+
options: {
|
|
739
|
+
only: { type: "string" },
|
|
740
|
+
"write-baseline": { type: "boolean" },
|
|
741
|
+
mutate: {
|
|
742
|
+
type: "string",
|
|
743
|
+
multiple: true
|
|
744
|
+
},
|
|
745
|
+
help: {
|
|
746
|
+
type: "boolean",
|
|
747
|
+
short: "h"
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
function misuse(message) {
|
|
753
|
+
console.error(`${message}\n\n${USAGE}`);
|
|
754
|
+
return 2;
|
|
755
|
+
}
|
|
756
|
+
/** Runs a command in the project at `root` and returns the exit code: 0 passed, 1 a gate failed, 2 misuse. */
|
|
757
|
+
async function main(argv, root = process.cwd()) {
|
|
758
|
+
const { positionals, values } = parseCommand(argv);
|
|
759
|
+
const [command, extra] = positionals;
|
|
760
|
+
if (values.help) {
|
|
761
|
+
console.log(USAGE);
|
|
762
|
+
return 0;
|
|
763
|
+
}
|
|
764
|
+
if (extra !== void 0) return misuse(`unexpected argument: ${extra}`);
|
|
765
|
+
if (command === "check") return check(root, values.only, values["write-baseline"]);
|
|
766
|
+
if (command === "mutation") return runMutation(root, await loadConfig(root), values.mutate ?? []);
|
|
767
|
+
return misuse(command ? `unknown command: ${command}` : "missing command");
|
|
768
|
+
}
|
|
769
|
+
if (import.meta.main) main(process.argv.slice(2)).then((code) => process.exit(code), (error) => {
|
|
770
|
+
console.error(`jsq: ${error instanceof Error ? error.message : String(error)}`);
|
|
771
|
+
process.exit(2);
|
|
772
|
+
});
|
|
773
|
+
export { main, parseGates };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { join, posix } from "node:path";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { glob } from "tinyglobby";
|
|
5
|
+
// src/sandbox.ts
|
|
6
|
+
const STRING_OR_COMMENT = /("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
|
|
7
|
+
const STRING_OR_TRAILING_COMMA = /("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g;
|
|
8
|
+
/** Parses a tsconfig file: JSON with comments and trailing commas, without TypeScript's API. */
|
|
9
|
+
function parseJsonc(text) {
|
|
10
|
+
const json = text.replace(STRING_OR_COMMENT, (_, string) => string ?? "").replace(STRING_OR_TRAILING_COMMA, (_, string, closing) => string ?? closing);
|
|
11
|
+
return JSON.parse(json);
|
|
12
|
+
}
|
|
13
|
+
/** Whether a path written in the sandbox file `file` resolves out of the sandbox. */
|
|
14
|
+
function leavesSandbox(file, reference) {
|
|
15
|
+
const path = posix.join(posix.dirname(file), reference);
|
|
16
|
+
return path === ".." || path.startsWith("../");
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Rewrites the paths of a tsconfig file copied into Stryker's sandbox, `<root>/.stryker-tmp/sandbox-…`, that point
|
|
20
|
+
* out of it (`"extends": "../../tsconfig.base.json"` in a monorepo package): two levels more reach the original
|
|
21
|
+
* target. Same rewrite as Stryker's own, which needs TypeScript's API. `file` is relative to the sandbox. Returns
|
|
22
|
+
* undefined when nothing changes.
|
|
23
|
+
*/
|
|
24
|
+
function rewriteTsconfig(config, file) {
|
|
25
|
+
const rewrite = (reference) => typeof reference === "string" && leavesSandbox(file, reference) ? `../../${reference}` : reference;
|
|
26
|
+
const rewritten = { ...config };
|
|
27
|
+
for (const key of [
|
|
28
|
+
"extends",
|
|
29
|
+
"include",
|
|
30
|
+
"exclude",
|
|
31
|
+
"files"
|
|
32
|
+
]) {
|
|
33
|
+
const value = config[key];
|
|
34
|
+
if (value !== void 0) rewritten[key] = Array.isArray(value) ? value.map(rewrite) : rewrite(value);
|
|
35
|
+
}
|
|
36
|
+
if (Array.isArray(config.references)) rewritten.references = config.references.map((reference) => ({
|
|
37
|
+
...reference,
|
|
38
|
+
path: rewrite(reference.path)
|
|
39
|
+
}));
|
|
40
|
+
return isDeepStrictEqual(rewritten, config) ? void 0 : rewritten;
|
|
41
|
+
}
|
|
42
|
+
/** Rewrites, in place, the tsconfig files of the sandbox whose paths point out of it. */
|
|
43
|
+
async function rewriteSandboxTsconfigs(sandbox) {
|
|
44
|
+
const files = await glob("**/tsconfig*.json", {
|
|
45
|
+
cwd: sandbox,
|
|
46
|
+
ignore: ["**/node_modules/**"]
|
|
47
|
+
});
|
|
48
|
+
await Promise.all(files.map(async (file) => {
|
|
49
|
+
const path = join(sandbox, file);
|
|
50
|
+
const config = rewriteTsconfig(parseJsonc(await readFile(path, "utf8")), file);
|
|
51
|
+
if (config) await writeFile(path, JSON.stringify(config, null, 2));
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
// src/sandbox-build.ts
|
|
55
|
+
await rewriteSandboxTsconfigs(process.cwd());
|
|
56
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adrien-chinour/js-quality",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Advanced quality gates for JS/TS projects: cognitive complexity, CRAP, duplication, mutation.",
|
|
5
|
+
"license": "0BSD",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/adrien-chinour/js-quality.git"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"jsq": "dist/cli.mjs"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@stryker-mutator/core": "10.1.1",
|
|
22
|
+
"@stryker-mutator/vitest-runner": "10.1.1",
|
|
23
|
+
"eslint-plugin-sonarjs": "4.2.2",
|
|
24
|
+
"jscpd": "5.4.3",
|
|
25
|
+
"oxc-parser": "0.158.0",
|
|
26
|
+
"oxlint": "1.91.0",
|
|
27
|
+
"tinyglobby": "0.2.17"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "24.19.2",
|
|
31
|
+
"@vitest/coverage-v8": "5.1.0",
|
|
32
|
+
"vite-plus": "1.5.0",
|
|
33
|
+
"vitest": "5.1.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"vitest": ">=5.1.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependenciesMeta": {
|
|
39
|
+
"vitest": {
|
|
40
|
+
"optional": true
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"devEngines": {
|
|
44
|
+
"packageManager": {
|
|
45
|
+
"name": "pnpm",
|
|
46
|
+
"version": "12.18.0",
|
|
47
|
+
"onFail": "download"
|
|
48
|
+
},
|
|
49
|
+
"runtime": {
|
|
50
|
+
"name": "node",
|
|
51
|
+
"version": "24"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "vp pack",
|
|
56
|
+
"qa": "vp check --deny-warnings && vp test run --coverage && node src/cli.ts check",
|
|
57
|
+
"mutation": "node src/cli.ts mutation"
|
|
58
|
+
}
|
|
6
59
|
}
|