@rickycourtes/designrail 0.2.2 → 0.3.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/cli.js CHANGED
@@ -102,6 +102,13 @@ export async function main(argv) {
102
102
  return;
103
103
  }
104
104
 
105
+ if ((cmd === 'check' && !flags['--install-hook']) || cmd === 'audit') {
106
+ const { loadConfig, loosenedError } = await import('./project.js');
107
+ let msg;
108
+ try { msg = loosenedError(loadConfig(root)); } catch (e) { fail(e.message); }
109
+ if (msg) fail(msg);
110
+ }
111
+
105
112
  const model = await load();
106
113
 
107
114
  if (cmd === 'scan') {
package/src/contract.js CHANGED
@@ -25,6 +25,8 @@ export const CONTRACT = [
25
25
  { name: '--success', group: 'colour', role: 'any', about: 'Something worked.', derive: '#16a34a' },
26
26
  { name: '--warning', group: 'colour', role: 'any', about: 'Careful.', derive: '#d97706' },
27
27
  { name: '--focus', group: 'colour', role: 'any', about: 'The keyboard focus ring.', derive: 'var(--accent)' },
28
+ { name: '--focus-ring', group: 'colour', role: 'border', about: 'The focus outline (`none` for a glow only).', derive: '2px solid var(--focus)' },
29
+ { name: '--focus-glow', group: 'colour', role: 'any', about: 'A focus glow, as a box-shadow (`none` by default).', derive: 'none' },
28
30
  // type
29
31
  { name: '--font-ui', group: 'type', about: 'Every label and paragraph.', derive: "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" },
30
32
  { name: '--font-display', group: 'type', about: 'Headings.', derive: 'var(--font-ui)' },
package/src/init.js CHANGED
@@ -8,12 +8,29 @@ import { isTokenFile } from './model.js';
8
8
  import { analyze } from './sources.js';
9
9
  import { isSpecimenPage } from './specimens.js';
10
10
 
11
- const RULES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'rules', 'DESIGN.md');
11
+ export const BASE_RULES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'rules', 'DESIGN.md');
12
+
13
+ // The project's own rules file: it extends the base and starts empty.
14
+ export const PROJECT_RULES = `Extends @rickycourtes/designrail/rules/DESIGN.md
15
+
16
+ # Design rules
17
+
18
+ designrail's base rules (\`node_modules/@rickycourtes/designrail/rules/DESIGN.md\`)
19
+ hold for this project as written. This file only adds to them: a rule here
20
+ says something the base doesn't, and never reuses a base \`{id}\`
21
+ (\`designrail check\` fails that: rules-override). End each bullet with a tag
22
+ \`{id · checks}\` as the base does: \`check\`, \`audit\` or \`eye\`.
23
+
24
+ ## Project rules
25
+
26
+ `;
12
27
 
