@rickycourtes/designrail 0.0.0-stage → 0.2.1

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/model.js ADDED
@@ -0,0 +1,128 @@
1
+ // The project as a design system: which files hold tokens, what each token
2
+ // resolves to, and every hardcoded design value used outside the token files.
3
+ import { literals, COLOR_PROP, lengthCategory, normValue } from './values.js';
4
+ import { JS_EXT } from './sources.js';
5
+
6
+ const ROOTISH = /^(:root|html|:host|\[data-[\w-]+(=["']?[\w-]+["']?)?\]|\.[\w-]*theme[\w-]*|body)(\s*,\s*(:root|html|:host|\[data-[\w-]+(=["']?[\w-]+["']?)?\]|\.[\w-]*theme[\w-]*|body))*$|^(:root|html)(\[[^\]]+\]|\.[\w-]+)+$/;
7
+ const KEYWORD = /^(inherit|initial|unset|revert|none|auto|0|transparent|currentcolor|normal)$/i;
8
+
9
+ export function isTokenFile(file, cfg) {
10
+ if (cfg.tokens.some((t) => file.path === t || file.path.endsWith('/' + t))) return true;
11
+ let defs = 0, all = 0;
12
+ for (const r of file.rules) {
13
+ if (r.origin === 'js-object' || r.origin === 'tailwind') continue;
14
+ for (const d of r.decls) { all++; if (d.prop.startsWith('--') && ROOTISH.test(r.sel ?? '')) defs++; }
15
+ }
16
+ return defs >= 8 && defs / all >= 0.8;
17
+ }
18
+
19
+ // A declaration that carries design (colour, spacing, radius, type, shadow).
20
+ export function designSlot(prop) {
21
+ if (prop.startsWith('--')) return null;
22
+ const cat = lengthCategory(prop);
23
+ if (cat === 'space' || cat === 'radius' || cat === 'font-size') return cat;
24
+ if (COLOR_PROP.test(prop) && prop !== 'background-image') return 'color';
25
+ if (prop === 'font-family') return 'font';
26
+ if (prop === 'box-shadow') return 'shadow';
27
+ return null;
28
+ }
29
+
30
+ export function buildModel(project) {
31
+ const { files, cfg } = project;
32
+ const tokenFiles = new Set(files.filter((f) => isTokenFile(f, cfg)).map((f) => f.path));
33
+ const defs = new Map();
34
+ const uses = new Map();
35
+ const runtime = new Set(cfg.runtimeTokens);
36
+ const occ = [];
37
+ const decls = [];
38
+ let slots = 0, tokenized = 0;
39
+ const slotsBy = {};
40
+
41
+ for (const f of files) {
42
+ const inTokens = tokenFiles.has(f.path);
43
+ for (const name of f.runtime) runtime.add(name);
44
+ // A var() in a plain JS file may be a string in a test or a tool: it
45
+ // counts as a read (unused) but never fails unresolved or primitive-direct.
46
+ const js = JS_EXT.test(f.path);
47
+ for (const [name, line, fallback] of f.uses) {
48
+ if (!uses.has(name)) uses.set(name, []);
49
+ uses.get(name).push({ file: f.path, line, inTokens, js, fallback: Boolean(fallback) });
50
+ }
51
+ for (const r of f.rules) {
52
+ if (r.sel === '@font-face') continue;
53
+ for (const d of r.decls) {
54
+ if (d.prop.startsWith('--')) {
55
+ if (!defs.has(d.prop)) defs.set(d.prop, []);
56
+ defs.get(d.prop).push({ value: d.value, file: f.path, line: d.line, sel: r.sel, media: r.media, inTokens });
57
+ }
58
+ if (inTokens) continue;
59
+ if (/designrail-ignore|\bmeasured\b/.test(d.value)) continue;
60
+ decls.push({ file: f.path, rule: r, d });
61
+ const slot = designSlot(d.prop);
62
+ const lits = literals(d.prop, d.value);
63
+ if (slot && !KEYWORD.test(d.value.trim())) {
64
+ slots++;
65
+ slotsBy[slot] = (slotsBy[slot] ?? 0) + 1;
66
+ const own = lits.filter((l) => slotOf(l) === slot);
67
+ if (!own.length && /var\(/.test(d.value)) tokenized++;
68
+ }
69
+ for (const lit of lits) occ.push({ file: f.path, line: d.line, sel: r.sel, media: r.media, origin: r.origin, prop: d.prop, value: d.value, vstart: d.vstart, lit });
70
+ }
71
+ }
72
+ }
73
+
74
+ // The foundation underneath: its tokens resolve the project's var()s, its
75
+ // parts' reads count as reads, and none of it is audited as project code.
76
+ for (const f of project.foundation?.files ?? []) {
77
+ const inTokens = /tokens\.css$/.test(f.path);
78
+ for (const [name, line] of f.uses) {
79
+ if (!uses.has(name)) uses.set(name, []);
80
+ uses.get(name).push({ file: f.path, line, inTokens, external: true });
81
+ }
82
+ for (const r of f.rules) for (const d of r.decls) if (d.prop.startsWith('--')) {
83
+ if (!defs.has(d.prop)) defs.set(d.prop, []);
84
+ defs.get(d.prop).push({ value: d.value, file: f.path, line: d.line, sel: r.sel, media: r.media, inTokens, external: true });
85
+ }
86
+ }
87
+
88
+ const resolve = (name, seen = new Set()) => {
89
+ if (seen.has(name)) return { value: null, chain: [...seen, name], cycle: true };
90
+ seen.add(name);
91
+ const d = pickDef(defs.get(name));
92
+ if (!d) return { value: null, chain: [...seen], missing: name };
93
+ const m = /^var\(\s*(--[\w-]+)\s*(?:,\s*([^)]*))?\)$/.exec(d.value.trim());
94
+ if (m) {
95
+ const r = resolve(m[1], seen);
96
+ return r.value == null && m[2] ? { value: m[2].trim(), chain: r.chain } : r;
97
+ }
98
+ // Substitute inner var()s for a computed-ish value (color-mix, calc).
99
+ const value = d.value.replace(/var\(\s*(--[\w-]+)\s*(?:,[^)]*)?\)/g, (all, n) => resolve(n, new Set(seen)).value ?? all);
100
+ return { value, chain: [...seen], def: d };
101
+ };
102
+
103
+ return { ...project, tokenFiles, defs, uses, runtime, occ, decls, slots, slotsBy, tokenized, resolve };
104
+ }
105
+
106
+ // The definition that wins on :root: the project's own over the foundation's
107
+ // (its tokens are layered, the project's are not), a token file's over a
108
+ // part's local knob.
109
+ export function pickDef(list = []) {
110
+ const order = [(x) => !x.external && x.inTokens && /^(:root|html)$/.test(x.sel ?? ''), (x) => !x.external && x.inTokens,
111
+ (x) => x.inTokens && /^(:root|html)$/.test(x.sel ?? ''), (x) => x.inTokens, () => true];
112
+ for (const ok of order) { const d = list.find(ok); if (d) return d; }
113
+ return undefined;
114
+ }
115
+
116
+ export function slotOf(lit) {
117
+ if (lit.kind === 'color') return 'color';
118
+ if (lit.kind === 'length') return lit.cat;
119
+ if (lit.kind === 'font') return 'font';
120
+ if (lit.kind === 'shadow') return 'shadow';
121
+ return lit.cat;
122
+ }
123
+
124
+ // A rule's declarations as one comparable set (custom props and inline sources left out).
125
+ export function declSet(rule, colorMap = null) {
126
+ const norm = (v) => { const n = normValue(v); return colorMap ? n.replace(/#[0-9a-f]{6,8}\b/g, (h) => colorMap.get(h) ?? h) : n; };
127
+ return [...new Set(rule.decls.filter((d) => !d.prop.startsWith('--')).map((d) => `${d.prop}:${norm(d.value)}`))].sort();
128
+ }
package/src/project.js ADDED
@@ -0,0 +1,180 @@
1
+ // Load a project: config, the file list, and every file analysed, from a
2
+ // stat-keyed cache when nothing changed and in worker threads when lots did.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import { Worker } from 'node:worker_threads';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { analyze, ALL_EXT } from './sources.js';
9
+
10
+ const PKG = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
11
+ export const VERSION = PKG.version;
12
+ export const OWN_KIT = fileURLToPath(new URL('../kit', import.meta.url));
13
+ const CACHE_VERSION = `${VERSION}-1`;
14
+
15
+ // Never project source, whatever the config says.
16
+ const ALWAYS = ['.git', '.designrail', 'node_modules'];
17
+
18
+ export const DEFAULT_CONFIG = {
19
+ include: ['.'],
20
+ exclude: ['node_modules', 'dist', 'build', 'out', 'coverage', '.git', '.next', '.nuxt', '.svelte-kit', '.output', '.vercel', '.turbo', '.cache', '.designrail', 'vendor', '**/*.min.*', '**/*.map'],
21
+ // Token files: where the design system's custom properties are defined.
22
+ tokens: ['tokens/primitives.css', 'tokens/semantic.css'],
23
+ // Where `add` copies kit parts.
24
+ parts: 'ui',
25
+ grid: 4,
26
+ // ΔE OK below which two colours count as the same colour.
27
+ colorTolerance: 0.01,
28
+ // Lengths this close (px) snap to a token in `fix --snap`.
29
+ snap: 1,
30
+ // Outside token files, read semantic tokens only (primitive scales listed in allowPrimitives pass).
31
+ semanticOnly: true,
32
+ allowPrimitives: ['--space-', '--radius-', '--font-size-'],
33
+ // Custom properties set from JS at runtime (resolve without a CSS definition).
34
+ runtimeTokens: [],
35
+ rules: { hardcoded: 'error', unresolved: 'error', 'primitive-direct': 'warn', 'duplicate-block': 'error', unused: 'warn', 'tracked-caps': 'warn', contract: 'warn', 'part-restyle': 'warn' },
36
+ maxFileBytes: 1_500_000,
37
+ };
38
+
39
+ export function loadConfig(root) {
40
+ const file = path.join(root, 'designrail.config.json');
41
+ let user = {};
42
+ if (fs.existsSync(file)) {
43
+ try { user = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new Error(`designrail.config.json: ${e.message}`); }
44
+ }
45
+ const cfg = { ...DEFAULT_CONFIG, ...user, rules: { ...DEFAULT_CONFIG.rules, ...(user.rules ?? {}) } };
46
+ cfg.exists = fs.existsSync(file);
47
+ return cfg;
48
+ }
49
+
50
+ // Merge keys into designrail.config.json (created when missing).
51
+ export function saveConfig(root, patch) {
52
+ const file = path.join(root, 'designrail.config.json');
53
+ let cur = {};
54
+ try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { /* new */ }
55
+ fs.writeFileSync(file, JSON.stringify({ ...cur, ...patch }, null, 2) + '\n');
56
+ }
57
+
58
+ function globRe(g) {
59
+ return new RegExp('(^|/)' + g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*\//g, '(.*/)?').replace(/\*\*/g, '.*').replace(/\*/g, '[^/]*') + '($|/)');
60
+ }
61
+
62
+ function gitignored(root) {
63
+ const f = path.join(root, '.gitignore');
64
+ if (!fs.existsSync(f)) return [];
65
+ return fs.readFileSync(f, 'utf8').split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
66
+ .map((l) => l.replace(/^\//, '').replace(/\/$/, ''));
67
+ }
68
+
69
+ export function listFiles(root, cfg) {
70
+ const ex = [...new Set([...ALWAYS, ...cfg.exclude, ...gitignored(root)])].map(globRe);
71
+ const out = [];
72
+ const walk = (rel) => {
73
+ let ents;
74
+ try { ents = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { return; }
75
+ for (const d of ents) {
76
+ const r = rel ? `${rel}/${d.name}` : d.name;
77
+ if (ex.some((re) => re.test(r))) continue;
78
+ if (d.isDirectory()) walk(r);
79
+ else if (d.isFile() && ALL_EXT.test(d.name)) out.push(r);
80
+ }
81
+ };
82
+ for (const inc of cfg.include) walk(inc === '.' ? '' : inc.replace(/\/$/, ''));
83
+ return [...new Set(out)].sort();
84
+ }
85
+
86
+ function readCache(root) {
87
+ try {
88
+ const c = JSON.parse(fs.readFileSync(path.join(root, '.designrail/cache.json'), 'utf8'));
89
+ return c.v === CACHE_VERSION ? c.files : {};
90
+ } catch { return {}; }
91
+ }
92
+
93
+ function writeCache(root, files) {
94
+ try {
95
+ fs.mkdirSync(path.join(root, '.designrail'), { recursive: true });
96
+ const gi = path.join(root, '.designrail/.gitignore');
97
+ if (!fs.existsSync(gi)) fs.writeFileSync(gi, '*\n');
98
+ fs.writeFileSync(path.join(root, '.designrail/cache.json'), JSON.stringify({ v: CACHE_VERSION, files }));
99
+ } catch { /* a read-only tree still scans */ }
100
+ }
101
+
102
+ async function inWorkers(root, jobs) {
103
+ const n = Math.min(Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1), Math.ceil(jobs.length / 48), 8);
104
+ const chunks = Array.from({ length: n }, (_, i) => jobs.filter((_, j) => j % n === i));
105
+ const url = new URL('./worker.js', import.meta.url);
106
+ const parts = await Promise.all(chunks.map((files) => new Promise((resolve, reject) => {
107
+ const w = new Worker(url, { workerData: { root, files } });
108
+ w.once('message', resolve);
109
+ w.once('error', reject);
110
+ })));
111
+ return parts.flat();
112
+ }
113
+
114
+ // → { root, cfg, files: [{ path, ...analysis }], stats }
115
+ // The names the foundation is installed under: the published package, and
116
+ // a plain git or local install.
117
+ export const PACKAGE_NAMES = [PKG.name, 'designrail'];
118
+
119
+ // The foundation a project builds on: the installed package when there is
120
+ // one (node_modules/@rickycourtes/designrail), else this copy of Designrail
121
+ // when the project says it depends on it. Its files are read for their tokens
122
+ // and the tokens its parts read, never audited as the project's own code.
123
+ export function findFoundation(root, cfg) {
124
+ let declared = false;
125
+ try {
126
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
127
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies };
128
+ declared = PACKAGE_NAMES.some((n) => deps[n]);
129
+ } catch { /* no package.json */ }
130
+ for (const name of PACKAGE_NAMES) {
131
+ const installed = path.join(root, 'node_modules', ...name.split('/'));
132
+ if (!fs.existsSync(path.join(installed, 'kit', 'foundation.css'))) continue;
133
+ const version = JSON.parse(fs.readFileSync(path.join(installed, 'package.json'), 'utf8')).version;
134
+ return { dir: path.join(installed, 'kit'), version, installed: true, name };
135
+ }
136
+ if (declared || cfg.foundation) return { dir: OWN_KIT, version: VERSION, installed: false, name: PKG.name };
137
+ return null;
138
+ }
139
+
140
+ function foundationFiles(f) {
141
+ const out = [];
142
+ const walk = (rel) => {
143
+ for (const d of fs.readdirSync(path.join(f.dir, rel), { withFileTypes: true })) {
144
+ const r = rel ? `${rel}/${d.name}` : d.name;
145
+ if (d.isDirectory()) walk(r);
146
+ else if (/\.css$/.test(d.name) && d.name !== 'foundation.css') out.push({ path: `designrail:${r}`, ...analyze(r, fs.readFileSync(path.join(f.dir, r), 'utf8')) });
147
+ }
148
+ };
149
+ walk('');
150
+ return out;
151
+ }
152
+
153
+ export async function loadProject(root, { cache = true, only = null, read = null } = {}) {
154
+ root = path.resolve(root);
155
+ const cfg = loadConfig(root);
156
+ const t0 = performance.now();
157
+ const list = only ?? listFiles(root, cfg);
158
+ const old = cache && !read ? readCache(root) : {};
159
+ const fresh = {};
160
+ const todo = [];
161
+ const files = [];
162
+ for (const rel of list) {
163
+ if (read) { const text = read(rel); if (text != null) files.push({ path: rel, ...analyze(rel, text) }); continue; }
164
+ let st;
165
+ try { st = fs.statSync(path.join(root, rel)); } catch { continue; }
166
+ if (st.size > cfg.maxFileBytes) continue;
167
+ const key = `${st.size}:${Math.round(st.mtimeMs)}`;
168
+ const hit = old[rel];
169
+ if (hit && hit.k === key) { fresh[rel] = hit; files.push({ path: rel, ...hit.d }); } else todo.push({ rel, key });
170
+ }
171
+ let done;
172
+ if (todo.length > 150) done = await inWorkers(root, todo);
173
+ else done = todo.map(({ rel, key }) => ({ rel, key, d: analyze(rel, fs.readFileSync(path.join(root, rel), 'utf8')) }));
174
+ for (const { rel, key, d } of done) { fresh[rel] = { k: key, d }; files.push({ path: rel, ...d }); }
175
+ files.sort((a, b) => (a.path < b.path ? -1 : 1));
176
+ if (cache && !read) writeCache(root, fresh);
177
+ const foundation = findFoundation(root, cfg);
178
+ if (foundation) foundation.files = foundationFiles(foundation);
179
+ return { root, cfg, files, foundation, stats: { files: files.length, parsed: todo.length, cached: files.length - todo.length, ms: Math.round(performance.now() - t0) } };
180
+ }
package/src/report.js ADDED
@@ -0,0 +1,104 @@
1
+ // Terminal and HTML output. Colour only on a TTY and never with NO_COLOR.
2
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
3
+ const c = (n) => (s) => (tty ? `\x1b[${n}m${s}\x1b[0m` : String(s));
4
+ export const bold = c(1), dim = c(2), red = c(31), green = c(32), yellow = c(33), cyan = c(36);
5
+ const swatch = (hex) => (tty ? `\x1b[48;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m \x1b[0m` : '');
6
+ const bar = (n, of, w = 20) => { const k = Math.round((n / of) * w); return (n / of >= 0.7 ? green : n / of >= 0.4 ? yellow : red)('█'.repeat(k)) + dim('░'.repeat(w - k)); };
7
+ const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
8
+
9
+ export function auditText(a, model, { limit = 6 } = {}) {
10
+ const out = [];
11
+ const p = (...s) => out.push(s.join(''));
12
+ const grade = a.score >= 80 ? green : a.score >= 50 ? yellow : red;
13
+ p(bold('Designrail audit'), dim(` · ${model.files.length} files · ${a.tokenFiles.length ? `tokens in ${a.tokenFiles.join(', ')}` : 'no token files yet'}`));
14
+ p('');
15
+ p(' ', bold('Design system health '), grade(bold(`${a.score}/100`)));
16
+ for (const [k, v] of Object.entries(a.breakdown)) p(' ', k.padEnd(12), bar(v.score, v.of), ' ', `${v.score}/${v.of}`.padStart(5), ' ', dim(v.note));
17
+ p('');
18
+
19
+ p(bold('Colours'), dim(` · ${a.colors.items.length} distinct, ${a.colors.groups.length} after merging near-identical`));
20
+ for (const g of a.colors.near.slice(0, limit)) p(' ', g.members.map((m) => `${swatch(m.value)} ${m.value}`).join(' '), dim(` ${g.count} uses: look the same, pick one`));
21
+ if (a.colors.near.length > limit) p(dim(` … ${a.colors.near.length - limit} more groups`));
22
+
23
+ for (const [cat, s] of Object.entries(a.scales)) {
24
+ if (!s.items.length) continue;
25
+ p(bold(cat[0].toUpperCase() + cat.slice(1)), dim(` · ${s.items.length} distinct values${cat !== 'font-size' ? `, ${s.offGrid.length} off the ${s.grid}px grid` : ''}`));
26
+ p(' ', s.items.slice(0, 16).map((i) => `${+i.value.toFixed(2)}${dim('×' + i.count)}`).join(' '));
27
+ if (cat !== 'font-size' && s.offGrid.length) p(' ', yellow('off grid: '), s.offGrid.slice(0, 10).map((i) => `${+i.value.toFixed(2)}px ${dim(i.at[0])}`).join(', '));
28
+ }
29
+ const other = [['Font families', a.fonts], ['Font weights', a.weights], ['Shadows', a.shadows], ['Durations', a.durations], ['z-index', a.z]];
30
+ for (const [label, list] of other) if (list.length) p(bold(label), dim(` · ${list.length} distinct: `), list.slice(0, 6).map((i) => `${String(i.value).slice(0, 40)}${dim('×' + i.count)}`).join(', '));
31
+ p('');
32
+
33
+ p(bold('Duplicate rule blocks'), dim(` · ${plural(a.blocks.groups.length, 'group')} identical, ${plural(a.blocks.near.length, 'pair')} nearly`));
34
+ for (const g of a.blocks.groups.slice(0, limit)) p(' ', cyan(g.rules.map((r) => r.sel).slice(0, 4).join(' ≡ ')), dim(` ${g.decls.length} declarations · ${g.rules.map((r) => `${r.file}:${r.line}`).slice(0, 3).join(', ')}`));
35
+ for (const n of a.blocks.near.slice(0, limit)) p(' ', cyan(`${n.a.sel} ≈ ${n.b.sel}`), dim(` ${Math.round(n.similarity * 100)}% · ${n.a.file}:${n.a.line}, ${n.b.file}:${n.b.line}`), n.diff.length ? dim(` differs: ${n.diff.slice(0, 3).join(', ')}`) : '');
36
+ p('');
37
+
38
+ p(bold('Parts drawn more than one way'), dim(' · the same part under different class families'));
39
+ if (!a.parts.length) p(dim(' none found'));
40
+ for (const r of a.parts.slice(0, limit)) {
41
+ p(' ', bold(r.role), dim(` · ${`${r.families.length} families`} → one part with variants: the foundation's ${{ button: '.btn', field: '.input', card: '.card', pill: '.pill', dialog: '.sheet', toast: '.toast', dropdown: '.menu' }[r.role]}`));
42
+ for (const f of r.families.slice(0, 5)) p(' ', cyan(f.family.padEnd(18)), dim(`${[...f.classes].slice(0, 4).map((x) => '.' + x).join(' ')} ${f.at[0]}`));
43
+ }
44
+ p('');
45
+
46
+ p(bold('Repeated markup'), dim(` · ${plural(a.markup.exact.length, 'block')} copied as is, ${plural(a.markup.shape.length, 'structure')} repeated with different classes`));
47
+ for (const m of a.markup.exact.slice(0, limit)) p(' ', cyan(m.label), dim(` (${m.size} elements: ${m.kids}) × ${m.count} in ${plural(m.files, 'file')} · ${m.at.slice(0, 3).join(', ')}`));
48
+ for (const m of a.markup.shape.slice(0, Math.max(2, limit / 2))) p(' ', yellow(m.label), dim(` same shape, ${m.size} elements × ${m.count} · ${m.at.slice(0, 3).join(', ')}`));
49
+ p('');
50
+ p(dim('Next: '), model.foundation ? '' : 'npm i -D @rickycourtes/designrail → ', a.tokenFiles.length ? 'designrail fix (preview) → designrail fix --write' : 'designrail extract → designrail fix → designrail check --install-hook');
51
+ return out.join('\n');
52
+ }
53
+
54
+ export function hitsText(list, { title, limit = 40 } = {}) {
55
+ const out = [];
56
+ const by = {};
57
+ for (const h of list) (by[h.rule] ??= []).push(h);
58
+ if (title) out.push(bold(title));
59
+ for (const [rule, hs] of Object.entries(by)) {
60
+ const lvl = hs[0].level === 'error' ? red : yellow;
61
+ out.push(`${lvl(rule)} ${dim(`· ${hs.length}`)}`);
62
+ for (const h of hs.slice(0, limit)) out.push(` ${dim(`${h.file}:${h.line}`)} ${h.msg}`);
63
+ if (hs.length > limit) out.push(dim(` … ${hs.length - limit} more (--all)`));
64
+ }
65
+ return out.join('\n');
66
+ }
67
+
68
+ const esc = (s) => String(s).replace(/[&<>"]/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[ch]));
69
+
70
+ export function auditHtml(a, model) {
71
+ const name = esc(model.root.split('/').pop());
72
+ const color = a.score >= 80 ? '#1f9d55' : a.score >= 50 ? '#c98a00' : '#d23c3c';
73
+ const rows = (list, f) => list.map(f).join('');
74
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${name} · Designrail audit</title>
75
+ <style>
76
+ :root{--bg:#fbfbfa;--fg:#18181b;--mute:#6b6b74;--rim:#e7e7ea;--card:#fff;--accent:#2f6bff}
77
+ @media(prefers-color-scheme:dark){:root{--bg:#111113;--fg:#f2f2f3;--mute:#9a9aa3;--rim:#26262b;--card:#18181b;--accent:#6b95ff}}
78
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,'Segoe UI',sans-serif}
79
+ main{max-width:1040px;margin:0 auto;padding:40px 24px;display:grid;gap:24px}
80
+ h1{margin:0;font-size:24px}h2{margin:0 0 12px;font-size:17px}.mute{color:var(--mute)}code{font:12.5px ui-monospace,Menlo,monospace}
81
+ .card{background:var(--card);border:1px solid var(--rim);border-radius:14px;padding:20px}
82
+ .head{display:flex;gap:24px;align-items:center}.ring{width:96px;height:96px;border-radius:50%;display:grid;place-items:center;background:conic-gradient(${color} ${a.score * 3.6}deg,var(--rim) 0);flex:none}
83
+ .ring b{display:grid;place-items:center;width:76px;height:76px;border-radius:50%;background:var(--card);font-size:26px}
84
+ .bars{display:grid;gap:8px}.bar{display:grid;grid-template-columns:110px 1fr 56px;gap:12px;align-items:center;font-size:14px}
85
+ .track{height:8px;border-radius:4px;background:var(--rim);overflow:hidden}.track i{display:block;height:100%;background:var(--accent);border-radius:4px}
86
+ .sw{display:flex;flex-wrap:wrap;gap:8px}.chip{display:flex;align-items:center;gap:8px;padding:4px 10px 4px 4px;border:1px solid var(--rim);border-radius:999px;font-size:12.5px}.chip span{width:22px;height:22px;border-radius:50%;box-shadow:inset 0 0 0 1px rgb(0 0 0/.1)}
87
+ .group{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px 0;border-bottom:1px solid var(--rim)}
88
+ table{width:100%;border-collapse:collapse;font-size:13.5px}td,th{text-align:left;padding:8px 6px;border-bottom:1px solid var(--rim);vertical-align:top}th{color:var(--mute);font-weight:500}
89
+ .vals{display:flex;flex-wrap:wrap;gap:6px}.val{padding:2px 8px;border-radius:6px;background:var(--rim);font-size:12.5px}.val.off{background:#c98a0033}
90
+ </style></head><body><main>
91
+ <div class="card head"><div class="ring"><b>${a.score}</b></div><div><h1>${name}</h1><p class="mute">${model.files.length} files scanned · ${a.hardcoded} hardcoded design values · ${a.tokenFiles.length ? 'tokens: ' + esc(a.tokenFiles.join(', ')) : 'no token files yet'}</p></div></div>
92
+ <div class="card"><h2>Health</h2><div class="bars">${rows(Object.entries(a.breakdown), ([k, v]) => `<div class="bar"><span>${k}</span><div class="track"><i style="width:${(v.score / v.of) * 100}%"></i></div><span>${v.score}/${v.of}</span></div><div class="mute" style="font-size:12.5px;margin:-4px 0 4px 122px">${esc(v.note)}</div>`)}</div></div>
93
+ <div class="card"><h2>Colours <span class="mute">· ${a.colors.items.length} distinct</span></h2>
94
+ ${a.colors.near.length ? `<p class="mute">Near-identical groups: each could be one token.</p>${rows(a.colors.near, (g) => `<div class="group">${g.members.map((m) => `<span class="chip"><span style="background:${m.value}"></span>${m.value} <span class="mute">×${m.count}</span></span>`).join('')}</div>`)}` : ''}
95
+ <p class="mute">All colours by use</p><div class="sw">${rows(a.colors.items.slice(0, 80), (i) => `<span class="chip"><span style="background:${i.value}"></span>${i.value} <span class="mute">×${i.count}</span></span>`)}</div></div>
96
+ <div class="card"><h2>Scales</h2>${rows(Object.entries(a.scales).filter(([, s]) => s.items.length), ([cat, s]) => `<p><b>${cat}</b> <span class="mute">· ${s.items.length} values${cat !== 'font-size' ? `, ${s.offGrid.length} off the ${s.grid}px grid` : ''}</span></p><div class="vals">${s.items.map((i) => `<span class="val ${cat !== 'font-size' && i.value % s.grid ? 'off' : ''}">${+i.value.toFixed(2)}px ×${i.count}</span>`).join('')}</div>`)}</div>
97
+ <div class="card"><h2>Duplicate rule blocks <span class="mute">· ${a.blocks.groups.length} identical groups, ${a.blocks.near.length} near pairs</span></h2><table><tr><th>Selectors</th><th>Declarations</th><th>Where</th></tr>
98
+ ${rows(a.blocks.groups.slice(0, 40), (g) => `<tr><td><code>${esc(g.rules.map((r) => r.sel).join(' ≡ '))}</code></td><td>${g.decls.length}</td><td class="mute">${esc(g.rules.map((r) => `${r.file}:${r.line}`).join(', '))}</td></tr>`)}
99
+ ${rows(a.blocks.near.slice(0, 40), (n) => `<tr><td><code>${esc(n.a.sel)} ≈ ${esc(n.b.sel)}</code> <span class="mute">${Math.round(n.similarity * 100)}%</span></td><td>${n.shared}</td><td class="mute">${esc(`${n.a.file}:${n.a.line}, ${n.b.file}:${n.b.line}`)}</td></tr>`)}</table></div>
100
+ <div class="card"><h2>Parts drawn more than one way</h2>${a.parts.length ? `<table><tr><th>Part</th><th>Families</th><th>Where</th></tr>${rows(a.parts, (r) => `<tr><td><b>${r.role}</b></td><td>${r.families.map((f) => `<code>${esc(f.family)}</code> <span class="mute">(${[...f.classes].slice(0, 4).map((x) => '.' + esc(x)).join(' ')})</span>`).join('<br>')}</td><td class="mute">${r.families.map((f) => esc(f.at[0])).join('<br>')}</td></tr>`)}</table>` : '<p class="mute">None found.</p>'}</div>
101
+ <div class="card"><h2>Repeated markup</h2>${a.markup.exact.length + a.markup.shape.length ? `<table><tr><th>Block</th><th>Copies</th><th>Where</th></tr>${rows(a.markup.exact.slice(0, 30), (m) => `<tr><td><code>${esc(m.label)}</code> <span class="mute">${m.size} elements: ${esc(m.kids)}</span></td><td>${m.count}</td><td class="mute">${esc(m.at.join(', '))}</td></tr>`)}${rows(a.markup.shape.slice(0, 15), (m) => `<tr><td><code>${esc(m.label)}</code> <span class="mute">same shape, other classes</span></td><td>${m.count}</td><td class="mute">${esc(m.at.join(', '))}</td></tr>`)}</table>` : '<p class="mute">None found.</p>'}</div>
102
+ <p class="mute" style="text-align:center">Generated by Designrail</p>
103
+ </main></body></html>`;
104
+ }
package/src/sources.js ADDED
@@ -0,0 +1,145 @@
1
+ // One file → what Designrail needs from it: style rules with value offsets,
2
+ // custom-property uses, Tailwind arbitrary values and markup fingerprints.
3
+ // Pure (text in, data out), so it runs the same in a worker or the main thread.
4
+ import { parseCss, lineStarts } from './css.js';
5
+ import { kebab } from './values.js';
6
+ import { markupTrees } from './markup.js';
7
+
8
+ export const CSS_EXT = /\.(css|scss|less|pcss|postcss)$/;
9
+ export const SFC_EXT = /\.(vue|svelte|astro|html?)$/;
10
+ export const JS_EXT = /\.(m?[jt]sx?|cjs)$/;
11
+ export const ALL_EXT = /\.(css|scss|less|pcss|postcss|vue|svelte|astro|html?|m?[jt]sx?|cjs)$/;
12
+
13
+ const lineAt = (starts, i) => {
14
+ let lo = 0, hi = starts.length - 1;
15
+ while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= i) lo = mid; else hi = mid - 1; }
16
+ return lo + 1;
17
+ };
18
+
19
+ // Template interpolations `${…}` become same-length filler so offsets hold.
20
+ function fillInterpolations(s) {
21
+ let out = '', i = 0;
22
+ while (i < s.length) {
23
+ if (s[i] === '$' && s[i + 1] === '{') {
24
+ let d = 0, j = i + 1;
25
+ for (; j < s.length; j++) { if (s[j] === '{') d++; else if (s[j] === '}' && --d === 0) break; }
26
+ out += 'x'.repeat(j + 1 - i).replace(/x/g, (c, k) => (s[i + k] === '\n' ? '\n' : 'x'));
27
+ i = j + 1;
28
+ } else out += s[i++];
29
+ }
30
+ return out;
31
+ }
32
+
33
+ // CSS property names written camelCase in JS style objects.
34
+ const JS_PROPS = /^(color|background|backgroundColor|border|borderColor|border(Top|Right|Bottom|Left)(Color)?|borderRadius|border(Top|Bottom)(Left|Right)Radius|outline|outlineColor|fill|stroke|boxShadow|textShadow|margin|marginTop|marginRight|marginBottom|marginLeft|marginInline|marginBlock|padding|paddingTop|paddingRight|paddingBottom|paddingLeft|paddingInline|paddingBlock|gap|rowGap|columnGap|top|right|bottom|left|inset|fontSize|fontWeight|fontFamily|lineHeight|letterSpacing|zIndex)$/;
35
+ const UNITLESS = /^(fontWeight|lineHeight|zIndex)$/;
36
+
37
+ // Tailwind arbitrary values: p-[13px], bg-[#fafafa], rounded-[6px], text-[15px].
38
+ const TW = /(?<![\w-])(-?)(p|px|py|pt|pr|pb|pl|ps|pe|m|mx|my|mt|mr|mb|ml|ms|me|gap|gap-x|gap-y|space-x|space-y|inset|top|right|bottom|left|rounded(?:-[trblse]{1,2})?|text|bg|border(?:-[trblxy])?|outline|ring|fill|stroke|shadow|z|leading|tracking|font|w|h|min-w|min-h|max-w|max-h|size|duration)-\[([^\]\s'"`]+)\]/g;
39
+ const TW_PROP = (u, v) => {
40
+ const isColor = /^(#|rgb|hsl|oklch|oklab)/.test(v);
41
+ if (/^p[xytrblse]?$/.test(u)) return 'padding';
42
+ if (/^m[xytrblse]?$/.test(u)) return 'margin';
43
+ if (/^(gap|space)/.test(u)) return 'gap';
44
+ if (/^(inset|top|right|bottom|left)$/.test(u)) return u === 'inset' ? 'inset' : u;
45
+ if (u.startsWith('rounded')) return 'border-radius';
46
+ if (u === 'text') return isColor ? 'color' : 'font-size';
47
+ if (u === 'bg') return 'background-color';
48
+ if (u.startsWith('border')) return isColor ? 'border-color' : 'border-width';
49
+ if (u === 'outline' || u === 'ring') return isColor ? 'outline-color' : 'outline-width';
50
+ if (u === 'fill' || u === 'stroke') return u;
51
+ if (u === 'shadow') return 'box-shadow';
52
+ if (u === 'z') return 'z-index';
53
+ if (u === 'leading') return 'line-height';
54
+ if (u === 'tracking') return 'letter-spacing';
55
+ if (u === 'font') return /^\d+$/.test(v) ? 'font-weight' : 'font-family';
56
+ if (u === 'duration') return 'transition-duration';
57
+ return { w: 'width', h: 'height', 'min-w': 'min-width', 'min-h': 'min-height', 'max-w': 'max-width', 'max-h': 'max-height', size: 'width' }[u];
58
+ };
59
+
60
+ // Everything outside <script> blanked, offsets kept.
61
+ function onlyScripts(text) {
62
+ const out = text.replace(/[^\n]/g, ' ').split('');
63
+ for (const m of text.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)) {
64
+ const s = m.index + m[0].indexOf('>') + 1;
65
+ for (let i = 0; i < m[1].length; i++) out[s + i] = m[1][i];
66
+ }
67
+ return out.join('');
68
+ }
69
+
70
+ export function analyze(path, text) {
71
+ const starts = lineStarts(text);
72
+ const rules = [];
73
+ const add = (r, origin) => { for (const x of r.rules) { x.origin = origin; rules.push(x); } };
74
+
75
+ if (CSS_EXT.test(path)) add(parseCss(text, { starts, lineComments: /\.(scss|less)$/.test(path) }), 'css');
76
+
77
+ if (SFC_EXT.test(path)) {
78
+ for (const m of text.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi)) {
79
+ const base = m.index + m[0].indexOf('>') + 1;
80
+ add(parseCss(m[2], { base, starts, lineComments: /lang=["'](scss|less)/.test(m[1]) }), 'style');
81
+ }
82
+ for (const m of text.matchAll(/\sstyle=(["'])([^"']*)\1/gi)) {
83
+ if (/[{}]/.test(m[2])) continue;
84
+ const base = m.index + m[0].indexOf(m[1]) + 1;
85
+ add(parseCss(m[2], { base, starts, inline: `style@${lineAt(starts, m.index)}` }), 'inline');
86
+ }
87
+ }
88
+
89
+ const script = JS_EXT.test(path) ? text : SFC_EXT.test(path) ? onlyScripts(text) : '';
90
+ if (script) {
91
+ // css`…`, styled.x`…`, styled(X)`…`, createGlobalStyle`…`, keyframes`…`
92
+ for (const m of script.matchAll(/\b(css|styled(?:\.\w+|\([^()]*\))(?:\.attrs\([^)]*\))?|createGlobalStyle|injectGlobal|keyframes)\s*`/g)) {
93
+ const s = m.index + m[0].length;
94
+ let e = s;
95
+ for (; e < script.length; e++) { if (script[e] === '\\') e++; else if (script[e] === '`') break; else if (script[e] === '$' && script[e + 1] === '{') { let d = 0; for (e++; e < script.length; e++) { if (script[e] === '{') d++; else if (script[e] === '}' && --d === 0) break; } } }
96
+ const body = fillInterpolations(text.slice(s, e));
97
+ add(parseCss(body, { base: s, starts, inline: `${m[1].split(/[.(]/)[0]}@${lineAt(starts, m.index)}` }), 'css-in-js');
98
+ }
99
+ // Inline style objects: style={{ … }}, sx={{ … }}, Object.assign(el.style, { … }),
100
+ // and el.style.prop = '…'. Known CSS props only, so config objects stay out.
101
+ const decls = [];
102
+ const prop = (name, raw, numeric, at, vstart) => {
103
+ if (!JS_PROPS.test(name) || (numeric && Number(raw) === 0)) return;
104
+ const value = numeric && !UNITLESS.test(name) ? `${raw}px` : raw;
105
+ decls.push({ prop: kebab(name), value, line: lineAt(starts, at), vstart, vend: vstart + raw.length, js: numeric ? 'number' : 'string' });
106
+ };
107
+ for (const m of script.matchAll(/\b(?:style|sx)\s*=\s*\{\{|Object\.assign\(\s*[\w.$]*\.style\s*,\s*\{/g)) {
108
+ const s = m.index + m[0].length;
109
+ let d = 1, e = s;
110
+ for (; e < script.length && d; e++) { if (script[e] === '{') d++; else if (script[e] === '}') d--; }
111
+ const body = script.slice(s, e - 1);
112
+ for (const p of body.matchAll(/(?<![\w$.])([a-zA-Z]+)\s*:\s*(?:(['"])([^'"\n]*)\2|(-?\d+\.?\d*)(?![\w.]))/g)) {
113
+ const numeric = p[4] !== undefined, raw = p[3] ?? p[4];
114
+ const at = s + p.index;
115
+ prop(p[1], raw, numeric, at, at + p[0].length - (numeric ? raw.length : raw.length + 1));
116
+ }
117
+ }
118
+ for (const m of script.matchAll(/\.style\.([a-zA-Z]+)\s*=\s*(['"])([^'"\n]*)\2/g)) {
119
+ prop(m[1], m[3], false, m.index, m.index + m[0].length - m[3].length - 1);
120
+ }
121
+ if (decls.length) rules.push({ sel: 'style object', media: null, line: decls[0].line, decls, origin: 'js-object' });
122
+ }
123
+
124
+ // Tailwind arbitrary values anywhere a class list can be.
125
+ if (!CSS_EXT.test(path)) {
126
+ const decls = [];
127
+ for (const m of text.matchAll(TW)) {
128
+ const prop = TW_PROP(m[2], m[3]);
129
+ if (!prop) continue;
130
+ const vstart = m.index + m[0].length - 1 - m[3].length;
131
+ decls.push({ prop, value: m[3].replace(/_/g, ' '), line: lineAt(starts, m.index), vstart, vend: vstart + m[3].length, tw: true });
132
+ }
133
+ if (decls.length) rules.push({ sel: 'tailwind', media: null, line: decls[0].line, decls, origin: 'tailwind' });
134
+ }
135
+
136
+ // Custom properties read, and set at runtime (setProperty / style vars).
137
+ const uses = [];
138
+ for (const m of text.matchAll(/var\(\s*(--[\w-]+)\s*(,)?/g)) uses.push([m[1], lineAt(starts, m.index), m[2] ? 1 : 0]);
139
+ const runtime = [...new Set([...script.matchAll(/(?:setProperty|style\.setProperty|live)\(\s*[^,]*?['"](--[\w-]+)['"]/g), ...script.matchAll(/['"](--[\w-]+)['"]\s*:/g)].map((m) => m[1]))];
140
+
141
+ const trees = SFC_EXT.test(path) || /\.[jt]sx$/.test(path) || (JS_EXT.test(path) && /<[A-Za-z][\w.]*[\s>/]/.test(text) && /return\s*\(?\s*</.test(text))
142
+ ? markupTrees(text, starts, path) : [];
143
+
144
+ return { rules, uses, runtime, trees };
145
+ }