@rocss/sass-architecture 0.0.0-stage → 1.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/src/checker.js ADDED
@@ -0,0 +1,422 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
+ import selectorParser from 'postcss-selector-parser';
4
+ import { scan } from './scan.js';
5
+
6
+ export const LAYERS = ['tokens', 'primitives', 'behaviors', 'combinators', 'components', 'globals', 'bootstrap'];
7
+ export const FAMILIES = ['context', 'scope', 'state', 'part'];
8
+ // Spécification I12 : identifiants des canoniques ; tout autre combinator est une spécialisation.
9
+ const CANONICAL_FAMILIES = {
10
+ media: 'context', supports: 'context', container: 'context',
11
+ 'pseudo-class': 'state', attribute: 'state', ancestor: 'scope', 'pseudo-element': 'part',
12
+ };
13
+ // Spécification I15 : précédence des familles, de l'extérieur vers l'intérieur.
14
+ const FAMILY_RANK = Object.fromEntries(FAMILIES.map((family, rank) => [family, rank]));
15
+ // Spécification I21 : plafond de spécificité d'une signature (0,3,1), aligné sur `selector-max-specificity`.
16
+ const SPECIFICITY_CAP = [0, 3, 1];
17
+ const CANONICALS = new Set(Object.keys(CANONICAL_FAMILIES));
18
+
19
+ // Spécification §2 : couches que chaque couche PEUT consommer (hors elle-même).
20
+ const ALLOWED = {
21
+ tokens: [],
22
+ primitives: ['tokens'],
23
+ behaviors: ['tokens', 'primitives'],
24
+ combinators: ['tokens', 'primitives'],
25
+ components: ['tokens', 'primitives', 'behaviors', 'combinators'],
26
+ globals: ['tokens', 'primitives'],
27
+ bootstrap: ['tokens', 'primitives', 'combinators'],
28
+ };
29
+
30
+ const CONDITIONAL_AT_RULES = ['media', 'supports', 'container'];
31
+ const EMITTING_AT_RULES = [...CONDITIONAL_AT_RULES, 'keyframes', 'font-face', 'property', 'include'];
32
+ const GLOBAL_AT_RULES = ['keyframes', 'font-face', 'property'];
33
+ const BASES = ['', 'src', 'scss', 'styles', 'src/scss', 'src/styles'];
34
+
35
+ /**
36
+ * @typedef {Object} Violation
37
+ * @property {string} rule Invariant de la spécification (I1, I8…)
38
+ * @property {'error'|'warning'} severity
39
+ * @property {string} file Chemin relatif au répertoire analysé
40
+ * @property {number} line
41
+ * @property {string} layer
42
+ * @property {string} message
43
+ */
44
+
45
+ function isDirectory(path) {
46
+ try {
47
+ return statSync(path).isDirectory();
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ function listScss(dir) {
54
+ const files = [];
55
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
56
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
57
+ const path = join(dir, entry.name);
58
+ if (entry.isDirectory()) files.push(...listScss(path));
59
+ else if (entry.name.endsWith('.scss')) files.push(path);
60
+ }
61
+ return files.sort();
62
+ }
63
+
64
+ /** Détecte un dossier par couche (convention) ; `overrides` associe une couche à un chemin. */
65
+ export function discoverLayers(root, overrides = {}) {
66
+ const dirs = {};
67
+ for (const layer of LAYERS) {
68
+ if (overrides[layer]) {
69
+ dirs[layer] = resolve(root, overrides[layer]);
70
+ continue;
71
+ }
72
+ for (const base of BASES) {
73
+ const candidate = resolve(root, base, layer);
74
+ if (isDirectory(candidate)) {
75
+ dirs[layer] = candidate;
76
+ break;
77
+ }
78
+ }
79
+ }
80
+ return dirs;
81
+ }
82
+
83
+ const normalize = name => name.replaceAll('_', '-');
84
+ const inside = (dir, path) => path === dir || path.startsWith(dir + sep);
85
+
86
+ function layerOfPath(layerDirs, path) {
87
+ let best = null;
88
+ for (const [layer, dir] of Object.entries(layerDirs)) {
89
+ if (inside(dir, path) && (!best || dir.length > layerDirs[best].length)) best = layer;
90
+ }
91
+ return best;
92
+ }
93
+
94
+ /** Fichiers SCSS de chaque couche ; une couche imbriquée dans une autre lui est retirée. */
95
+ export function sourceFiles(layerDirs) {
96
+ return Object.entries(layerDirs).flatMap(([layer, dir]) => listScss(dir)
97
+ .filter(file => layerOfPath(layerDirs, file) === layer).map(file => ({ file, layer })));
98
+ }
99
+
100
+ const inNthArgument = node => {
101
+ for (let parent = node.parent; parent; parent = parent.parent) {
102
+ if (parent.type === 'pseudo' && /^:nth-/.test(parent.value)) return true;
103
+ }
104
+ return false;
105
+ };
106
+
107
+ /** Problèmes I19 d'un sélecteur ; les interpolations sont neutralisées, une syntaxe inconnue est ignorée. */
108
+ function selectorProblems(selector, layer, family) {
109
+ const problems = new Set();
110
+ try {
111
+ selectorParser(root => {
112
+ root.walk(node => {
113
+ if (node.type === 'class' || node.type === 'id') {
114
+ problems.add('Sélecteur sémantique (classe ou id) interdit');
115
+ } else if (node.type === 'combinator' && layer !== 'bootstrap' && !inNthArgument(node)) {
116
+ const descendant = !node.value.trim();
117
+ if (!descendant || family !== 'scope') problems.add('Combinateur CSS interdit hors forme canonique scope');
118
+ }
119
+ });
120
+ }).processSync(selector.replace(/#\{[^}]*\}/g, '__interpolation__'));
121
+ } catch {
122
+ // Pas un sélecteur (ex. étape de @keyframes) : rien à contrôler.
123
+ }
124
+ return problems;
125
+ }
126
+
127
+ const addSpecificity = (a, b) => a.map((value, i) => value + b[i]);
128
+ const exceeds = (specificity, cap) => {
129
+ for (let i = 0; i < 3; i++) if (specificity[i] !== cap[i]) return specificity[i] > cap[i];
130
+ return false;
131
+ };
132
+
133
+ /** Barème I21 de l'ancêtre d'un scope ; null si l'argument n'est pas un littéral reconnu. */
134
+ function ancestorSpecificity(argument) {
135
+ const root = /^(html|body|:root|\.[A-Za-z][\w-]*)\[/.exec(argument ?? '')?.[1];
136
+ if (!root) return null;
137
+ return root === 'html' || root === 'body' ? [0, 1, 1] : [0, 2, 0];
138
+ }
139
+
140
+ const firstLiteral = text => /\(\s*(["'])(.*?)\1/.exec(text)?.[2] ?? null;
141
+
142
+ /**
143
+ * Vérifie l'architecture en couches (invariants I1, I2, I3, I7–I16, I19, I21, I22, I23).
144
+ * L'analyse est statique et heuristique : elle ne prouve pas la conformité complète.
145
+ * @param {string} root
146
+ * @param {{ layers?: Record<string,string> }} [options]
147
+ * @returns {{ layers: Record<string,string>, files: number, violations: Violation[] }}
148
+ */
149
+ export function checkArchitecture(root, options = {}) {
150
+ root = resolve(root);
151
+ const layerDirs = discoverLayers(root, options.layers);
152
+ const violations = [];
153
+ const cache = new Map();
154
+
155
+ const layerOf = path => layerOfPath(layerDirs, path);
156
+ const familyOf = path => {
157
+ const dir = layerDirs.combinators;
158
+ if (!dir || !inside(dir, path)) return null;
159
+ const first = relative(dir, path).split(sep)[0];
160
+ return FAMILIES.includes(first) ? first : null;
161
+ };
162
+
163
+ const load = file => {
164
+ if (!cache.has(file)) {
165
+ let nodes = [];
166
+ let error = null;
167
+ try {
168
+ nodes = scan(readFileSync(file, 'utf8'));
169
+ } catch (e) {
170
+ error = { line: e.line ?? 1, message: e.reason ?? e.message };
171
+ }
172
+ const imports = [];
173
+ for (const node of nodes) {
174
+ if (node.atRule !== 'use' && node.atRule !== 'forward') continue;
175
+ const spec = /^@(?:use|forward)\s+(["'])(.+?)\1/.exec(node.raw)?.[2];
176
+ if (spec) imports.push({ spec, line: node.line });
177
+ }
178
+ cache.set(file, { nodes, imports, error });
179
+ }
180
+ return cache.get(file);
181
+ };
182
+
183
+ const resolveFile = abs => {
184
+ const name = basename(abs);
185
+ const candidates = [`${abs}.scss`, join(dirname(abs), `_${name}.scss`), join(abs, '_index.scss'),
186
+ join(abs, 'index.scss'), abs];
187
+ return candidates.find(path => path.endsWith('.scss') && existsSync(path) && !isDirectory(path)) ?? null;
188
+ };
189
+
190
+ /** @returns {{ layer: string, family: string|null, file: string|null, external?: boolean }|null} */
191
+ const resolveImport = (spec, from) => {
192
+ if (spec.startsWith('sass:')) return null;
193
+ const pkg = /^(?:pkg:)?@rocss\/sass(?:\/([\w-]+))?$/.exec(spec);
194
+ if (pkg) return { layer: 'combinators', family: pkg[1] ?? '*', file: null, external: true };
195
+ const bare = !spec.startsWith('.') && !spec.startsWith('/');
196
+ // Sass résout d'abord relativement au fichier courant, puis via les loadPaths.
197
+ const candidates = bare
198
+ ? [dirname(from), root, ...Object.values(layerDirs).map(dirname)].map(base => resolve(base, spec))
199
+ : [resolve(dirname(from), spec)];
200
+ // Un import qui ne désigne aucun fichier existant est ignoré : le compilateur le signalera.
201
+ const found = candidates.find(abs => resolveFile(abs) && layerOf(resolveFile(abs)));
202
+ if (!found) return null;
203
+ const file = resolveFile(found);
204
+ const path = file;
205
+ return { layer: layerOf(path), family: familyOf(path), file };
206
+ };
207
+
208
+ /** Familles de combinators atteintes depuis un fichier, dépendances transitives comprises. */
209
+ const reachableFamilies = (file, seen = new Set()) => {
210
+ const families = new Set();
211
+ if (!file || seen.has(file)) return families;
212
+ seen.add(file);
213
+ if (familyOf(file)) families.add(familyOf(file));
214
+ for (const { spec } of load(file).imports) {
215
+ const target = resolveImport(spec, file);
216
+ if (target?.layer !== 'combinators') continue;
217
+ if (target.family) families.add(target.family);
218
+ for (const family of reachableFamilies(target.file, seen)) families.add(family);
219
+ }
220
+ return families;
221
+ };
222
+
223
+ // Première passe : noms de mixins par couche (I10, I14, I16) et définitions de canoniques (I12).
224
+ const files = sourceFiles(layerDirs);
225
+ const mixinLayers = new Map();
226
+ const canonicalDefs = new Map();
227
+ const mixinFamilies = new Map();
228
+ const scopeAncestors = new Map();
229
+ for (const { file, layer } of files) {
230
+ for (const node of load(file).nodes) {
231
+ const name = node.atRule === 'mixin' && /^@mixin\s+([\w-]+)/.exec(node.text)?.[1];
232
+ if (!name) continue;
233
+ const key = normalize(name);
234
+ mixinLayers.set(key, new Set([...(mixinLayers.get(key) ?? []), layer]));
235
+ if (layer === 'combinators' && familyOf(file)) {
236
+ mixinFamilies.set(key, new Set([...(mixinFamilies.get(key) ?? []), familyOf(file)]));
237
+ }
238
+ if (layer === 'combinators' && familyOf(file) === 'scope') {
239
+ const ancestor = load(file).nodes.find(n => n.atRule === 'include' && n.ancestors.includes(node)
240
+ && /^@include\s+(?:[\w-]+\.)?ancestor\b/.test(n.text));
241
+ if (ancestor) scopeAncestors.set(key, firstLiteral(ancestor.raw));
242
+ }
243
+ if (layer === 'combinators' && CANONICALS.has(key)) {
244
+ canonicalDefs.set(key, [...(canonicalDefs.get(key) ?? []), { file, line: node.line, family: familyOf(file) }]);
245
+ }
246
+ }
247
+ }
248
+
249
+ for (const { file, layer } of files) {
250
+ const rel = relative(root, file);
251
+ const { nodes, imports, error } = load(file);
252
+ const report = (rule, line, message, severity = 'error') =>
253
+ violations.push({ rule, severity, file: rel, line, layer, message });
254
+
255
+ if (error) report('SYNTAX', error.line, `Syntaxe SCSS invalide : ${error.message}`);
256
+
257
+ for (const { spec, line } of imports) {
258
+ const target = resolveImport(spec, file);
259
+ if (!target) continue;
260
+ const to = target.layer;
261
+ if (to === layer) {
262
+ if (layer === 'tokens' && basename(file) !== '_index.scss' && target.file !== file) {
263
+ report('I7', line, `Les modules de tokens ne doivent pas dépendre les uns des autres ("${spec}").`);
264
+ }
265
+ if (layer === 'combinators' && target.family && familyOf(file) && target.family !== familyOf(file)) {
266
+ report('I13', line, `Un combinator ne peut consommer que le canonique de sa propre famille ("${spec}").`);
267
+ }
268
+ continue;
269
+ }
270
+ if (to === 'globals' || to === 'bootstrap') {
271
+ report('I1', line, `Aucune couche ne doit consommer ${to} ("${spec}").`);
272
+ } else if (!ALLOWED[layer].includes(to)) {
273
+ report('I1', line, `La couche ${layer} ne peut pas consommer ${to} ("${spec}").`);
274
+ } else if (layer === 'bootstrap' && to === 'combinators') {
275
+ const families = target.external
276
+ ? new Set([target.family])
277
+ : new Set([...(target.family ? [target.family] : []), ...reachableFamilies(target.file)]);
278
+ if (target.family === null && !target.file) families.add('*');
279
+ const extra = [...families].filter(family => family !== 'context');
280
+ if (extra.length > 0) {
281
+ report('I23', line, `bootstrap ne peut importer que la famille context ; "${spec}" expose ${extra.join(', ')}.`);
282
+ }
283
+ }
284
+ }
285
+
286
+ const callable = node => node.ancestors.some(a => a.atRule === 'mixin' || a.atRule === 'function');
287
+ const isRule = node => node.kind === 'block' && !node.atRule && !node.text.endsWith(':');
288
+ const isDeclaration = node => node.kind === 'statement' && !node.atRule && /^[^$@][^:]*:/.test(node.text);
289
+
290
+ for (const node of nodes) {
291
+ const { text, line, atRule } = node;
292
+
293
+ if (/!\s*important/.test(text) && layer !== 'bootstrap') {
294
+ report('I22', line, '!important est réservé au reset de bootstrap.');
295
+ }
296
+
297
+ if (isDeclaration(node) && /^--[\w-]+\s*:/.test(text) && layer !== 'bootstrap' && layer !== 'globals') {
298
+ report('I3', line, "L'affectation d'une custom property de token relève de bootstrap.", 'warning');
299
+ }
300
+
301
+ // Émission autonome (I2).
302
+ if (layer !== 'bootstrap' && !callable(node)) {
303
+ const emitting = n => isRule(n) || isDeclaration(n) || EMITTING_AT_RULES.includes(n.atRule);
304
+ const permitted = layer === 'globals' && GLOBAL_AT_RULES.includes(atRule);
305
+ const insidePermitted = layer === 'globals' && node.ancestors.some(a => GLOBAL_AT_RULES.includes(a.atRule));
306
+ // Seule l'émission la plus externe est signalée.
307
+ if (emitting(node) && !permitted && !insidePermitted && !node.ancestors.some(emitting)) {
308
+ report('I2', line, `La couche ${layer} ne doit rien émettre d'autonome.`);
309
+ }
310
+ }
311
+
312
+ // Sélecteurs (I19), analysés avec postcss-selector-parser.
313
+ if (isRule(node)) {
314
+ for (const problem of selectorProblems(text, layer, familyOf(file))) {
315
+ report('I19', line, `${problem} : "${text}".`);
316
+ }
317
+ }
318
+
319
+ if (layer === 'primitives') {
320
+ if (atRule === 'mixin') report('I8', line, 'primitives ne contient que des @function.');
321
+ if (atRule === 'content') report('I8', line, 'primitives ne contient pas de @content.');
322
+ if (isRule(node) || isDeclaration(node)) report('I8', line, 'primitives ne produit aucun sélecteur ni propriété.');
323
+ }
324
+
325
+ if (layer === 'behaviors' && callable(node)) {
326
+ if (atRule === 'content') report('I9', line, 'Un behavior est output-only : @content interdit.');
327
+ if (CONDITIONAL_AT_RULES.includes(atRule)) report('I9', line, `Un behavior ne contient pas @${atRule}.`);
328
+ if (isRule(node)) report('I9', line, `Un behavior ne contient aucun sélecteur : "${text}".`);
329
+ if (/&/.test(text) && atRule !== 'include' && !isDeclaration(node)) report('I9', line, 'Un behavior ne référence pas &.');
330
+ }
331
+
332
+ if (atRule === 'include' && (layer === 'behaviors' || layer === 'combinators')) {
333
+ const name = /^@include\s+(?:[\w-]+\.)?([\w-]+)/.exec(text)?.[1];
334
+ const defined = name && mixinLayers.get(normalize(name));
335
+ if (layer === 'behaviors' && defined?.has('behaviors')) {
336
+ report('I10', line, `Un behavior n'inclut aucun autre behavior ("${name}").`);
337
+ }
338
+ if (layer === 'combinators' && (defined?.has('behaviors') || defined?.has('components'))) {
339
+ report('I16', line, `Un combinator ne consomme ni behavior ni component ("${name}").`);
340
+ }
341
+ // I14 : une spécialisation ne consomme que des canoniques, jamais une autre spécialisation.
342
+ const owner = node.ancestors.findLast(a => a.atRule === 'mixin');
343
+ const ownerName = owner && /^@mixin\s+([\w-]+)/.exec(owner.text)?.[1];
344
+ if (layer === 'combinators' && ownerName && !CANONICALS.has(normalize(ownerName))
345
+ && defined?.has('combinators') && !CANONICALS.has(normalize(name))) {
346
+ report('I14', line, `La spécialisation "${ownerName}" ne consomme pas une autre spécialisation ("${name}").`);
347
+ }
348
+ }
349
+ }
350
+
351
+ // I15 : précédence des familles dans les @include imbriqués ; un seul scope et un seul part.
352
+ const familyOfInclude = node => {
353
+ if (node.atRule !== 'include') return null;
354
+ const name = /^@include\s+(?:[\w-]+\.)?([\w-]+)/.exec(node.text)?.[1];
355
+ const families = name && mixinFamilies.get(normalize(name));
356
+ return families?.size === 1 ? [...families][0] : null;
357
+ };
358
+ const includeName = node => /^@include\s+(?:[\w-]+\.)?([\w-]+)/.exec(node.text)?.[1];
359
+ /** Spécificité d'une signature (I21) ; null si un scope n'a pas d'ancêtre littéral. */
360
+ const signatureSpecificity = chain => {
361
+ const scope = chain.find(n => familyOfInclude(n) === 'scope');
362
+ let total = [0, 1, 0];
363
+ if (scope) {
364
+ const name = normalize(includeName(scope));
365
+ const ancestor = ancestorSpecificity(name === 'ancestor' ? firstLiteral(scope.raw) : scopeAncestors.get(name));
366
+ if (!ancestor) return null;
367
+ total = ancestor;
368
+ }
369
+ for (const n of chain) {
370
+ if (familyOfInclude(n) === 'state') total = addSpecificity(total, [0, 1, 0]);
371
+ if (familyOfInclude(n) === 'part') total = addSpecificity(total, [0, 0, 1]);
372
+ }
373
+ return total;
374
+ };
375
+ for (const node of nodes) {
376
+ const inner = familyOfInclude(node);
377
+ if (!inner) continue;
378
+ const chain = [...node.ancestors.filter(familyOfInclude), node];
379
+ const specificity = signatureSpecificity(chain);
380
+ const outerSpecificity = chain.length > 1 ? signatureSpecificity(chain.slice(0, -1)) : null;
381
+ if (specificity && exceeds(specificity, SPECIFICITY_CAP) && !(outerSpecificity && exceeds(outerSpecificity, SPECIFICITY_CAP))) {
382
+ report('I21', node.line, `La signature atteint la spécificité (${specificity}), au-delà du plafond (${SPECIFICITY_CAP}).`);
383
+ }
384
+ for (const outer of node.ancestors.map(familyOfInclude).filter(Boolean)) {
385
+ if (FAMILY_RANK[inner] < FAMILY_RANK[outer]) {
386
+ report('I15', node.line, `La famille ${inner} ne peut pas être imbriquée dans ${outer} (context → scope → state → part).`);
387
+ break;
388
+ } else if (inner === outer && (inner === 'scope' || inner === 'part')) {
389
+ report('I15', node.line, `Une signature ne contient qu'un seul ${inner}.`);
390
+ break;
391
+ }
392
+ }
393
+ }
394
+
395
+ if (layer === 'combinators') {
396
+ for (const mixin of nodes.filter(node => node.atRule === 'mixin')) {
397
+ const hasContent = nodes.some(node => node.atRule === 'content' && node.ancestors.includes(mixin));
398
+ if (!hasContent) report('I11', mixin.line, `Le combinator "${mixin.text.replace(/\s*\(.*$/, '')}" doit transmettre @content.`);
399
+ }
400
+ }
401
+ }
402
+
403
+ // I12 : un seul canonique par identifiant, dans la famille de son mécanisme.
404
+ for (const [id, defs] of canonicalDefs) {
405
+ defs.forEach(({ file, line, family }, index) => {
406
+ const add = message => violations.push({
407
+ rule: 'I12', severity: 'error', file: relative(root, file), line, layer: 'combinators', message,
408
+ });
409
+ if (index > 0) add(`Le canonique "${id}" est défini plusieurs fois ; aucun autre combinator ne doit porter ce nom.`);
410
+ if (family && family !== CANONICAL_FAMILIES[id]) {
411
+ add(`Le canonique "${id}" appartient à la famille ${CANONICAL_FAMILIES[id]}, pas à ${family}.`);
412
+ }
413
+ });
414
+ }
415
+
416
+ violations.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.rule.localeCompare(b.rule));
417
+ return {
418
+ layers: Object.fromEntries(Object.entries(layerDirs).map(([layer, dir]) => [layer, relative(root, dir) || '.'])),
419
+ files: files.length,
420
+ violations,
421
+ };
422
+ }
package/src/cli.js ADDED
@@ -0,0 +1,104 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { parseArgs } from 'node:util';
3
+ import process from 'node:process';
4
+ import { checkArchitecture, LAYERS } from './checker.js';
5
+ import { checkEmission } from './emission.js';
6
+
7
+ // Version affichée : lue depuis le manifeste du package, jamais codée en dur.
8
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
9
+
10
+ const HELP = `
11
+ ROCS Sass Architecture Checker — v${version}
12
+ Vérifie statiquement les invariants de l'architecture Sass de référence.
13
+
14
+ Usage:
15
+ sass-architecture check [dir] [options]
16
+
17
+ Options:
18
+ --dir <path> Répertoire du projet (défaut: .)
19
+ --layer <nom=chemin> Chemin d'une couche (répétable). Couches : ${LAYERS.join(', ')}
20
+ --format <format> text (défaut) ou json
21
+ --compile Compile aussi les modules avec sass pour vérifier I2 (sass requis)
22
+ --strict Exit 1 sur les warnings également
23
+ --help Afficher cette aide
24
+
25
+ Convention : un dossier par couche, à la racine ou sous src/, scss/ ou styles/.
26
+ Les combinators sont répartis en sous-dossiers context/, scope/, state/, part/.
27
+ Codes de sortie : 0 conforme, 1 violation, 2 usage invalide.
28
+
29
+ L'analyse est heuristique : elle ne prouve pas la conformité complète.
30
+ `;
31
+
32
+ export function formatText(result) {
33
+ const lines = ['', 'ROCS Sass Architecture — rapport', ''];
34
+ const found = Object.entries(result.layers).map(([layer, dir]) => `${layer}=${dir}`);
35
+ lines.push(`Couches : ${found.join(', ') || 'aucune'}`, `Fichiers analysés : ${result.files}`, '');
36
+ for (const v of result.violations) {
37
+ lines.push(`${v.severity === 'error' ? '❌' : '⚠️ '} [${v.rule}] ${v.file}:${v.line} — ${v.message}`);
38
+ }
39
+ const errors = result.violations.filter(v => v.severity === 'error').length;
40
+ const warnings = result.violations.length - errors;
41
+ lines.push('', `Erreurs : ${errors} Avertissements : ${warnings}`, '');
42
+ return lines.join('\n');
43
+ }
44
+
45
+ /** @returns {Promise<number>} code de sortie */
46
+ export async function runCli(argv = process.argv.slice(2), out = process.stdout) {
47
+ let parsed;
48
+ try {
49
+ parsed = parseArgs({
50
+ args: argv,
51
+ options: {
52
+ dir: { type: 'string' },
53
+ layer: { type: 'string', multiple: true },
54
+ format: { type: 'string', default: 'text' },
55
+ compile: { type: 'boolean', default: false },
56
+ strict: { type: 'boolean', default: false },
57
+ help: { type: 'boolean', default: false },
58
+ },
59
+ allowPositionals: true,
60
+ });
61
+ } catch (error) {
62
+ process.stderr.write(`${error.message}\n`);
63
+ return 2;
64
+ }
65
+ const { values, positionals } = parsed;
66
+ if (values.help) {
67
+ out.write(HELP);
68
+ return 0;
69
+ }
70
+ const [command = 'check', maybeDir] = positionals;
71
+ if (command !== 'check' || !['text', 'json'].includes(values.format)) {
72
+ process.stderr.write(`Usage invalide.${HELP}`);
73
+ return 2;
74
+ }
75
+ const layers = {};
76
+ for (const entry of values.layer ?? []) {
77
+ const [name, path] = entry.split('=');
78
+ if (!LAYERS.includes(name) || !path) {
79
+ process.stderr.write(`--layer attend <nom=chemin> avec nom parmi ${LAYERS.join(', ')} : "${entry}".\n`);
80
+ return 2;
81
+ }
82
+ layers[name] = path;
83
+ }
84
+ const directory = values.dir ?? maybeDir ?? '.';
85
+ const result = checkArchitecture(directory, { layers });
86
+ if (Object.keys(result.layers).length === 0) {
87
+ process.stderr.write('Aucune couche détectée. Utilisez des dossiers nommés par couche ou --layer.\n');
88
+ return 2;
89
+ }
90
+ if (values.compile) {
91
+ try {
92
+ const reported = new Set(result.violations.filter(v => v.rule === 'I2').map(v => v.file));
93
+ const compiled = await checkEmission(directory, { layers });
94
+ result.violations.push(...compiled.filter(v => v.rule !== 'I2' || !reported.has(v.file)));
95
+ result.violations.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.rule.localeCompare(b.rule));
96
+ } catch (error) {
97
+ process.stderr.write(`${error.message}\n`);
98
+ return 2;
99
+ }
100
+ }
101
+ out.write(values.format === 'json' ? `${JSON.stringify(result, null, 2)}\n` : formatText(result));
102
+ const failing = result.violations.some(v => v.severity === 'error' || values.strict);
103
+ return failing ? 1 : 0;
104
+ }
@@ -0,0 +1,65 @@
1
+ import { createRequire } from 'node:module';
2
+ import { dirname, join, relative, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import postcss from 'postcss';
5
+ import { discoverLayers, sourceFiles } from './checker.js';
6
+
7
+ // Couches de la chaîne : le CSS compilé d'un module doit être vide (I2).
8
+ const CHAIN = ['tokens', 'primitives', 'behaviors', 'combinators', 'components'];
9
+ // `globals` n'émet que des déclarations non sélectives (I2).
10
+ const GLOBAL_AT_RULES = ['keyframes', 'font-face', 'property'];
11
+
12
+ async function loadSass(root) {
13
+ const candidates = [
14
+ async () => import(pathToFileURL(createRequire(join(root, 'noop.js')).resolve('sass')).href),
15
+ async () => import('sass'),
16
+ ];
17
+ for (const candidate of candidates) {
18
+ try {
19
+ const module = await candidate();
20
+ return module.compile ? module : module.default;
21
+ } catch {
22
+ // Essayer le compilateur suivant.
23
+ }
24
+ }
25
+ throw new Error('Le compilateur "sass" (>= 1.71.0) est introuvable : installez-le pour utiliser --compile.');
26
+ }
27
+
28
+ /**
29
+ * Compile chaque module des couches non terminales et vérifie qu'il n'émet rien (I2).
30
+ * Contrairement à l'analyse statique, ce contrôle est sémantique, mais il exige que
31
+ * les dépendances externes du projet soient résolubles.
32
+ * @param {string} root
33
+ * @param {{ layers?: Record<string,string> }} [options]
34
+ * @returns {Promise<import('./checker.js').Violation[]>}
35
+ */
36
+ export async function checkEmission(root, options = {}) {
37
+ root = resolve(root);
38
+ const sass = await loadSass(root);
39
+ const layerDirs = discoverLayers(root, options.layers);
40
+ const loadPaths = [root, ...Object.values(layerDirs).map(dirname)];
41
+ const importers = sass.NodePackageImporter ? [new sass.NodePackageImporter(root)] : [];
42
+ const violations = [];
43
+
44
+ for (const { file, layer } of sourceFiles(layerDirs)) {
45
+ if (layer === 'bootstrap') continue;
46
+ const report = (rule, severity, message) =>
47
+ violations.push({ rule, severity, file: relative(root, file), line: 1, layer, message });
48
+ let css;
49
+ try {
50
+ ({ css } = sass.compile(file, { loadPaths, importers, charset: false, logger: sass.Logger.silent }));
51
+ } catch (error) {
52
+ report('COMPILE', 'warning', `Compilation impossible : ${String(error.sassMessage ?? error.message).split('\n')[0]}`);
53
+ continue;
54
+ }
55
+ if (!css.trim()) continue;
56
+ if (layer === 'globals') {
57
+ const stray = postcss.parse(css).nodes.find(node => node.type !== 'comment'
58
+ && !(node.type === 'atrule' && GLOBAL_AT_RULES.includes(node.name)));
59
+ if (stray) report('I2', 'error', 'globals ne doit émettre que @keyframes, @font-face et @property (compilation).');
60
+ } else if (CHAIN.includes(layer)) {
61
+ report('I2', 'error', `La couche ${layer} émet du CSS au chargement (compilation).`);
62
+ }
63
+ }
64
+ return violations;
65
+ }
package/src/scan.js ADDED
@@ -0,0 +1,58 @@
1
+ import scss from 'postcss-scss';
2
+
3
+ /**
4
+ * @typedef {Object} ScanNode
5
+ * @property {'block'|'statement'} kind
6
+ * @property {string} text Texte normalisé, contenu des chaînes masqué
7
+ * @property {string} raw Même texte, chaînes conservées
8
+ * @property {number} line
9
+ * @property {string|null} atRule Nom de l'at-rule sans « @ »
10
+ * @property {ScanNode[]} ancestors Blocs englobants, du plus externe au plus interne
11
+ */
12
+
13
+ const maskStrings = text => text.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, match => match[0] + ' '.repeat(match.length - 2) + match[0]);
14
+
15
+ function describe(node) {
16
+ switch (node.type) {
17
+ case 'atrule':
18
+ return { raw: `@${node.name} ${node.params}`.trim(), atRule: node.name };
19
+ case 'rule':
20
+ return { raw: node.selector, atRule: null };
21
+ case 'decl': {
22
+ const value = node.value ?? '';
23
+ const important = node.important ? ' !important' : '';
24
+ return { raw: `${node.prop}${node.raws.between ?? ':'}${value}${important}`.trim(), atRule: null };
25
+ }
26
+ default:
27
+ return null;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Aplatit l'AST postcss-scss en nœuds ordonnés avec leurs blocs englobants.
33
+ * @throws {Error} erreur de syntaxe SCSS (`line` et `reason` renseignés)
34
+ * @returns {ScanNode[]}
35
+ */
36
+ export function scan(source) {
37
+ const root = scss.parse(source);
38
+ const nodes = [];
39
+ const visit = (parent, ancestors) => {
40
+ parent.each(child => {
41
+ const info = describe(child);
42
+ if (!info) return;
43
+ const block = Array.isArray(child.nodes);
44
+ const node = {
45
+ kind: block ? 'block' : 'statement',
46
+ text: maskStrings(info.raw),
47
+ raw: info.raw,
48
+ line: child.source?.start?.line ?? 0,
49
+ atRule: info.atRule,
50
+ ancestors,
51
+ };
52
+ nodes.push(node);
53
+ if (block) visit(child, [...ancestors, node]);
54
+ });
55
+ };
56
+ visit(root, []);
57
+ return nodes;
58
+ }