13
28
  const AGENT_BLOCK = `
14
29
  ## Design system (designrail)
15
30
 
16
- Before touching UI, read \`DESIGN.md\`. Build from the parts in \`{parts}/\` and
31
+ Before touching UI, read both rule files: designrail's base rules
32
+ (\`node_modules/@rickycourtes/designrail/rules/DESIGN.md\`) and this project's
33
+ \`DESIGN.md\`, which extends them. Build from the parts in \`{parts}/\` and
17
34
  the tokens in {tokens}, on top of the designrail foundation (\`@rickycourtes/designrail/foundation.css\`). Restyle a foundation part with its knobs on a variant, never by editing it; never type a colour, spacing, radius or font size by
18
35
  hand. Run \`npx designrail check\` before committing; \`npx designrail trace <selector>\`
19
36
  shows where a value comes from. A part the foundation lacks: write it in \`{parts}/\` from tokens; \`npx designrail eject <part>\` only to own a copy.
@@ -37,7 +54,7 @@ export function init(root, { agents = false, force = false } = {}) {
37
54
  done.push(`designrail.config.json${found.length ? ` (tokens found in ${found.join(', ')})` : ''}${pages.length ? ` (specimens: ${pages.join(', ')})` : ''}`);
38
55
  }
39
56
  const rulesPath = path.join(root, 'DESIGN.md');
40
- if (!fs.existsSync(rulesPath) || force) { fs.copyFileSync(RULES, rulesPath); done.push('DESIGN.md'); }
57
+ if (!fs.existsSync(rulesPath) || force) { fs.writeFileSync(rulesPath, PROJECT_RULES); done.push('DESIGN.md'); }
41
58
  if (agents) {
42
59
  const target = ['CLAUDE.md', 'AGENTS.md'].map((f) => path.join(root, f)).find((f) => fs.existsSync(f)) ?? path.join(root, 'CLAUDE.md');
43
60
  const now = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : '';
package/src/model.js CHANGED
@@ -44,9 +44,9 @@ export function buildModel(project) {
44
44
  // A var() in a plain JS file may be a string in a test or a tool: it
45
45
  // counts as a read (unused) but never fails unresolved or primitive-direct.
46
46
  const js = JS_EXT.test(f.path);
47
- for (const [name, line, fallback] of f.uses) {
47
+ for (const [name, line, fallback, quoted] of f.uses) {
48
48
  if (!uses.has(name)) uses.set(name, []);
49
- uses.get(name).push({ file: f.path, line, inTokens, js, fallback: Boolean(fallback) });
49
+ uses.get(name).push({ file: f.path, line, inTokens, js: js || Boolean(quoted), fallback: Boolean(fallback) });
50
50
  }
51
51
  for (const r of f.rules) {
52
52
  if (r.sel === '@font-face') continue;
package/src/project.js CHANGED
@@ -34,7 +34,7 @@ export const DEFAULT_CONFIG = {
34
34
  allowPrimitives: ['--space-', '--radius-', '--font-size-'],
35
35
  // Custom properties set from JS at runtime (resolve without a CSS definition).
36
36
  runtimeTokens: [],
37
- rules: { hardcoded: 'error', unresolved: 'error', 'primitive-direct': 'warn', 'duplicate-block': 'error', unused: 'warn', 'tracked-caps': 'warn', contract: 'warn', 'part-restyle': 'warn' },
37
+ rules: { hardcoded: 'error', unresolved: 'error', 'primitive-direct': 'warn', 'duplicate-block': 'error', unused: 'warn', 'tracked-caps': 'warn', contract: 'warn', 'part-restyle': 'warn', 'rules-override': 'error' },
38
38
  maxFileBytes: 1_500_000,
39
39
  // Rule blocks count as duplicates only when they share this many declarations.
40
40
  duplicates: { minDeclarations: 3 },
@@ -48,9 +48,33 @@ export function loadConfig(root) {
48
48
  }
49
49
  const cfg = { ...DEFAULT_CONFIG, ...user, rules: { ...DEFAULT_CONFIG.rules, ...(user.rules ?? {}) }, duplicates: { ...DEFAULT_CONFIG.duplicates, ...(user.duplicates ?? {}) } };
50
50
  cfg.exists = fs.existsSync(file);
51
+ cfg.loosened = loosened(user);
51
52
  return cfg;
52
53
  }
53
54
 
55
+ // A project can turn a foundation rule up, never down: what in its config
56
+ // is laxer than DEFAULT_CONFIG. `check` and `audit` refuse to run on it.
57
+ const LEVEL = { off: 0, warn: 1, error: 2 };
58
+ function loosened(user) {
59
+ const out = [];
60
+ for (const [rule, level] of Object.entries(user.rules ?? {})) {
61
+ const base = DEFAULT_CONFIG.rules[rule];
62
+ if (base && (LEVEL[level] ?? 0) < LEVEL[base]) out.push(`rules.${rule} ${JSON.stringify(level)}`);
63
+ }
64
+ if (user.semanticOnly === false) out.push('semanticOnly false');
65
+ for (const p of user.allowPrimitives ?? []) if (!DEFAULT_CONFIG.allowPrimitives.includes(p)) out.push(`allowPrimitives ${JSON.stringify(p)}`);
66
+ const min = user.duplicates?.minDeclarations;
67
+ if (min !== undefined && !(min <= DEFAULT_CONFIG.duplicates.minDeclarations)) out.push(`duplicates.minDeclarations ${min}`);
68
+ return out;
69
+ }
70
+
71
+ // The one line `check` and `audit` exit 2 with, or null when nothing loosens.
72
+ export function loosenedError(cfg) {
73
+ const l = cfg.loosened ?? [];
74
+ if (!l.length) return null;
75
+ return `designrail.config.json: ${l.join(', ')} ${l.length === 1 ? 'loosens a foundation rule' : 'loosen foundation rules'}; a project can turn a rule up, never down`;
76
+ }
77
+
54
78
  // Merge keys into designrail.config.json (created when missing).
55
79
  export function saveConfig(root, patch) {
56
80
  const file = path.join(root, 'designrail.config.json');
package/src/sources.js CHANGED
@@ -136,7 +136,13 @@ export function analyze(path, text) {
136
136
  // Custom properties read, and set at runtime (setProperty / style vars).
137
137
  const uses = [];
138
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]))];
139
+ const setters = [...script.matchAll(/(?:setProperty|style\.setProperty|live)\(\s*[^,]*?['"](--[\w-]+)['"]/g), ...script.matchAll(/['"](--[\w-]+)['"]\s*:/g)];
140
+ const runtime = [...new Set(setters.map((m) => m[1]))];
141
+ // A quoted name script reads (getPropertyValue('--x'), tok('--x')) is a use:
142
+ // it keeps the token off `unused`, and like a var() in JS never fails
143
+ // unresolved or primitive-direct (the 4th field marks it).
144
+ const set = new Set(setters.map((m) => m.index + m[0].lastIndexOf(m[1]) - 1));
145
+ for (const m of script.matchAll(/(['"`])(--[\w-]+)\1(?!\s*:)/g)) if (!set.has(m.index)) uses.push([m[2], lineAt(starts, m.index), 0, 1]);
140
146
 
