ShtukbaseStandard
package file→ .shtukbase/packages/design-tokens/actions/tokenslib.ts

actions/tokenslib.ts

260 lines, 15.7 KB.

  1. // Design tokens in the format of the W3C Design Tokens Community Group (DTCG, https://www.designtokens.org/tr/2025.10/format/):
  2. // read, validate, resolve references and turn into CSS custom properties. The working directory is the project root.
  3. // Settings on /design/tokens.md: source (tokens file), dark (optional file of dark-scheme overrides), out (CSS file),
  4. // prefix (of the custom property names), darkSelector.
  5. import { existsSync, readFileSync } from 'node:fs';
  6. import { join } from 'node:path';
  7. import { readPage } from '../../collections/checks/lib/pages.ts';
  8. export const PAGE = 'design/tokens.md';
  9. export const TYPES = ['color', 'dimension', 'fontFamily', 'fontWeight', 'duration', 'cubicBezier', 'number', 'strokeStyle', 'border', 'transition', 'shadow', 'gradient', 'typography'];
  10. const GROUP_KEYS = new Set(['$type', '$description', '$extensions', '$deprecated', '$extends', '$root']);
  11. const TOKEN_KEYS = new Set(['$value', '$type', '$description', '$extensions', '$deprecated']);
  12. const WEIGHTS: Record<string, number> = {
  13. thin: 100, hairline: 100, 'extra-light': 200, 'ultra-light': 200, light: 300, normal: 400, regular: 400, book: 400,
  14. medium: 500, 'semi-bold': 600, 'demi-bold': 600, bold: 700, 'extra-bold': 800, 'ultra-bold': 800, black: 900, heavy: 900,
  15. 'extra-black': 950, 'ultra-black': 950,
  16. };
  17. const STROKES = ['solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'outset', 'inset'];
  18. const SPACES = ['srgb', 'srgb-linear', 'hsl', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec2020', 'xyz-d65', 'xyz-d50'];
  19. export type Config = { source: string; dark: string; out: string; prefix: string; darkSelector: string };
  20. export function config(root = process.cwd(), over: Partial<Config> = {}): Config {
  21. const p = join(root, PAGE);
  22. const fm = existsSync(p) ? readPage(p).fm : {};
  23. const s = (v: unknown, d: string) => (typeof v === 'string' && v.trim() ? v.trim().replace(/^\/+/, '') : d);
  24. return { source: s(fm.source, 'design/tokens.json'), dark: s(fm.dark, ''), out: s(fm.out, 'design/tokens.css'), prefix: typeof fm.prefix === 'string' ? fm.prefix : '', darkSelector: s(fm.darkSelector, '.dark'), ...over };
  25. }
  26. /** The settings of a style package's tokens (token contract, `/design/contract.md`): `/design/<id>/tokens.json` and
  27. * `tokens.dark.json` build into `/design/<id>/tokens.css`, the dark scheme on `.dark, [data-theme="dark"]`, no prefix. */
  28. export const styleConfig = (id: string): Config => ({
  29. source: `design/${id}/tokens.json`, dark: `design/${id}/tokens.dark.json`, out: `design/${id}/tokens.css`, prefix: '', darkSelector: '.dark, [data-theme="dark"]',
  30. });
  31. export type Token = { path: string; value: unknown; type: string | null; file: string };
  32. const REF = /^\{([^{}]+)\}$/;
  33. const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
  34. /** Every token of a tokens tree, with the type it inherits from its groups. Problems with the tree go to `bad`. */
  35. export function collect(tree: unknown, file: string, bad: string[]): Map<string, Token> {
  36. const out = new Map<string, Token>();
  37. const walk = (node: unknown, path: string[], type: string | null) => {
  38. if (!isObj(node)) { bad.push(`${file}: ${path.join('.') || '(root)'} — not an object`); return; }
  39. const where = path.join('.') || '(root)';
  40. if ('$value' in node) {
  41. for (const k of Object.keys(node)) if (!TOKEN_KEYS.has(k)) bad.push(`${file}: ${where} — extra field ${k} in the token`);
  42. const own = node.$type;
  43. if (own !== undefined && (typeof own !== 'string' || !TYPES.includes(own))) bad.push(`${file}: ${where} — unknown $type ${JSON.stringify(own)}`);
  44. out.set(where, { path: where, value: node.$value, type: typeof own === 'string' && TYPES.includes(own) ? own : type, file });
  45. return;
  46. }
  47. let t = type;
  48. if (node.$type !== undefined) {
  49. if (typeof node.$type !== 'string' || !TYPES.includes(node.$type)) bad.push(`${file}: ${where} — unknown group $type ${JSON.stringify(node.$type)}`);
  50. else t = node.$type;
  51. }
  52. for (const [k, v] of Object.entries(node)) {
  53. if (k.startsWith('$')) { if (!GROUP_KEYS.has(k)) bad.push(`${file}: ${where} — unknown group field ${k}`); continue; }
  54. if (/[{}.]/.test(k)) { bad.push(`${file}: ${[...path, k].join('.')} — a name cannot contain { } or a dot`); continue; }
  55. walk(v, [...path, k], t);
  56. }
  57. };
  58. walk(tree, [], null);
  59. return out;
  60. }
  61. export function readTree(rel: string, root = process.cwd()): { tree: unknown; error: string | null } {
  62. const p = join(root, rel);
  63. if (!existsSync(p)) return { tree: null, error: `${rel}: the file is missing` };
  64. try {
  65. return { tree: JSON.parse(readFileSync(p, 'utf8')), error: null };
  66. } catch (e) {
  67. return { tree: null, error: `${rel}: not JSON — ${(e as Error).message}` };
  68. }
  69. }
  70. /** Final type of a token: its own or its group's, else that of the token it references. */
  71. export function typeOf(t: Token, all: Map<string, Token>, seen = new Set<string>()): string | null {
  72. if (t.type) return t.type;
  73. const m = typeof t.value === 'string' ? REF.exec(t.value) : null;
  74. if (!m || seen.has(t.path)) return null;
  75. seen.add(t.path);
  76. const target = all.get(m[1]);
  77. return target ? typeOf(target, all, seen) : null;
  78. }
  79. const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
  80. const unitValue = (v: unknown, units: string[]) =>
  81. (isObj(v) && num(v.value) && units.includes(String(v.unit))) || (typeof v === 'string' && new RegExp(`^-?\\d*\\.?\\d+(${units.join('|')})$`).test(v)) || v === 0;
  82. /** Problems with one value of a type (sub-values of composites may be references, checked elsewhere). */
  83. export function valueProblem(type: string, v: unknown): string | null {
  84. if (typeof v === 'string' && REF.test(v)) return null;
  85. switch (type) {
  86. case 'color':
  87. if (typeof v === 'string') return /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8}|[0-9a-fA-F]{3})$/.test(v) ? null : 'color is hex (#rrggbb) or an object {colorSpace, components}';
  88. if (!isObj(v) || !SPACES.includes(String(v.colorSpace))) return `color: colorSpace is one of ${SPACES.join(', ')}`;
  89. if (!Array.isArray(v.components) || v.components.length !== 3 || v.components.some((c) => !num(c) && c !== 'none')) return 'color: components are three numbers';
  90. if (v.alpha !== undefined && !(num(v.alpha) && (v.alpha as number) >= 0 && (v.alpha as number) <= 1)) return 'color: alpha from 0 to 1';
  91. return null;
  92. case 'dimension': return unitValue(v, ['px', 'rem']) ? null : 'dimension is {value, unit: px|rem}';
  93. case 'duration': return unitValue(v, ['ms', 's']) ? null : 'duration is {value, unit: ms|s}';
  94. case 'number': return num(v) ? null : 'number';
  95. case 'fontFamily': return typeof v === 'string' || (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string')) ? null : 'font is a string or a list of strings';
  96. case 'fontWeight': return (num(v) && (v as number) >= 1 && (v as number) <= 1000) || (typeof v === 'string' && v in WEIGHTS) ? null : 'weight is a number 1–1000 or a word (bold, regular…)';
  97. case 'cubicBezier': return Array.isArray(v) && v.length === 4 && v.every(num) && [v[0], v[2]].every((x) => x >= 0 && x <= 1) ? null : 'curve is [x1, y1, x2, y2], x from 0 to 1';
  98. case 'strokeStyle': return (typeof v === 'string' && STROKES.includes(v)) || (isObj(v) && Array.isArray(v.dashArray) && typeof v.lineCap === 'string') ? null : `stroke is ${STROKES.join(', ')} or {dashArray, lineCap}`;
  99. case 'border': return fields(v, { color: 'color', width: 'dimension', style: 'strokeStyle' });
  100. case 'transition': return fields(v, { duration: 'duration', delay: 'duration', timingFunction: 'cubicBezier' });
  101. case 'typography': return fields(v, { fontFamily: 'fontFamily', fontSize: 'dimension', fontWeight: 'fontWeight', letterSpacing: 'dimension', lineHeight: 'number' });
  102. case 'shadow': {
  103. const layers = Array.isArray(v) ? v : [v];
  104. for (const l of layers) {
  105. const p = fields(l, { color: 'color', offsetX: 'dimension', offsetY: 'dimension', blur: 'dimension', spread: 'dimension' });
  106. if (p) return p;
  107. }
  108. return null;
  109. }
  110. case 'gradient':
  111. if (!Array.isArray(v) || !v.length) return 'gradient is a list of {color, position}';
  112. for (const s of v) { const p = fields(s, { color: 'color', position: 'number' }); if (p) return p; }
  113. return null;
  114. }
  115. return null;
  116. }
  117. function fields(v: unknown, spec: Record<string, string>): string | null {
  118. if (!isObj(v)) return `composite value is an object with the fields ${Object.keys(spec).join(', ')}`;
  119. for (const [k, t] of Object.entries(spec)) {
  120. if (!(k in v)) return `no field ${k}`;
  121. const p = valueProblem(t, v[k]);
  122. if (p) return `${k}: ${p}`;
  123. }
  124. return null;
  125. }
  126. /** Every reference string inside a value, with the type it must point at (null: any). */
  127. export function refs(type: string | null, v: unknown): { ref: string; type: string | null }[] {
  128. const out: { ref: string; type: string | null }[] = [];
  129. const sub: Record<string, Record<string, string>> = {
  130. border: { color: 'color', width: 'dimension', style: 'strokeStyle' },
  131. transition: { duration: 'duration', delay: 'duration', timingFunction: 'cubicBezier' },
  132. typography: { fontFamily: 'fontFamily', fontSize: 'dimension', fontWeight: 'fontWeight', letterSpacing: 'dimension', lineHeight: 'number' },
  133. shadow: { color: 'color', offsetX: 'dimension', offsetY: 'dimension', blur: 'dimension', spread: 'dimension' },
  134. gradient: { color: 'color', position: 'number' },
  135. };
  136. const visit = (x: unknown, t: string | null) => {
  137. if (typeof x === 'string') { const m = REF.exec(x); if (m) out.push({ ref: m[1], type: t }); return; }
  138. if (Array.isArray(x)) { for (const y of x) visit(y, t && sub[t] ? t : null); return; }
  139. if (isObj(x) && t && sub[t]) for (const [k, kt] of Object.entries(sub[t])) if (k in x) visit(x[k], kt);
  140. };
  141. visit(v, type);
  142. return out;
  143. }
  144. /** All problems of the tokens: structure, types, values, references (missing, wrong type, cycles). */
  145. export function validate(root = process.cwd(), over: Partial<Config> = {}): { problems: string[]; tokens: Map<string, Token>; dark: Map<string, Token> } {
  146. const c = config(root, over);
  147. const problems: string[] = [];
  148. const base = readTree(c.source, root);
  149. if (base.error) return { problems: [base.error], tokens: new Map(), dark: new Map() };
  150. const tokens = collect(base.tree, c.source, problems);
  151. let dark = new Map<string, Token>();
  152. if (c.dark) {
  153. const d = readTree(c.dark, root);
  154. if (d.error) problems.push(d.error);
  155. else {
  156. dark = collect(d.tree, c.dark, problems);
  157. for (const [p, t] of dark) {
  158. if (!tokens.has(p)) problems.push(`${c.dark}: ${p} — no such token in ${c.source}`);
  159. else if (!t.type) t.type = (tokens.get(p) as Token).type; // the dark value has the type of the token it overrides
  160. }
  161. }
  162. }
  163. for (const set of [tokens, dark]) {
  164. for (const t of set.values()) {
  165. const all = set === dark ? new Map([...tokens, ...dark]) : tokens;
  166. const type = typeOf(t, all);
  167. if (!type) { problems.push(`${t.file}: ${t.path} — the type is set neither on the token nor on the group`); continue; }
  168. const p = valueProblem(type, t.value);
  169. if (p) problems.push(`${t.file}: ${t.path} — ${p}`);
  170. for (const r of refs(type, t.value)) {
  171. const target = all.get(r.ref);
  172. if (!target) { problems.push(`${t.file}: ${t.path} — the reference {${r.ref}} leads nowhere`); continue; }
  173. const tt = typeOf(target, all);
  174. if (r.type && tt && tt !== r.type) problems.push(`${t.file}: ${t.path} — the reference {${r.ref}} points to ${tt}, but ${r.type} is needed`);
  175. }
  176. // Cycles: follow whole-value references.
  177. const seen = [t.path];
  178. let cur: Token | undefined = t;
  179. while (cur && typeof cur.value === 'string' && REF.test(cur.value)) {
  180. const next = (REF.exec(cur.value) as RegExpExecArray)[1];
  181. if (seen.includes(next)) { problems.push(`${t.file}: ${t.path} — circular references: ${[...seen, next].join(' → ')}`); break; }
  182. seen.push(next);
  183. cur = all.get(next);
  184. }
  185. }
  186. }
  187. return { problems, tokens, dark };
  188. }
  189. export const varName = (path: string, prefix: string) => `--${prefix}${path.split('.').join('-')}`.replace(/[^\w-]/g, '-').toLowerCase();
  190. function css(type: string | null, v: unknown, prefix: string): string {
  191. if (typeof v === 'string') { const m = REF.exec(v); if (m) return `var(${varName(m[1], prefix)})`; }
  192. const r = (x: unknown, t: string) => css(t, x, prefix);
  193. switch (type) {
  194. case 'color': {
  195. if (typeof v === 'string') return v;
  196. const o = v as { colorSpace: string; components: (number | 'none')[]; alpha?: number; hex?: string };
  197. const a = o.alpha === undefined || o.alpha === 1 ? '' : ` / ${o.alpha}`;
  198. if (o.hex && !a) return o.hex;
  199. const c = o.components.map(String);
  200. if (['hsl', 'hwb'].includes(o.colorSpace)) return `${o.colorSpace}(${c[0]} ${c[1]}% ${c[2]}%${a})`;
  201. if (['lab', 'lch', 'oklab', 'oklch'].includes(o.colorSpace)) return `${o.colorSpace}(${c.join(' ')}${a})`;
  202. return `color(${o.colorSpace} ${c.join(' ')}${a})`;
  203. }
  204. case 'dimension': case 'duration':
  205. return typeof v === 'object' && v ? `${(v as any).value}${(v as any).unit}` : String(v);
  206. case 'fontFamily': return (Array.isArray(v) ? v : [v]).map((f) => (/^[\w-]+$/.test(String(f)) ? String(f) : `"${f}"`)).join(', ');
  207. case 'fontWeight': return String(typeof v === 'string' ? WEIGHTS[v] ?? v : v);
  208. case 'cubicBezier': return `cubic-bezier(${(v as number[]).join(', ')})`;
  209. case 'strokeStyle': return typeof v === 'string' ? v : 'dashed';
  210. case 'border': { const o = v as any; return `${r(o.width, 'dimension')} ${r(o.style, 'strokeStyle')} ${r(o.color, 'color')}`; }
  211. case 'transition': { const o = v as any; return `${r(o.duration, 'duration')} ${r(o.timingFunction, 'cubicBezier')} ${r(o.delay, 'duration')}`; }
  212. case 'shadow':
  213. return (Array.isArray(v) ? v : [v]).map((l: any) => `${l.inset ? 'inset ' : ''}${r(l.offsetX, 'dimension')} ${r(l.offsetY, 'dimension')} ${r(l.blur, 'dimension')} ${r(l.spread, 'dimension')} ${r(l.color, 'color')}`).join(', ');
  214. case 'gradient': return (v as any[]).map((s) => `${r(s.color, 'color')} ${Math.round(Number(s.position) * 1000) / 10}%`).join(', ');
  215. }
  216. return String(v);
  217. }
  218. /** Custom property lines of a set of tokens (typography fans out into one property per field). */
  219. function lines(set: Map<string, Token>, all: Map<string, Token>, prefix: string): string[] {
  220. const out: string[] = [];
  221. for (const t of set.values()) {
  222. const type = typeOf(t, all);
  223. const name = varName(t.path, prefix);
  224. if (type === 'typography' && !(typeof t.value === 'string')) {
  225. const o = t.value as Record<string, unknown>;
  226. const kinds: Record<string, string> = { fontFamily: 'fontFamily', fontSize: 'dimension', fontWeight: 'fontWeight', letterSpacing: 'dimension', lineHeight: 'number' };
  227. for (const [k, kt] of Object.entries(kinds)) if (k in o) out.push(` ${name}-${k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}: ${css(kt, o[k], prefix)};`);
  228. continue;
  229. }
  230. out.push(` ${name}: ${css(type, t.value, prefix)};`);
  231. }
  232. return out;
  233. }
  234. /** The CSS file the tokens give. */
  235. export function build(root = process.cwd(), over: Partial<Config> = {}): { text: string; problems: string[] } {
  236. const c = config(root, over);
  237. const { problems, tokens, dark } = validate(root, over);
  238. if (problems.length) return { text: '', problems };
  239. let text = `/* Built from ${c.source}${c.dark ? ` and ${c.dark}` : ''} by \`shtuk run design-tokens build\`. Do not edit: edit the tokens and build again. */\n:root {\n${lines(tokens, tokens, c.prefix).join('\n')}\n}\n`;
  240. if (dark.size) text += `\n${c.darkSelector} {\n${lines(dark, new Map([...tokens, ...dark]), c.prefix).join('\n')}\n}\n`;
  241. return { text, problems };
  242. }