@rickycourtes/designrail 0.0.0-stage → 0.2.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.
@@ -0,0 +1,94 @@
1
+ // Specimens: one static page with every token and every part, wearing the
2
+ // project's own token files, so the whole system can be seen at once.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { tokenIndex } from './tokens.js';
6
+ import { KIT, PARTS } from './kit.js';
7
+
8
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
9
+
10
+ const DEMO = {
11
+ button: `<div class="actions" style="justify-content:flex-start"><button class="btn primary">Save changes</button><button class="btn">Duplicate</button><button class="btn quiet">Not now</button><button class="btn danger">Delete</button><button class="btn small">Small</button><button class="icon-btn" aria-label="More"><svg viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg></button></div>`,
12
+ field: `<div class="stack" style="max-width:360px"><label class="field"><span class="label">Email</span><input class="input" type="email" placeholder="you@example.com"><span class="hint">We never share it.</span></label><label class="field invalid"><span class="label">Name</span><input class="input" value="?"><span class="hint">Use at least two letters.</span></label><label class="field"><span class="label">Plan</span><select class="input"><option>Starter</option><option>Team</option></select></label><label class="check"><input type="checkbox" checked><span>Email me when someone replies, including replies to threads I follow</span></label></div>`,
13
+ card: `<div class="card" style="max-width:360px"><div class="card-head"><h3>Weekly digest</h3><p>Every Monday at 9:00</p></div><div class="inset">Inner boxes keep a concentric corner.</div><div class="actions"><button class="btn quiet">Skip</button><button class="btn primary">Turn on</button></div></div>`,
14
+ pill: `<div class="row"><span class="pill">Draft</span><span class="pill accent"><span class="dot"></span>Live</span><span class="pill success">Paid</span><span class="pill warning">Due soon</span><span class="pill danger">Failed</span><span class="row tight">Comments <span class="count">12</span></span></div>`,
15
+ dropdown: `<div style="min-height:200px"><div class="dropdown"><button class="btn" aria-haspopup="menu" aria-expanded="true">Sort by</button><div class="menu" role="menu"><button class="menu-item" role="menuitemradio" aria-checked="true">Newest</button><button class="menu-item" role="menuitemradio">Oldest</button><div class="menu-sep"></div><button class="menu-item" role="menuitem">Reset</button></div></div></div>`,
16
+ toast: `<div class="toast" style="animation:none">Link copied <button class="btn">Undo</button></div>`,
17
+ sheet: `<dialog class="sheet" open style="position:static;margin:0;animation:none"><header class="sheet-head"><h2>Rename project</h2><button class="icon-btn sheet-close" aria-label="Close">×</button></header><label class="field"><span class="label">Name</span><input class="input" value="Patchwork"></label><footer class="actions"><button class="btn quiet">Cancel</button><button class="btn primary">Rename</button></footer></dialog>`,
18
+ };
19
+
20
+ export function specimens(model) {
21
+ const tokens = tokenIndex(model);
22
+ const css = [...model.tokenFiles].map((f) => `/* ${f} */\n` + fs.readFileSync(path.join(model.root, f), 'utf8').replace(/@import[^;]+;/g, '')).join('\n');
23
+ const partsDir = path.join(model.root, model.cfg.parts);
24
+ const kitDir = model.foundation?.dir ?? KIT;
25
+ const ejected = new Set(model.cfg.ejected ?? []);
26
+ const parts = Object.entries(PARTS).map(([name, files]) => {
27
+ const own = path.join(partsDir, files[0]);
28
+ const mine = fs.existsSync(own) && (ejected.has(name) || !model.foundation);
29
+ const from = mine ? (model.foundation ? 'ejected' : 'project') : model.foundation ? 'foundation' : 'kit';
30
+ return { name, from, css: fs.readFileSync(mine ? own : path.join(kitDir, 'parts', files[0]), 'utf8') };
31
+ });
32
+ const noTokens = !tokens.some((t) => !t.external);
33
+ // The foundation's theme sits underneath (layered); the project's tokens go on top.
34
+ const kitTokens = model.foundation || noTokens ? fs.readFileSync(path.join(kitDir, 'tokens.css'), 'utf8') : '';
35
+ const themed = (noTokens && !model.foundation) || /data-theme|prefers-color-scheme:\s*dark/.test(css) || (model.foundation && !css);
36
+
37
+ const shown = tokens.filter((t) => !t.external || noTokens);
38
+ const colors = shown.filter((t) => t.color);
39
+ const sem = colors.filter((t) => t.semantic);
40
+ const prim = colors.filter((t) => !t.semantic);
41
+ const lengths = (cat) => shown.filter((t) => t.cat === cat && t.px != null).sort((a, b) => a.px - b.px);
42
+ const swatch = (t) => `<figure class="dr-sw"><span style="background:var(${t.name})"></span><figcaption><b>${esc(t.name)}</b><code>${esc(t.semantic ? t.raw : t.value)}</code></figcaption></figure>`;
43
+
44
+ const sections = [
45
+ sem.length && `<section><h2>Colour · semantic</h2><p class="dr-note">What each colour is for. Parts read these.</p><div class="dr-grid">${sem.map(swatch).join('')}</div></section>`,
46
+ prim.length && `<section><h2>Colour · primitives</h2><p class="dr-note">Raw values, named for what they are.</p><div class="dr-grid">${prim.map(swatch).join('')}</div></section>`,
47
+ lengths('space').length && `<section><h2>Space</h2>${lengths('space').map((t) => `<div class="dr-row"><code>${esc(t.name)}</code><span class="dr-bar" style="width:var(${t.name})"></span><small>${t.px}px</small></div>`).join('')}</section>`,
48
+ lengths('radius').length && `<section><h2>Radius</h2><div class="dr-grid">${lengths('radius').map((t) => `<figure class="dr-rad"><span style="border-radius:var(${t.name})"></span><figcaption><b>${esc(t.name)}</b><code>${esc(t.value)}</code></figcaption></figure>`).join('')}</div></section>`,
49
+ lengths('font-size').length && `<section><h2>Type sizes</h2>${lengths('font-size').map((t) => `<div class="dr-row"><code>${esc(t.name)}</code><span style="font-size:var(${t.name})">The quick brown fox</span><small>${t.px}px</small></div>`).join('')}</section>`,
50
+ shown.some((t) => t.font) && `<section><h2>Families</h2>${shown.filter((t) => t.font).map((t) => `<div class="dr-row"><code>${esc(t.name)}</code><span style="font-family:var(${t.name});font-size:22px">Sphinx of black quartz, judge my vow</span></div>`).join('')}</section>`,
51
+ shown.some((t) => t.shadow) && `<section><h2>Shadows</h2><div class="dr-grid">${shown.filter((t) => t.shadow).map((t) => `<figure class="dr-sh"><span style="box-shadow:var(${t.name})"></span><figcaption><b>${esc(t.name)}</b></figcaption></figure>`).join('')}</div></section>`,
52
+ `<section><h2>Parts</h2><p class="dr-note">${model.foundation ? `The foundation's parts (${esc(model.foundation.version)}) in this project's tokens${ejected.size ? '; <em>ejected</em> ones are the project’s own copies' : ''}.` : 'Parts marked <em>kit</em> come from the Designrail foundation: install it (<code>npm i -D @rickycourtes/designrail</code>) and import <code>@rickycourtes/designrail/foundation.css</code>.'}</p>${parts.filter((p) => DEMO[p.name]).map((p) => `<div class="dr-part"><h3>${p.name}<span class="dr-tag">${p.from}</span></h3><div class="dr-stage">${DEMO[p.name]}</div></div>`).join('')}</section>`,
53
+ ].filter(Boolean);
54
+
55
+ return `<!doctype html>
56
+ <html lang="en">
57
+ <head>
58
+ <meta charset="utf-8">
59
+ <meta name="viewport" content="width=device-width, initial-scale=1">
60
+ <title>${esc(path.basename(model.root))} · design system</title>
61
+ <style>
62
+ @layer designrail.tokens, designrail.base, designrail.parts;
63
+ ${kitTokens}
64
+ ${css}
65
+ ${parts.map((p) => `/* part: ${p.name} (${p.from}) */\n${p.css}`).join('\n')}
66
+ /* --- specimen chrome: reads the project's tokens, with fallbacks --- */
67
+ :root { --dr-bg: var(--surface, #fff); --dr-fg: var(--text, #111); --dr-mute: var(--text-muted, #666); --dr-rim: var(--border, #e5e5e5); --dr-font: var(--font-ui, system-ui, sans-serif); }
68
+ body { margin: 0; background: var(--dr-bg); color: var(--dr-fg); font: 15px/1.5 var(--dr-font); }
69
+ .dr-top { position: sticky; top: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 32px; background: color-mix(in srgb, var(--dr-bg) 86%, transparent); backdrop-filter: blur(12px); border-bottom: 1px solid var(--dr-rim); }
70
+ .dr-top h1 { margin: 0; font-size: 18px; } .dr-top p { margin: 0; color: var(--dr-mute); font-size: 13px; }
71
+ .dr-top button { height: 36px; padding: 0 16px; border-radius: 999px; border: 1px solid var(--dr-rim); background: transparent; color: var(--dr-fg); font: inherit; cursor: pointer; }
72
+ main { max-width: 1080px; margin: 0 auto; padding: 32px; display: grid; gap: 48px; }
73
+ section > h2 { margin: 0 0 4px; font-size: 20px; } .dr-note { margin: 0 0 16px; color: var(--dr-mute); font-size: 13px; }
74
+ .dr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 16px; }
75
+ figure { margin: 0; display: grid; gap: 8px; } figcaption { display: grid; gap: 2px; font-size: 12px; } figcaption b { font-weight: 600; word-break: break-all; } figcaption code, .dr-row code, .dr-row small { color: var(--dr-mute); font-size: 12px; word-break: break-all; }
76
+ .dr-sw span { height: 64px; border-radius: 10px; box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--dr-fg) 12%, transparent); background-image: none; }
77
+ .dr-rad span { width: 72px; height: 72px; background: color-mix(in srgb, var(--dr-fg) 10%, transparent); }
78
+ .dr-sh span { height: 72px; border-radius: 12px; background: var(--dr-bg); margin: 8px; }
79
+ .dr-row { display: grid; grid-template-columns: 180px 1fr 60px; align-items: center; gap: 16px; padding: 6px 0; border-bottom: 1px solid var(--dr-rim); }
80
+ .dr-bar { height: 12px; border-radius: 3px; background: var(--accent, #2563eb); min-width: 1px; }
81
+ .dr-part { display: grid; gap: 8px; margin-bottom: 24px; } .dr-part > h3 { margin: 0; font-size: 14px; display: flex; gap: 8px; align-items: center; text-transform: capitalize; }
82
+ .dr-tag { font-size: 11px; font-weight: 500; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--dr-rim); color: var(--dr-mute); text-transform: none; }
83
+ .dr-stage { padding: 24px; border: 1px solid var(--dr-rim); border-radius: 14px; background: var(--surface-sunken, transparent); }
84
+ </style>
85
+ </head>
86
+ <body>
87
+ <header class="dr-top"><div><h1>${esc(path.basename(model.root))} design system</h1><p>${tokens.filter((t) => !t.external).length} tokens from ${model.tokenFiles.size} token file${model.tokenFiles.size === 1 ? '' : 's'}${model.foundation ? ` on foundation ${esc(model.foundation.version)}` : noTokens ? ' (none yet: showing the foundation’s defaults)' : ''} · generated by Designrail</p></div>${themed ? '' : '<!-- no dark theme in the token files -->'}<button ${themed ? '' : 'hidden '}onclick="const r=document.documentElement;r.dataset.theme=r.dataset.theme==='dark'?'light':'dark'">Light / dark</button></header>
88
+ <main>
89
+ ${sections.join('\n')}
90
+ </main>
91
+ </body>
92
+ </html>
93
+ `;
94
+ }
package/src/tokens.js ADDED
@@ -0,0 +1,55 @@
1
+ // Every token the token files define, resolved to what it finally is, with
2
+ // the facts `fix`, `check`, `trace` and `specimens` match on.
3
+ import { parseColor, colorFacts, normShadow, lengthCategory } from './values.js';
4
+ import { roleOfName, CONTRACT } from './contract.js';
5
+ import { pickDef } from './model.js';
6
+
7
+ const nameCat = (n) => (/space|gap|pad|margin|inset|gutter|spacing/.test(n) ? 'space' : /radius|round|corner|rounded/.test(n) ? 'radius' : /font-size|text-size|(^--)(size|fs|type)-|-size-?\d/.test(n) ? 'font-size' : null);
8
+ export const firstFamily = (stack) => stack.split(',')[0].trim().replace(/^['"]|['"]$/g, '').toLowerCase();
9
+
10
+ export function tokenIndex(model) {
11
+ // Which property each token ends up in, followed up through semantic aliases.
12
+ const usedIn = new Map();
13
+ const bump = (name, cat) => { if (!usedIn.has(name)) usedIn.set(name, {}); const c = usedIn.get(name); c[cat] = (c[cat] ?? 0) + 1; };
14
+ for (const { d } of model.decls) {
15
+ const cat = lengthCategory(d.prop);
16
+ if (!cat) continue;
17
+ for (const m of d.value.matchAll(/var\(\s*(--[\w-]+)/g)) {
18
+ bump(m[1], cat);
19
+ for (const n of model.resolve(m[1]).chain ?? []) if (n !== m[1]) bump(n, cat);
20
+ }
21
+ }
22
+ const list = [];
23
+ for (const [name, ds] of model.defs) {
24
+ const d = pickDef(ds);
25
+ if (!d?.inTokens) continue;
26
+ const r = model.resolve(name);
27
+ const value = (r.value ?? '').trim();
28
+ const t = { name, raw: d.value, value, file: d.file, line: d.line, external: Boolean(d.external), semantic: /var\(/.test(d.value), role: roleOfName(name), chain: r.chain };
29
+ const c = parseColor(value);
30
+ if (c) t.color = colorFacts(c.hex);
31
+ const len = /^(-?\d*\.?\d+)(px|rem)$/.exec(value);
32
+ if (len) {
33
+ t.px = len[2] === 'px' ? parseFloat(len[1]) : parseFloat(len[1]) * 16;
34
+ const u = usedIn.get(name);
35
+ t.cat = u ? Object.entries(u).sort((a, b) => b[1] - a[1])[0][0] : nameCat(name);
36
+ }
37
+ if (/\d+px/.test(value) && /(#|rgb|hsl|oklch|inset|\d+px\s+-?\d+px)/.test(value) && /shadow|elev|depth/.test(name)) t.shadow = normShadow(value);
38
+ if (/font|family|face|typeface/.test(name) && !/size|weight|track|leading|line/.test(name) && /[a-z]/i.test(value) && !len) t.font = firstFamily(value);
39
+ const ms = /^(\d*\.?\d+)(ms|s)$/.exec(value);
40
+ if (ms) t.ms = ms[2] === 's' ? parseFloat(ms[1]) * 1000 : parseFloat(ms[1]);
41
+ list.push(t);
42
+ }
43
+ return list;
44
+ }
45
+
46
+ // Primitive: a token holding a literal, read by semantic tokens. A project with
47
+ // no semantic layer has no primitives in this sense (everything is the API).
48
+ // A literal token counts as a primitive when it lives in a primitives file or
49
+ // another token is built on it; a contract name is always API, never primitive.
50
+ export function primitivesOf(tokens) {
51
+ if (!tokens.some((t) => t.semantic)) return new Set();
52
+ const api = new Set(CONTRACT.map((c) => c.name));
53
+ const read = new Set(tokens.filter((t) => t.semantic).flatMap((t) => [...t.raw.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1])));
54
+ return new Set(tokens.filter((t) => !t.semantic && !api.has(t.name) && (/primitive/i.test(t.file) || read.has(t.name))).map((t) => t.name));
55
+ }
package/src/trace.js ADDED
@@ -0,0 +1,42 @@
1
+ // Trace: a selector's values down the token chain (rule → semantic →
2
+ // primitive → literal, file:line at each step), or a token's reach: what it
3
+ // is built on, what is built on it, and everywhere it is read.
4
+ import { pickDef } from './model.js';
5
+
6
+ function chainOf(model, name) {
7
+ const steps = [];
8
+ const seen = new Set();
9
+ let cur = name;
10
+ while (cur && !seen.has(cur)) {
11
+ seen.add(cur);
12
+ const d = pickDef(model.defs.get(cur));
13
+ if (!d) { steps.push({ name: cur, missing: !model.runtime.has(cur), runtime: model.runtime.has(cur) }); break; }
14
+ steps.push({ name: cur, value: d.value, at: `${d.file}:${d.line}` });
15
+ cur = /^var\(\s*(--[\w-]+)\s*(,[^)]*)?\)$/.exec(d.value.trim())?.[1];
16
+ }
17
+ return steps;
18
+ }
19
+
20
+ export function traceSelector(model, query) {
21
+ const q = query.trim();
22
+ const out = [];
23
+ for (const f of model.files) for (const r of f.rules) {
24
+ if (!r.sel || !r.sel.split(',').some((p) => p.trim() === q || p.trim().endsWith(q) || p.trim().split(/[\s>+~]+/).pop().startsWith(q + ':'))) continue;
25
+ out.push({
26
+ at: `${f.path}:${r.line}`, sel: r.sel, media: r.media,
27
+ decls: r.decls.map((d) => ({ prop: d.prop, value: d.value, chains: [...d.value.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => chainOf(model, m[1])) })),
28
+ });
29
+ }
30
+ return out;
31
+ }
32
+
33
+ export function traceToken(model, name) {
34
+ const chain = chainOf(model, name);
35
+ const builtOn = [];
36
+ for (const [n, ds] of model.defs) if (ds.some((d) => new RegExp(`var\\(\\s*${name}\\b`).test(d.value))) builtOn.push(n);
37
+ const reach = new Set([name]);
38
+ let grew = true;
39
+ while (grew) { grew = false; for (const [n, ds] of model.defs) if (!reach.has(n) && ds.some((d) => [...reach].some((r) => new RegExp(`var\\(\\s*${r}\\b`).test(d.value)))) { reach.add(n); grew = true; } }
40
+ const uses = [...reach].flatMap((n) => (model.uses.get(n) ?? []).filter((u) => !u.inTokens).map((u) => ({ ...u, via: n })));
41
+ return { chain, builtOn, reach: [...reach], uses };
42
+ }
package/src/upgrade.js ADDED
@@ -0,0 +1,69 @@
1
+ // Upgrade: move a project from the foundation version it was on
2
+ // (`foundation` in designrail.config.json) to the one installed. Every
3
+ // version's entry in kit/changes.json says what it renamed, added and
4
+ // removed; renames are rewritten across the project, the rest is reported,
5
+ // and ejected parts that drifted from the foundation are named.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { PARTS } from './kit.js';
9
+
10
+ export const semver = (v) => String(v ?? '0.0.0').split('.').map((n) => parseInt(n, 10) || 0);
11
+ export const cmp = (a, b) => { const x = semver(a), y = semver(b); for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i]; return 0; };
12
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
13
+
14
+ export function planUpgrade(model) {
15
+ const f = model.foundation;
16
+ if (!f) return null;
17
+ const from = model.cfg.foundation ?? '0.0.0';
18
+ const to = f.version;
19
+ let log = [];
20
+ try { log = JSON.parse(fs.readFileSync(path.join(f.dir, 'changes.json'), 'utf8')); } catch { /* an old foundation without a log */ }
21
+ const steps = log.filter((c) => cmp(c.version, from) > 0 && cmp(c.version, to) <= 0).sort((a, b) => cmp(a.version, b.version));
22
+
23
+ // Renames chain across versions: --a → --b in one, --b → --c in the next, is --a → --c.
24
+ const renames = new Map();
25
+ for (const s of steps) for (const [a, b] of Object.entries(s.renamed ?? {})) {
26
+ for (const [k, v] of renames) if (v === a) renames.set(k, b);
27
+ renames.set(a, b);
28
+ }
29
+ const edits = new Map();
30
+ for (const file of model.files) {
31
+ if (!renames.size) break;
32
+ const p = path.join(model.root, file.path);
33
+ const before = fs.readFileSync(p, 'utf8');
34
+ let text = before, count = 0;
35
+ for (const [a, b] of renames) {
36
+ if (a.startsWith('--')) {
37
+ text = text.replace(new RegExp(`(?<![\\w-])${esc(a)}(?![\\w-])`, 'g'), () => { count++; return b; });
38
+ } else if (a.startsWith('.')) {
39
+ const from = a.slice(1), to = b.replace(/^\./, '');
40
+ // In selectors, and inside class / className attribute values.
41
+ text = text.replace(new RegExp(`\\.${esc(from)}(?![\\w-])`, 'g'), () => { count++; return '.' + to; });
42
+ text = text.replace(/\b(class|className)=(["'])([^"']*)\2/g, (all, attr, q, v) => `${attr}=${q}${v.replace(new RegExp(`(^|\\s)${esc(from)}(?=\\s|$)`, 'g'), (m, sp) => { count++; return sp + to; })}${q}`);
43
+ }
44
+ }
45
+ if (count) edits.set(file.path, { text, count });
46
+ }
47
+
48
+ const added = { tokens: new Set(), parts: new Set(), classes: new Set() };
49
+ const removed = { tokens: new Set(), parts: new Set() };
50
+ for (const s of steps) {
51
+ for (const k of Object.keys(added)) for (const x of s.added?.[k] ?? []) added[k].add(x);
52
+ for (const k of Object.keys(removed)) for (const x of s.removed?.[k] ?? []) removed[k].add(x);
53
+ }
54
+ // Removed tokens the project still reads.
55
+ const stillRead = [...removed.tokens].filter((t) => (model.uses.get(t) ?? []).some((u) => !u.external));
56
+
57
+ // Ejected parts: the project's copy no longer follows the foundation.
58
+ const drifted = [];
59
+ for (const part of model.cfg.ejected ?? []) for (const file of PARTS[part] ?? []) {
60
+ const mine = path.join(model.root, model.cfg.parts, file);
61
+ const theirs = path.join(f.dir, 'parts', file);
62
+ if (fs.existsSync(mine) && fs.existsSync(theirs) && fs.readFileSync(mine, 'utf8') !== fs.readFileSync(theirs, 'utf8')) drifted.push(`${model.cfg.parts}/${file}`);
63
+ }
64
+ return { from, to, steps, renames: [...renames], edits, added, removed, stillRead, drifted, current: cmp(from, to) >= 0 };
65
+ }
66
+
67
+ export function applyUpgrade(root, plan) {
68
+ for (const [file, { text }] of plan.edits) fs.writeFileSync(path.join(root, file), text);
69
+ }
package/src/values.js ADDED
@@ -0,0 +1,204 @@
1
+ // Values: find every design literal in a declaration and say what it is.
2
+ // Pure: no fs. Colours normalise to #rrggbb(aa) and carry OKLab for distance.
3
+
4
+ const NAMED = Object.fromEntries(
5
+ ('aliceblue:f0f8ff antiquewhite:faebd7 aqua:00ffff aquamarine:7fffd4 azure:f0ffff beige:f5f5dc bisque:ffe4c4 ' +
6
+ 'black:000000 blanchedalmond:ffebcd blue:0000ff blueviolet:8a2be2 brown:a52a2a burlywood:deb887 cadetblue:5f9ea0 ' +
7
+ 'chartreuse:7fff00 chocolate:d2691e coral:ff7f50 cornflowerblue:6495ed cornsilk:fff8dc crimson:dc143c cyan:00ffff ' +
8
+ 'darkblue:00008b darkcyan:008b8b darkgoldenrod:b8860b darkgray:a9a9a9 darkgreen:006400 darkgrey:a9a9a9 ' +
9
+ 'darkkhaki:bdb76b darkmagenta:8b008b darkolivegreen:556b2f darkorange:ff8c00 darkorchid:9932cc darkred:8b0000 ' +
10
+ 'darksalmon:e9967a darkseagreen:8fbc8f darkslateblue:483d8b darkslategray:2f4f4f darkslategrey:2f4f4f ' +
11
+ 'darkturquoise:00ced1 darkviolet:9400d3 deeppink:ff1493 deepskyblue:00bfff dimgray:696969 dimgrey:696969 ' +
12
+ 'dodgerblue:1e90ff firebrick:b22222 floralwhite:fffaf0 forestgreen:228b22 fuchsia:ff00ff gainsboro:dcdcdc ' +
13
+ 'ghostwhite:f8f8ff gold:ffd700 goldenrod:daa520 gray:808080 green:008000 greenyellow:adff2f grey:808080 ' +
14
+ 'honeydew:f0fff0 hotpink:ff69b4 indianred:cd5c5c indigo:4b0082 ivory:fffff0 khaki:f0e68c lavender:e6e6fa ' +
15
+ 'lavenderblush:fff0f5 lawngreen:7cfc00 lemonchiffon:fffacd lightblue:add8e6 lightcoral:f08080 lightcyan:e0ffff ' +
16
+ 'lightgoldenrodyellow:fafad2 lightgray:d3d3d3 lightgreen:90ee90 lightgrey:d3d3d3 lightpink:ffb6c1 ' +
17
+ 'lightsalmon:ffa07a lightseagreen:20b2aa lightskyblue:87cefa lightslategray:778899 lightslategrey:778899 ' +
18
+ 'lightsteelblue:b0c4de lightyellow:ffffe0 lime:00ff00 limegreen:32cd32 linen:faf0e6 magenta:ff00ff maroon:800000 ' +
19
+ 'mediumaquamarine:66cdaa mediumblue:0000cd mediumorchid:ba55d3 mediumpurple:9370db mediumseagreen:3cb371 ' +
20
+ 'mediumslateblue:7b68ee mediumspringgreen:00fa9a mediumturquoise:48d1cc mediumvioletred:c71585 ' +
21
+ 'midnightblue:191970 mintcream:f5fffa mistyrose:ffe4e1 moccasin:ffe4b5 navajowhite:ffdead navy:000080 ' +
22
+ 'oldlace:fdf5e6 olive:808000 olivedrab:6b8e23 orange:ffa500 orangered:ff4500 orchid:da70d6 palegoldenrod:eee8aa ' +
23
+ 'palegreen:98fb98 paleturquoise:afeeee palevioletred:db7093 papayawhip:ffefd5 peachpuff:ffdab9 peru:cd853f ' +
24
+ 'pink:ffc0cb plum:dda0dd powderblue:b0e0e6 purple:800080 rebeccapurple:663399 red:ff0000 rosybrown:bc8f8f ' +
25
+ 'royalblue:4169e1 saddlebrown:8b4513 salmon:fa8072 sandybrown:f4a460 seagreen:2e8b57 seashell:fff5ee ' +
26
+ 'sienna:a0522d silver:c0c0c0 skyblue:87ceeb slateblue:6a5acd slategray:708090 slategrey:708090 snow:fffafa ' +
27
+ 'springgreen:00ff7f steelblue:4682b4 tan:d2b48c teal:008080 thistle:d8bfd8 tomato:ff6347 turquoise:40e0d0 ' +
28
+ 'violet:ee82ee wheat:f5deb3 white:ffffff whitesmoke:f5f5f5 yellow:ffff00 yellowgreen:9acd32')
29
+ .split(' ').map((p) => p.split(':')));
30
+
31
+ // Properties whose values may hold a colour.
32
+ export const COLOR_PROP = /^(color|background(-color|-image)?|border(-(top|right|bottom|left|block|inline)(-(start|end))?)?(-color)?|outline(-color)?|fill|stroke|(box|text)-shadow|caret-color|accent-color|text-decoration(-color)?|column-rule(-color)?|stop-color|flood-color|lighting-color|--[\w-]+)$/;
33
+
34
+ // Which scale a length belongs to, by property.
35
+ const LENGTH_CAT = [
36
+ [/^(margin|padding|scroll-margin|scroll-padding)(-(top|right|bottom|left|block|inline)(-(start|end))?)?$|^(gap|row-gap|column-gap|grid-gap|grid-row-gap|grid-column-gap)$|^(inset(-(block|inline)(-(start|end))?)?|top|right|bottom|left)$/, 'space'],
37
+ [/^border(-(top|bottom)-(left|right)|-(start|end)-(start|end))?-radius$/, 'radius'],
38
+ [/^font-size$|^font$/, 'font-size'],
39
+ [/^letter-spacing$/, 'tracking'],
40
+ [/^line-height$/, 'leading'],
41
+ [/^(min-|max-)?(width|height|inline-size|block-size)$|^flex-basis$/, 'size'],
42
+ [/^(border(-(top|right|bottom|left|block|inline))?(-width)?|outline(-width)?|outline-offset)$/, 'border-width'],
43
+ ];
44
+
45
+ export function lengthCategory(prop) {
46
+ for (const [re, cat] of LENGTH_CAT) if (re.test(prop)) return cat;
47
+ return null;
48
+ }
49
+
50
+ // The scales Designrail turns into tokens (others are reported, never tokenised).
51
+ export const SCALES = ['space', 'radius', 'font-size'];
52
+
53
+ export const kebab = (p) => p.startsWith('--') ? p : p.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase()).replace(/^(webkit|moz|ms)-/, '-$1-');
54
+
55
+ // --- colour maths --------------------------------------------------------
56
+
57
+ const clamp01 = (x) => Math.min(1, Math.max(0, x));
58
+ const toLin = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
59
+ const toGam = (c) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
60
+
61
+ export function rgbToOklab([r, g, b]) {
62
+ const R = toLin(r), G = toLin(g), B = toLin(b);
63
+ const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B);
64
+ const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B);
65
+ const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
66
+ return [
67
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
68
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
69
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
70
+ ];
71
+ }
72
+
73
+ export function oklabToRgb([L, a, b]) {
74
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
75
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
76
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
77
+ return [
78
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
79
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
80
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
81
+ ].map((c) => clamp01(toGam(c)));
82
+ }
83
+
84
+ function hslToRgb(h, s, l) {
85
+ h = ((h % 360) + 360) % 360;
86
+ const k = (n) => (n + h / 30) % 12;
87
+ const a = s * Math.min(l, 1 - l);
88
+ return [0, 8, 4].map((n) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)));
89
+ }
90
+
91
+ const num = (s, scale = 1) => (s.endsWith('%') ? parseFloat(s) / 100 : parseFloat(s) / scale);
92
+ const hue = (s) => (s.endsWith('turn') ? parseFloat(s) * 360 : s.endsWith('rad') ? (parseFloat(s) * 180) / Math.PI : parseFloat(s));
93
+
94
+ // A CSS colour string → { hex, rgba:[r,g,b,a] 0..1 } or null.
95
+ export function parseColor(raw) {
96
+ const s = raw.trim().toLowerCase();
97
+ if (s[0] === '#') {
98
+ let h = s.slice(1);
99
+ if (!/^[0-9a-f]+$/.test(h) || ![3, 4, 6, 8].includes(h.length)) return null;
100
+ if (h.length <= 4) h = [...h].map((c) => c + c).join('');
101
+ const v = h.match(/../g).map((x) => parseInt(x, 16) / 255);
102
+ return make(v[0], v[1], v[2], v[3] ?? 1);
103
+ }
104
+ if (NAMED[s]) return parseColor('#' + NAMED[s]);
105
+ const fn = /^(rgba?|hsla?|oklch|oklab)\(([^)]*)\)$/.exec(s);
106
+ if (!fn) return null;
107
+ const parts = fn[2].replace(/[,/]/g, ' ').trim().split(/\s+/);
108
+ if (parts.length < 3 || parts.some((p) => p === 'none' || p.startsWith('var'))) return null;
109
+ const alpha = parts[3] !== undefined ? num(parts[3]) : 1;
110
+ if (fn[1].startsWith('rgb')) return make(...parts.slice(0, 3).map((p) => clamp01(num(p, 255))), alpha);
111
+ if (fn[1].startsWith('hsl')) return make(...hslToRgb(hue(parts[0]), num(parts[1], 100), num(parts[2], 100)), alpha);
112
+ const L = parts[0].endsWith('%') ? num(parts[0]) : parseFloat(parts[0]);
113
+ if (fn[1] === 'oklab') return make(...oklabToRgb([L, num(parts[1], 1), num(parts[2], 1)]), alpha);
114
+ const C = parts[1].endsWith('%') ? num(parts[1]) * 0.4 : parseFloat(parts[1]);
115
+ const H = (hue(parts[2]) * Math.PI) / 180;
116
+ return make(...oklabToRgb([L, C * Math.cos(H), C * Math.sin(H)]), alpha);
117
+ }
118
+
119
+ function make(r, g, b, a) {
120
+ if ([r, g, b, a].some((x) => !Number.isFinite(x))) return null;
121
+ const x = (v) => Math.round(clamp01(v) * 255).toString(16).padStart(2, '0');
122
+ const al = clamp01(a);
123
+ return { hex: '#' + x(r) + x(g) + x(b) + (al < 1 ? x(al) : ''), rgba: [r, g, b, al] };
124
+ }
125
+
126
+ // Facts about a colour for naming and grouping: OKLab, lightness, chroma, hue.
127
+ export function colorFacts(hex) {
128
+ const c = parseColor(hex);
129
+ const lab = rgbToOklab(c.rgba);
130
+ const C = Math.hypot(lab[1], lab[2]);
131
+ const H = ((Math.atan2(lab[2], lab[1]) * 180) / Math.PI + 360) % 360;
132
+ return { hex: c.hex, lab, alpha: c.rgba[3], L: lab[0], C, H };
133
+ }
134
+
135
+ // Perceptual distance (ΔE OK). ~0.02 is barely visible, alpha counts as much.
136
+ export function colorDistance(a, b) {
137
+ const A = typeof a === 'string' ? colorFacts(a) : a;
138
+ const B = typeof b === 'string' ? colorFacts(b) : b;
139
+ return Math.hypot(A.lab[0] - B.lab[0], A.lab[1] - B.lab[1], A.lab[2] - B.lab[2], (A.alpha - B.alpha) * 0.5);
140
+ }
141
+
142
+ // --- finding literals ----------------------------------------------------
143
+
144
+ const blank = (s) => s.replace(/[^\n]/g, ' ');
145
+ const COLOR_RE = /#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|oklch|oklab)\([^()]*\)|\b[a-zA-Z]{3,20}\b/g;
146
+ const LEN_RE = /(?<![\w.#-])-?(?:\d+\.?\d*|\.\d+)(px|rem|em)\b/g;
147
+ const TIME_RE = /(?<![\w.#-])(?:\d+\.?\d*|\.\d+)(ms|s)\b/g;
148
+ const EASE_RE = /\b(?:cubic-bezier|steps)\([^()]*\)/g;
149
+
150
+ // Every literal in one declaration's value. Offsets are into `value`.
151
+ // → [{ kind: 'color'|'length'|'time'|'ease'|'font'|'weight'|'shadow'|'z'|'leading', cat, raw, at, ... }]
152
+ export function literals(prop, value) {
153
+ const out = [];
154
+ if (/^\s*var\(\s*--[\w-]+\s*\)\s*$/.test(value)) return out;
155
+ // Ignore url() contents and the names inside var(); keep var() fallbacks.
156
+ const v = value.replace(/url\([^)]*\)/gi, blank).replace(/var\(\s*--[\w-]+/g, blank);
157
+ if (COLOR_PROP.test(prop)) {
158
+ for (const m of v.matchAll(COLOR_RE)) {
159
+ const word = /^[a-zA-Z]+$/.test(m[0]);
160
+ if (word && !NAMED[m[0].toLowerCase()]) continue;
161
+ const c = parseColor(m[0]);
162
+ if (c) out.push({ kind: 'color', cat: 'color', raw: m[0], at: m.index, hex: c.hex });
163
+ }
164
+ }
165
+ const cat = lengthCategory(prop);
166
+ if (cat || prop.startsWith('--')) {
167
+ // In the `font` shorthand only the size counts, not the line height after `/`.
168
+ const lv = prop === 'font' ? v.replace(/\/\s*[^\s]+/g, blank) : v;
169
+ for (const m of lv.matchAll(LEN_RE)) {
170
+ const n = parseFloat(m[0]);
171
+ const px = m[1] === 'px' ? n : n * 16;
172
+ // 0 and hairlines (≤2px: a rim, an optical nudge) are measurements, not scale steps.
173
+ if ((cat === 'space' || cat === 'radius') && Math.abs(px) <= 2) continue;
174
+ out.push({ kind: 'length', cat: cat ?? 'custom', raw: m[0], at: m.index, px, unit: m[1] });
175
+ }
176
+ }
177
+ if (/^(transition|animation)(-duration|-delay)?$/.test(prop)) {
178
+ for (const m of v.matchAll(TIME_RE)) out.push({ kind: 'time', cat: 'duration', raw: m[0], at: m.index, ms: m[1] === 's' ? parseFloat(m[0]) * 1000 : parseFloat(m[0]) });
179
+ }
180
+ if (/^(transition|animation)(-timing-function)?$/.test(prop)) {
181
+ for (const m of v.matchAll(EASE_RE)) out.push({ kind: 'ease', cat: 'ease', raw: m[0], at: m.index });
182
+ }
183
+ const whole = value.trim();
184
+ const at = value.indexOf(whole);
185
+ if (prop === 'font-family' && !/var\(/.test(whole) && !/^(inherit|initial|unset)$/.test(whole)) out.push({ kind: 'font', cat: 'font', raw: whole, at });
186
+ if (prop === 'font-weight') {
187
+ const w = { normal: 400, bold: 700 }[whole] ?? (/^\d{3}$/.test(whole) ? Number(whole) : null);
188
+ if (w) out.push({ kind: 'weight', cat: 'weight', raw: whole, at, n: w });
189
+ }
190
+ if (prop === 'line-height' && /^\d*\.?\d+$/.test(whole)) out.push({ kind: 'leading', cat: 'leading', raw: whole, at, n: parseFloat(whole) });
191
+ if (prop === 'z-index' && /^-?\d+$/.test(whole)) out.push({ kind: 'z', cat: 'z', raw: whole, at, n: Number(whole) });
192
+ if (/^box-shadow$/.test(prop) && !/var\(|^none$|inherit|initial/.test(whole)) out.push({ kind: 'shadow', cat: 'shadow', raw: whole, at, norm: normShadow(whole) });
193
+ return out;
194
+ }
195
+
196
+ export function normShadow(s) {
197
+ return s.replace(COLOR_RE, (m) => { const c = /^[a-zA-Z]+$/.test(m) && !NAMED[m.toLowerCase()] ? null : parseColor(m); return c ? c.hex : m; })
198
+ .replace(/\s+/g, ' ').trim().toLowerCase();
199
+ }
200
+
201
+ // One declaration's value as a comparable string: case, spacing and colour spelling folded.
202
+ export function normValue(value) {
203
+ return value.trim().replace(/\s+/g, ' ').replace(/\s*([,/()])\s*/g, '$1').replace(/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?)\([^()]*\)/g, (m) => parseColor(m)?.hex ?? m).toLowerCase();
204
+ }
package/src/worker.js ADDED
@@ -0,0 +1,11 @@
1
+ // Worker: analyse its share of files and post the results back.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { parentPort, workerData } from 'node:worker_threads';
5
+ import { analyze } from './sources.js';
6
+
7
+ const { root, files } = workerData;
8
+ parentPort.postMessage(files.map(({ rel, key }) => {
9
+ try { return { rel, key, d: analyze(rel, fs.readFileSync(path.join(root, rel), 'utf8')) }; }
10
+ catch { return { rel, key, d: { rules: [], uses: [], runtime: [], trees: [] } }; }
11
+ }));