141
147
  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
148
  ? markupTrees(text, starts, path) : [];
package/src/tokens.js CHANGED
@@ -49,13 +49,17 @@ export function tokenIndex(model) {
49
49
 
50
50
  // Primitive: a token holding a literal, read by semantic tokens. A project with
51
51
  // no semantic layer has no primitives in this sense (everything is the API).
52
- // A literal token counts as a primitive when it lives in a primitives file or
53
- // another token is built on it, or it is a foundation literal; a contract
54
- // name is always API, never primitive.
52
+ // A literal token counts as a primitive when it is a foundation literal or
53
+ // lives in a primitives file. A project with no primitives file has only
54
+ // its literals that another token is built on. A contract name is always
55
+ // API, never primitive. With a primitives file, a literal in the semantic
56
+ // file that other tokens compose (`--safe-t`, `--icon-stroke`) is API.
55
57
  export function primitivesOf(tokens) {
56
58
  if (!tokens.some((t) => t.semantic)) return new Set();
57
59
  const api = new Set(CONTRACT.map((c) => c.name));
60
+ const isPrimFile = (t) => !t.external && /primitive/i.test(t.file);
61
+ const split = tokens.some(isPrimFile);
58
62
  const read = new Set(tokens.filter((t) => t.semantic).flatMap((t) => [...t.raw.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1])));
59
63
  // The foundation's own literals (--gray-950, --blue-500) are its primitives.
60
- return new Set(tokens.filter((t) => !t.semantic && !api.has(t.name) && (t.external || /primitive/i.test(t.file) || read.has(t.name))).map((t) => t.name));
64
+ return new Set(tokens.filter((t) => !t.semantic && !api.has(t.name) && (t.external || isPrimFile(t) || (!split && read.has(t.name)))).map((t) => t.name));
61
65
  }