包文件→ .shtukbase/packages/keer-style/checks/stylelib.ts
checks/stylelib.ts
131 行, 6.4 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Shared scanner of the keer-style checks. The working directory is the project root.
- // It reads the style files of the project (CSS, HTML, TSX/JSX/TS/JS, Vue, Svelte) and gives each check the parts
- // where style values live: CSS declarations, <style> blocks and style="…" attributes in HTML, string literals in code.
- // Skipped: pages laid by other packages (they keep their own style), hidden folders (.git, .shtukbase …), node_modules and build folders, files marked `@tokens` in their
- // first lines (a file of values), paths from `ignore:` of /design/keer-style.md, and any line with `keer-style: allow`.
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
- import { extname, join } from 'node:path';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- export type Kind = 'css' | 'html' | 'code';
- export type Part = { file: string; line: number; text: string };
- export type Finding = string;
- const EXT: Record<string, Kind> = {
- '.css': 'css', '.scss': 'css', '.less': 'css', '.pcss': 'css',
- '.html': 'html', '.htm': 'html', '.vue': 'html', '.svelte': 'html',
- '.tsx': 'code', '.jsx': 'code', '.ts': 'code', '.js': 'code', '.mjs': 'code',
- };
- const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'out', 'coverage', 'vendor', 'target']);
- export const CONFIG = 'design/keer-style.md';
- export const ALLOW = 'keer-style: allow';
- /** Paths (or folder prefixes) from `ignore:` of the style page; `*` matches any run of characters. */
- function ignores(root: string): RegExp[] {
- const page = join(root, CONFIG);
- if (!existsSync(page)) return [];
- const raw = readPage(page).fm.ignore;
- const list = Array.isArray(raw) ? raw.map(String) : [];
- return list.map((g) => {
- const clean = g.replace(/^\/+/, '');
- const re = clean.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*');
- return new RegExp(`^${re}${clean.endsWith('/') ? '' : '(/|$)'}`);
- });
- }
- /** Pages that other packages laid (from .shtukbase/packages.lock): they keep their own style and are not checked. */
- export function foreignPages(root: string, own = 'keer-style'): Set<string> {
- const lock = join(root, '.shtukbase', 'packages.lock');
- const out = new Set<string>();
- if (!existsSync(lock)) return out;
- let pkg = '';
- for (const line of readFileSync(lock, 'utf8').split('\n')) {
- const p = line.match(/^ ([\w.-]+):\s*$/);
- if (p) { pkg = p[1]; continue; }
- const page = line.match(/^ ("?)([^":]+)\1:\s*\{/);
- if (page && pkg !== own) out.add(page[2]);
- }
- return out;
- }
- /** Style files of the project, relative paths with forward slashes. */
- export function styleFiles(root = process.cwd()): { file: string; kind: Kind; text: string }[] {
- const skip = ignores(root);
- const foreign = foreignPages(root);
- const out: { file: string; kind: Kind; text: string }[] = [];
- const visit = (rel: string) => {
- for (const name of readdirSync(join(root, rel)).sort()) {
- const r = rel ? `${rel}/${name}` : name;
- const st = statSync(join(root, r));
- if (st.isDirectory()) {
- if (name.startsWith('.') || SKIP_DIRS.has(name)) continue;
- visit(r);
- continue;
- }
- const kind = EXT[extname(name).toLowerCase()];
- if (!kind || name.endsWith('.d.ts') || foreign.has(r) || skip.some((re) => re.test(r))) continue;
- const text = readFileSync(join(root, r), 'utf8');
- if (text.slice(0, 600).includes('@tokens')) continue;
- out.push({ file: r, kind, text });
- }
- };
- visit('');
- return out;
- }
- /** Keeps only the characters of the given ranges; the rest becomes spaces, newlines stay (line numbers hold). */
- function keep(text: string, ranges: [number, number][]): string {
- const chars = text.split('').map((c) => (c === '\n' ? '\n' : ' '));
- for (const [a, b] of ranges) {
- for (let i = a; i < b; i++) chars[i] = text[i];
- if (b < chars.length && chars[b] !== '\n') chars[b] = ';'; // the closing quote ends any declaration
- }
- return chars.join('');
- }
- function stripCssComments(text: string): string {
- return text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
- }
- /** The text of a file reduced to where style values are written. */
- export function styleText(kind: Kind, text: string): string {
- if (kind === 'css') return stripCssComments(text);
- if (kind === 'html') {
- const ranges: [number, number][] = [];
- for (const m of text.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)) ranges.push([m.index! + m[0].indexOf(m[1]), m.index! + m[0].indexOf(m[1]) + m[1].length]);
- for (const m of text.matchAll(/\b(?:style|class|className)\s*=\s*(["'])([\s\S]*?)\1/g)) ranges.push([m.index! + m[0].length - 1 - m[2].length, m.index! + m[0].length - 1]);
- return stripCssComments(keep(text, ranges));
- }
- // code: string literals only (Tailwind classes, inline styles); comments are dropped first
- const noComments = text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:"'`\\])\/\/[^\n]*/g, (m, p) => p + ' '.repeat(m.length - p.length));
- const ranges: [number, number][] = [];
- for (const m of noComments.matchAll(/(["'`])((?:\\.|(?!\1)[^\\\n])*)\1/g)) ranges.push([m.index! + 1, m.index! + 1 + m[2].length]);
- return keep(noComments, ranges);
- }
- /** CSS declarations `prop: value` in a reduced text: property, value, line of the property. */
- export function* declarations(text: string): Generator<{ prop: string; value: string; line: number }> {
- for (const m of text.matchAll(/(?<![\w-])(-{0,2}[a-zA-Z][\w-]*)\s*:\s*([^;{}"']+?)\s*(?=[;}"']|$)/gm)) {
- const line = text.slice(0, m.index!).split('\n').length;
- yield { prop: m[1].toLowerCase(), value: m[2], line };
- }
- }
- /** Class-like tokens (Tailwind) in a reduced text, with their line. */
- export function* classTokens(text: string): Generator<{ token: string; line: number }> {
- const lines = text.split('\n');
- for (let i = 0; i < lines.length; i++)
- for (const m of lines[i].matchAll(/[^\s"'`;]+/g)) yield { token: m[0], line: i + 1 };
- }
- export function allowed(source: string, line: number): boolean {
- return (source.split('\n')[line - 1] ?? '').includes(ALLOW);
- }
- /** Runs a check over the style files: prints findings, exit 1 when any. */
- export function run(check: (f: { file: string; kind: Kind; text: string; reduced: string }) => Finding[]): void {
- const out: Finding[] = [];
- for (const f of styleFiles()) out.push(...check({ ...f, reduced: styleText(f.kind, f.text) }));
- if (out.length) console.log(out.join('\n'));
- process.exitCode = out.length ? 1 : 0;
- }