slopscan.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. #!/usr/bin/env node
  2. /**
  3. * slopscan.mjs — AI-slop design linter, zero dependencies, read-only
  4. * ponytail: regex tokenization over CSS blocks, no full parser needed for these rules
  5. */
  6. import { readFileSync, statSync, readdirSync } from 'node:fs';
  7. import { join, extname, resolve } from 'node:path';
  8. const SCAN_EXTS = new Set(['.css','.scss','.html','.jsx','.tsx','.vue','.svelte','.astro','.js','.mjs','.ts']);
  9. // Pure-JS files get only JS-relevant rules — CSS-block heuristics false-positive on JS object literals
  10. const PURE_JS_EXTS = new Set(['.js','.mjs','.ts']);
  11. const SKIP_DIRS = new Set(['node_modules','dist','build','.git','.next','out']);
  12. // ── Color helpers ─────────────────────────────────────────────────────────────
  13. function rgbToHsl(r, g, b) {
  14. r /= 255; g /= 255; b /= 255;
  15. const max = Math.max(r, g, b), min = Math.min(r, g, b);
  16. let h = 0, s = 0;
  17. const l = (max + min) / 2;
  18. if (max !== min) {
  19. const d = max - min;
  20. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  21. if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
  22. else if (max === g) h = ((b - r) / d + 2) / 6;
  23. else h = ((r - g) / d + 4) / 6;
  24. }
  25. return { h: h * 360, s, l, _rgb: { r, g, b } };
  26. }
  27. /** Returns {h, s, l, isOklch?, C?} or null */
  28. function parseColor(tok) {
  29. tok = tok.trim().replace(/,$/, '');
  30. // oklch(L C H [/ alpha])
  31. let m = tok.match(/^oklch\(\s*([\d.]+%?)\s+([\d.]+)\s+([\d.]+)/i);
  32. if (m) {
  33. const L = parseFloat(m[1]) / (m[1].endsWith('%') ? 100 : 1);
  34. const C = parseFloat(m[2]);
  35. const H = parseFloat(m[3]);
  36. return { h: H, s: C > 0 ? 1 : 0, l: L, isOklch: true, C };
  37. }
  38. // hsl/hsla
  39. m = tok.match(/^hsla?\(\s*([\d.]+)(?:deg)?\s*[,\s]\s*([\d.]+)%?\s*[,\s]\s*([\d.]+)%?/i);
  40. if (m) return { h: parseFloat(m[1]), s: parseFloat(m[2]) / 100, l: parseFloat(m[3]) / 100 };
  41. // rgb/rgba
  42. m = tok.match(/^rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)/i);
  43. if (m) return rgbToHsl(+m[1], +m[2], +m[3]);
  44. // #rrggbbaa / #rrggbb / #rgb / #rgba
  45. m = tok.match(/^#([0-9a-f]{3,8})$/i);
  46. if (m) {
  47. let h = m[1];
  48. if (h.length === 3 || h.length === 4) h = h.split('').map(c => c + c).join('').slice(0, 6);
  49. if (h.length > 6) h = h.slice(0, 6);
  50. if (h.length !== 6) return null;
  51. return rgbToHsl(parseInt(h.slice(0,2),16), parseInt(h.slice(2,4),16), parseInt(h.slice(4,6),16));
  52. }
  53. return null;
  54. }
  55. function isGray(c) {
  56. if (!c) return true;
  57. // ponytail: oklch chroma < 0.03 = achromatic; HSL saturation < 0.05
  58. if (c.isOklch) return (c.C ?? 0) < 0.03;
  59. return c.s < 0.05;
  60. }
  61. // Extract all color tokens from a gradient string
  62. function extractGradientColors(str) {
  63. const re = /(#[0-9a-f]{3,8}|(?:oklch|rgba?|hsla?)\s*\([^)]+\))/gi;
  64. const colors = [];
  65. let m;
  66. while ((m = re.exec(str)) !== null) {
  67. const c = parseColor(m[1]);
  68. if (c) colors.push(c);
  69. }
  70. return colors;
  71. }
  72. // ── Line number helper ────────────────────────────────────────────────────────
  73. function makeLineAt(text) {
  74. // ponytail: binary search over precomputed newline positions
  75. const starts = [0];
  76. for (let i = 0; i < text.length; i++) if (text[i] === '\n') starts.push(i + 1);
  77. return pos => {
  78. let lo = 0, hi = starts.length - 1;
  79. while (lo < hi) {
  80. const mid = (lo + hi + 1) >> 1;
  81. if (starts[mid] <= pos) lo = mid; else hi = mid - 1;
  82. }
  83. return lo + 1;
  84. };
  85. }
  86. // ── CSS block extractor ───────────────────────────────────────────────────────
  87. /**
  88. * Extracts leaf CSS rule blocks (those with no nested { }).
  89. * Returns [{selector, body, startLine}]
  90. */
  91. function extractCSSBlocks(text) {
  92. const blocks = [];
  93. const lineAt = makeLineAt(text);
  94. const stack = []; // {selector, bodyStart}
  95. let i = 0, selectorStart = 0;
  96. while (i < text.length) {
  97. // Skip block comments
  98. if (text[i] === '/' && text[i+1] === '*') {
  99. const end = text.indexOf('*/', i + 2);
  100. i = end === -1 ? text.length : end + 2;
  101. continue;
  102. }
  103. // Skip strings
  104. if (text[i] === '"' || text[i] === "'") {
  105. const q = text[i++];
  106. while (i < text.length && text[i] !== q) { if (text[i] === '\\') i++; i++; }
  107. i++;
  108. continue;
  109. }
  110. if (text[i] === '{') {
  111. const sel = text.slice(selectorStart, i).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
  112. stack.push({ selector: sel, bodyStart: i + 1, startLine: lineAt(i + 1) });
  113. selectorStart = i + 1;
  114. i++;
  115. continue;
  116. }
  117. if (text[i] === '}') {
  118. const frame = stack.pop();
  119. if (frame) {
  120. const body = text.slice(frame.bodyStart, i);
  121. if (!/{/.test(body)) { // leaf block
  122. const fullSel = [...stack.map(f => f.selector), frame.selector].filter(Boolean).join(' ');
  123. blocks.push({ selector: fullSel || frame.selector, body, startLine: frame.startLine });
  124. }
  125. }
  126. selectorStart = i + 1;
  127. i++;
  128. continue;
  129. }
  130. i++;
  131. }
  132. return blocks;
  133. }
  134. // ── Suppression parser ────────────────────────────────────────────────────────
  135. function parseSuppressions(text) {
  136. const lineAt = makeLineAt(text);
  137. const suppressions = new Map();
  138. const patterns = [
  139. /\/\*\s*auteur-allow:\s*(\w+)\s*--\s*([\s\S]*?)\*\//g,
  140. /\/\/\s*auteur-allow:\s*(\w+)\s*--(.*)/gm,
  141. /<!--\s*auteur-allow:\s*(\w+)\s*--\s*(.*?)-->/g,
  142. ];
  143. for (const re of patterns) {
  144. let m;
  145. while ((m = re.exec(text)) !== null) {
  146. const ruleId = m[1].trim();
  147. const reason = m[2].trim();
  148. const reasonOk = reason.replace(/\s+/g, '').length >= 10;
  149. const line = lineAt(m.index);
  150. if (!suppressions.has(ruleId)) suppressions.set(ruleId, { line, reasonOk, reason });
  151. }
  152. }
  153. return suppressions;
  154. }
  155. // ── FAIL rules ────────────────────────────────────────────────────────────────
  156. function checkFontDefaultSlop(text, findings) {
  157. const lineAt = makeLineAt(text);
  158. // CSS font-family declarations
  159. const re = /font-family\s*:\s*([^\n;{}]+)/gi;
  160. let m;
  161. while ((m = re.exec(text)) !== null) {
  162. const first = m[1].split(',')[0].trim().replace(/['"]/g, '').trim();
  163. if (/^inter$/i.test(first) || /^space grotesk$/i.test(first)) {
  164. findings.push({ rule: 'FONT_DEFAULT_SLOP', severity: 'fail', line: lineAt(m.index),
  165. detail: `font-family first family is "${first}"` });
  166. }
  167. }
  168. // Tailwind fontFamily config: fontFamily: { key: ['Inter', ...] }
  169. const twRe = /fontFamily\s*:\s*\{[^}]*\}/gs;
  170. while ((m = twRe.exec(text)) !== null) {
  171. const block = m[0];
  172. const entryRe = /:\s*\[['"]([^'"]+)['"]/g;
  173. let em;
  174. while ((em = entryRe.exec(block)) !== null) {
  175. const first = em[1].trim();
  176. if (/^inter$/i.test(first) || /^space grotesk$/i.test(first)) {
  177. findings.push({ rule: 'FONT_DEFAULT_SLOP', severity: 'fail', line: lineAt(m.index),
  178. detail: `Tailwind fontFamily first entry is "${first}"` });
  179. }
  180. }
  181. }
  182. }
  183. function checkAiGradient(text, findings) {
  184. const lineAt = makeLineAt(text);
  185. const re = /(?:linear|radial|conic)-gradient\s*\(/gi;
  186. let m;
  187. while ((m = re.exec(text)) !== null) {
  188. // Extract balanced parens
  189. let depth = 0, j = m.index + m[0].length - 1;
  190. const start = j;
  191. while (j < text.length) {
  192. if (text[j] === '(') depth++;
  193. else if (text[j] === ')') { depth--; if (depth === 0) break; }
  194. j++;
  195. }
  196. const gradStr = text.slice(start, j + 1);
  197. const colors = extractGradientColors(gradStr);
  198. const aiColors = colors.filter(c => !isGray(c) && c.h >= 250 && c.h <= 290);
  199. if (aiColors.length >= 2) {
  200. findings.push({ rule: 'AI_GRADIENT', severity: 'fail', line: lineAt(m.index),
  201. detail: `${aiColors.length} gradient stops in hue 250–290 (purple-blue AI default)` });
  202. }
  203. }
  204. }
  205. function checkGradientText(blocks, findings) {
  206. const gradRe = /(?:linear|radial|conic)-gradient/i;
  207. const clipRe = /-webkit-background-clip\s*:\s*text|background-clip\s*:\s*text|-webkit-text-fill-color\s*:\s*transparent/i;
  208. for (const block of blocks) {
  209. if (gradRe.test(block.body) && clipRe.test(block.body)) {
  210. findings.push({ rule: 'GRADIENT_TEXT', severity: 'fail', line: block.startLine,
  211. detail: `gradient + background-clip:text (or -webkit-text-fill-color:transparent) in same block` });
  212. }
  213. }
  214. }
  215. function checkTransitionAll(text, findings) {
  216. const lineAt = makeLineAt(text);
  217. const re = /transition\s*:\s*all\b/gi;
  218. let m;
  219. while ((m = re.exec(text)) !== null) {
  220. findings.push({ rule: 'TRANSITION_ALL', severity: 'fail', line: lineAt(m.index),
  221. detail: `transition: all — use specific properties instead` });
  222. }
  223. }
  224. function checkRawScrollListener(text, findings) {
  225. const lineAt = makeLineAt(text);
  226. let m;
  227. const re = /addEventListener\s*\(\s*['"]scroll['"]/g;
  228. while ((m = re.exec(text)) !== null) {
  229. findings.push({ rule: 'RAW_SCROLL_LISTENER', severity: 'fail', line: lineAt(m.index),
  230. detail: `addEventListener('scroll') — use IntersectionObserver or animation-timeline` });
  231. }
  232. const re2 = /\bonscroll\s*=/g;
  233. while ((m = re2.exec(text)) !== null) {
  234. findings.push({ rule: 'RAW_SCROLL_LISTENER', severity: 'fail', line: lineAt(m.index),
  235. detail: `onscroll= attribute — use IntersectionObserver or animation-timeline` });
  236. }
  237. }
  238. // ── WARN rules ────────────────────────────────────────────────────────────────
  239. function checkGlassCard(blocks, findings) {
  240. for (const block of blocks) {
  241. if (!/card|tile|panel/i.test(block.selector)) continue;
  242. if (/backdrop-filter\s*:\s*blur\s*\(/i.test(block.body)) {
  243. findings.push({ rule: 'GLASS_CARD', severity: 'warn', line: block.startLine,
  244. detail: `backdrop-filter:blur() in "${block.selector.slice(0, 60)}"` });
  245. }
  246. }
  247. }
  248. function checkCardCloneGrid(blocks, findings) {
  249. const getTriple = body => {
  250. const get = prop => { const m = body.match(new RegExp(prop + '\\s*:\\s*([^;\\n]+)')); return m ? m[1].trim() : null; };
  251. const br = get('border-radius'), p = get('padding'), bs = get('box-shadow');
  252. return br && p && bs ? `${br}|${p}|${bs}` : null;
  253. };
  254. const seen = new Map();
  255. for (const block of blocks) {
  256. const key = getTriple(block.body);
  257. if (!key) continue;
  258. if (!seen.has(key)) seen.set(key, []);
  259. seen.get(key).push(block.startLine);
  260. }
  261. for (const [, lines] of seen) {
  262. if (lines.length >= 4) {
  263. findings.push({ rule: 'CARD_CLONE_GRID', severity: 'warn', line: lines[0],
  264. detail: `${lines.length} blocks share identical border-radius/padding/box-shadow (lines ${lines.join(', ')})` });
  265. }
  266. }
  267. }
  268. // Ban #16 is "em-dash-HEAVY sentences" — a density property, not the presence of the glyph.
  269. // Flagging every occurrence trains you to suppress the rule, which is how a linter loses its
  270. // authority; and the old remediation ("use &mdash;") renders the identical character, so
  271. // following it changed nothing the rule claimed to detect.
  272. const PROSE_EXT = new Set(['.html', '.htm', '.md', '.jsx', '.tsx', '.vue', '.svelte']);
  273. function checkEmDashCopy(text, ext, findings) {
  274. if (!PROSE_EXT.has(ext)) return;
  275. // Keep only what a visitor actually reads: no script/style, no comments, no <title>/<meta>.
  276. const prose = text
  277. .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  278. .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  279. .replace(/<title[\s\S]*?<\/title>/gi, ' ')
  280. .replace(/<meta[^>]*>/gi, ' ')
  281. // Headings, terms and captions are LABELS, not sentences. "-200m — The Blue" is a dash doing
  282. // exactly the job a dash should do, and counting it made the rule argue against good typography.
  283. .replace(/<(h[1-6]|dt|summary|figcaption|legend|caption|th)\b[\s\S]*?<\/\1>/gi, ' ')
  284. .replace(/<!--[\s\S]*?-->/g, ' ')
  285. .replace(/\/\*[\s\S]*?\*\//g, ' ')
  286. .replace(/(^|\s)\/\/[^\n]*/g, ' ')
  287. .replace(/<[^>]+>/g, ' ');
  288. // Entity-encoded dashes render the identical glyph. Counting only the literal character meant the
  289. // rule was defeated by `&mdash;` — the exact dodge the comment above says the old advice suffered
  290. // from. Decode first, then count.
  291. const decoded = prose
  292. .replace(/&mdash;|&#8212;|&#[xX]2014;/g, '—')
  293. .replace(/&ndash;|&#8211;|&#[xX]2013;/g, '–')
  294. .replace(/&hellip;|&#8230;/g, '…')
  295. .replace(/&nbsp;|&#160;/g, ' ');
  296. const dashes = (decoded.match(/—/g) || []).length;
  297. if (dashes < 3) return;
  298. const sentences = (decoded.match(/[.!?]["')\]]?(\s|$)/g) || []).length || 1;
  299. const words = (decoded.match(/\S+/g) || []).length || 1;
  300. const perSentence = dashes / sentences;
  301. const per100w = (dashes / words) * 100;
  302. // One criterion, because the ban is about the dash replacing sentence structure: if more than
  303. // half your sentences carry an em dash, it is structural. A per-100-words test looked reasonable
  304. // and flagged prose with one dash every four sentences, which is just writing.
  305. if (perSentence < 0.5) return;
  306. const lineAt = makeLineAt(text);
  307. const first = text.indexOf('—');
  308. findings.push({
  309. rule: 'EM_DASH_COPY', severity: 'warn', line: lineAt(first < 0 ? 0 : first),
  310. detail: `${dashes} em dashes across ${sentences} sentences / ${words} words of visible copy (${perSentence.toFixed(2)}/sentence, ${per100w.toFixed(1)} per 100 words) — the dash is doing the work sentence structure should. Rewrite the densest ones as full sentences; an occasional em dash is fine.`,
  311. });
  312. }
  313. function checkEyebrowEverywhere(blocks, findings) {
  314. const matched = [];
  315. for (const block of blocks) {
  316. if (!/text-transform\s*:\s*uppercase/i.test(block.body)) continue;
  317. const lsM = block.body.match(/letter-spacing\s*:\s*([\d.]+)(em|rem)/i);
  318. if (!lsM || parseFloat(lsM[1]) < 0.05) continue;
  319. const fsM = block.body.match(/font-size\s*:\s*([\d.]+)(rem|px|em)/i);
  320. if (!fsM) continue;
  321. const fs = parseFloat(fsM[1]), unit = fsM[2].toLowerCase();
  322. const fsRem = unit === 'px' ? fs / 16 : fs;
  323. if (fsRem > 0.875) continue;
  324. matched.push(block.startLine);
  325. }
  326. if (matched.length > 3) {
  327. findings.push({ rule: 'EYEBROW_EVERYWHERE', severity: 'warn', line: matched[0],
  328. detail: `${matched.length} blocks with text-transform:uppercase + letter-spacing≥0.05em + font-size≤0.875rem` });
  329. }
  330. }
  331. function checkCreamDefault(blocks, findings) {
  332. for (const block of blocks) {
  333. if (!/^(?::root|body|html)\b/i.test(block.selector.trim())) continue;
  334. const bgM = block.body.match(/background(?:-color)?\s*:\s*([^\n;]+)/i);
  335. if (!bgM) continue;
  336. const val = bgM[1].trim().split(/\s+/)[0];
  337. const c = parseColor(val);
  338. if (!c) continue;
  339. let inBand = false;
  340. if (c.isOklch) {
  341. inBand = c.l >= 0.84 && c.l <= 0.97 && (c.C ?? 0) < 0.06 && c.h >= 40 && c.h <= 100;
  342. } else {
  343. // ponytail: sRGB→OKLCH approximation via HSL; check lightness, small chroma gap, warm hue
  344. // max-min distance in [0,1] maps roughly to OKLCH chroma < 0.06 for near-white colors
  345. const rgb = c._rgb;
  346. if (!rgb) continue;
  347. const dRgb = Math.max(rgb.r, rgb.g, rgb.b) - Math.min(rgb.r, rgb.g, rgb.b);
  348. inBand = c.l >= 0.84 && c.l <= 0.97 && dRgb > 0.002 && dRgb < 0.08 && c.h >= 30 && c.h <= 110;
  349. }
  350. if (inBand) {
  351. findings.push({ rule: 'CREAM_DEFAULT', severity: 'warn', line: block.startLine,
  352. detail: `body/:root background "${val}" is in warm-cream default band` });
  353. }
  354. }
  355. }
  356. // ── Tier-1 motion / WebGL / audio rules ─────────────────────────────────────────
  357. function checkAutoplaySound(text, findings) {
  358. const lineAt = makeLineAt(text);
  359. const re = /<(audio|video)\b([^>]*)>/gi;
  360. let m;
  361. while ((m = re.exec(text)) !== null) {
  362. if (/\bautoplay\b/i.test(m[2]) && !/\bmuted\b/i.test(m[2])) {
  363. findings.push({ rule: 'AUTOPLAY_SOUND', severity: 'fail', line: lineAt(m.index),
  364. detail: `<${m[1].toLowerCase()} autoplay> without muted — sound must start on a user gesture` });
  365. }
  366. }
  367. }
  368. function checkVideoNoPoster(text, findings) {
  369. const lineAt = makeLineAt(text);
  370. const re = /<video\b([^>]*)>/gi;
  371. let m;
  372. while ((m = re.exec(text)) !== null) {
  373. if (!/\bposter\s*=/i.test(m[1])) {
  374. findings.push({ rule: 'VIDEO_NO_POSTER', severity: 'warn', line: lineAt(m.index),
  375. detail: `<video> without poster — blank hero until the clip decodes` });
  376. }
  377. }
  378. }
  379. function checkWebglNoReducedMotion(text, findings) {
  380. const lineAt = makeLineAt(text);
  381. const ctxRe = /new\s+THREE\.WebGLRenderer|getContext\s*\(\s*['"](?:webgl2?|webgpu)['"]|new\s+GPUDevice|new\s+OGLRenderer/;
  382. const cm = ctxRe.exec(text);
  383. if (!cm) return;
  384. if (!/prefers-reduced-motion/i.test(text)) {
  385. findings.push({ rule: 'WEBGL_NO_REDUCED_MOTION', severity: 'warn', line: lineAt(cm.index),
  386. detail: `WebGL/WebGPU scene with no prefers-reduced-motion branch — reduced-motion is an alternative art direction, not an afterthought` });
  387. }
  388. }
  389. function checkPointerNoRaf(text, findings) {
  390. const lineAt = makeLineAt(text);
  391. const pm = /addEventListener\s*\(\s*['"](?:pointermove|mousemove)['"]/.exec(text);
  392. if (!pm) return;
  393. if (!/requestAnimationFrame/.test(text)) {
  394. findings.push({ rule: 'POINTER_NO_RAF', severity: 'warn', line: lineAt(pm.index),
  395. detail: `pointermove/mousemove handler with no requestAnimationFrame — throttle DOM/uniform writes to rAF, never per-event` });
  396. }
  397. }
  398. // ── File scanner ──────────────────────────────────────────────────────────────
  399. function scanFile(filePath) {
  400. const text = readFileSync(filePath, 'utf8');
  401. const ext = extname(filePath).toLowerCase();
  402. const suppressions = parseSuppressions(text);
  403. const findings = [];
  404. const blocks = extractCSSBlocks(text);
  405. if (PURE_JS_EXTS.has(ext)) {
  406. checkTransitionAll(text, findings);
  407. checkRawScrollListener(text, findings);
  408. checkWebglNoReducedMotion(text, findings);
  409. checkPointerNoRaf(text, findings);
  410. } else {
  411. checkFontDefaultSlop(text, findings);
  412. checkAiGradient(text, findings);
  413. checkGradientText(blocks, findings);
  414. checkTransitionAll(text, findings);
  415. checkRawScrollListener(text, findings);
  416. checkGlassCard(blocks, findings);
  417. checkCardCloneGrid(blocks, findings);
  418. checkEmDashCopy(text, ext, findings);
  419. checkEyebrowEverywhere(blocks, findings);
  420. checkCreamDefault(blocks, findings);
  421. checkAutoplaySound(text, findings);
  422. checkVideoNoPoster(text, findings);
  423. checkWebglNoReducedMotion(text, findings);
  424. checkPointerNoRaf(text, findings);
  425. }
  426. const result = findings.map(f => {
  427. const sup = suppressions.get(f.rule);
  428. return { ...f, suppressed: !!(sup && sup.reasonOk) };
  429. });
  430. // Invalid suppressions: present but reason too short
  431. for (const [ruleId, sup] of suppressions) {
  432. if (!sup.reasonOk) {
  433. result.push({ rule: 'SUPPRESSION_NO_REASON', severity: 'warn', line: sup.line,
  434. detail: `auteur-allow: ${ruleId} — reason too short (need 10+ non-whitespace chars)`, suppressed: false });
  435. }
  436. }
  437. return { path: filePath, findings: result };
  438. }
  439. // ── File walker ───────────────────────────────────────────────────────────────
  440. function walk(entry) {
  441. const files = [];
  442. let stat;
  443. try { stat = statSync(entry); } catch { return files; }
  444. if (stat.isFile()) {
  445. if (SCAN_EXTS.has(extname(entry).toLowerCase())) files.push(entry);
  446. return files;
  447. }
  448. for (const name of readdirSync(entry)) {
  449. if (SKIP_DIRS.has(name)) continue;
  450. const full = join(entry, name);
  451. try {
  452. const s = statSync(full);
  453. if (s.isDirectory()) files.push(...walk(full));
  454. else if (SCAN_EXTS.has(extname(name).toLowerCase())) files.push(full);
  455. } catch { /* skip unreadable */ }
  456. }
  457. return files;
  458. }
  459. // ── Main ──────────────────────────────────────────────────────────────────────
  460. function main() {
  461. const argv = process.argv.slice(2);
  462. const jsonMode = argv.includes('--json');
  463. const target = argv.find(a => !a.startsWith('-'));
  464. if (!target) {
  465. process.stderr.write('Usage: node slopscan.mjs <dir-or-file> [--json]\n');
  466. process.exit(2);
  467. }
  468. const rootDir = resolve(target);
  469. const files = walk(rootDir);
  470. const fileResults = files.map(f => scanFile(f));
  471. let totalFails = 0, totalWarns = 0, totalSuppressed = 0;
  472. for (const fr of fileResults) {
  473. for (const f of fr.findings) {
  474. if (f.suppressed) totalSuppressed++;
  475. else if (f.severity === 'fail') totalFails++;
  476. else totalWarns++;
  477. }
  478. }
  479. if (jsonMode) {
  480. process.stdout.write(JSON.stringify({ files: fileResults, summary: { fails: totalFails, warns: totalWarns, suppressed: totalSuppressed } }, null, 2) + '\n');
  481. } else {
  482. for (const fr of fileResults) {
  483. if (!fr.findings.length) continue;
  484. const rel = fr.path.replace(rootDir, '').replace(/^[\\/]/, '');
  485. for (const f of fr.findings) {
  486. const tag = f.suppressed ? 'SKIP' : f.severity.toUpperCase();
  487. process.stdout.write(`${tag} ${f.rule} ${rel}:${f.line} — ${f.detail}\n`);
  488. }
  489. }
  490. process.stdout.write(`\nSummary: ${totalFails} fails, ${totalWarns} warns, ${totalSuppressed} suppressed\n`);
  491. }
  492. process.exit(totalFails > 0 ? 1 : 0);
  493. }
  494. main();