import-design-system.mjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env node
  2. // import-design-system: builds a design-system file (see references/design-system.md) from a workspace's
  3. // CSS custom properties, Tailwind config and existing HTML pages. Node standard library only.
  4. // Tailwind configs are parsed as text and never executed; dynamic values are skipped and reported.
  5. //
  6. // node import-design-system.mjs <workspace> [--name <name>] [--out <file>] [--from <path>]... [--force] [--stdout]
  7. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  8. import { mkdir, realpath, writeFile } from 'node:fs/promises';
  9. import { basename, dirname, extname, join, relative, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. import {
  12. GENERIC_FAMILIES, colorKey, cssDeclarations, findColors, formatDesignSystem, htmlStyleSources,
  13. inlineDeclarations, lengthPx, normalizeFamily, parseColor, rgbKey, splitFamilies,
  14. } from './design-tokens.mjs';
  15. const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'out', 'coverage', 'vendor', 'design-system', 'target', '__pycache__']);
  16. const TAILWIND = /^tailwind\.config\.(js|cjs|mjs|ts|cts|mts)$/;
  17. const MAX_FILES = 2000;
  18. const MAX_BYTES = 1024 * 1024;
  19. const ROOT_SELECTOR = /(^|[\s,]):root\b|(^|[\s,])html\b|:host\b/;
  20. // Channel-only custom properties (shadcn/ui and friends): `--primary: 221 83% 53%` used as hsl(var(--primary)).
  21. const HSL_CHANNELS = /^-?[\d.]+(?:deg)?\s+[\d.]+%\s+[\d.]+%(?:\s*\/\s*[\d.]+%?)?$/;
  22. const RGB_CHANNELS = /^\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}$/;
  23. // ---------------------------------------------------------------- file discovery
  24. function walk(root, out) {
  25. const stack = [root];
  26. while (stack.length > 0 && out.length < MAX_FILES) {
  27. const dir = stack.pop();
  28. let entries;
  29. try {
  30. entries = readdirSync(dir, { withFileTypes: true });
  31. } catch {
  32. continue;
  33. }
  34. for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
  35. if (entry.name.startsWith('.')) continue;
  36. const path = join(dir, entry.name);
  37. if (entry.isDirectory()) {
  38. if (!SKIP_DIRS.has(entry.name)) stack.push(path);
  39. } else if (entry.isFile() && classify(entry.name)) out.push(path);
  40. }
  41. }
  42. return out;
  43. }
  44. function classify(name) {
  45. if (TAILWIND.test(name)) return 'tailwind';
  46. const ext = extname(name).toLowerCase();
  47. if (ext === '.css' || ext === '.scss') return 'css';
  48. if (ext === '.html' || ext === '.htm') return 'html';
  49. return null;
  50. }
  51. export function discoverSources(workspace, from = []) {
  52. const files = [];
  53. if (from.length === 0) walk(workspace, files);
  54. for (const item of from) {
  55. const path = resolve(workspace, item);
  56. if (!existsSync(path)) continue;
  57. if (statSync(path).isDirectory()) walk(path, files);
  58. else files.push(path);
  59. }
  60. // Stylesheets first so their custom-property names win over Tailwind keys and page literals.
  61. const order = { css: 0, tailwind: 1, html: 2 };
  62. return [...new Set(files)]
  63. .filter((path) => classify(basename(path)) && statSync(path).size <= MAX_BYTES)
  64. .sort((a, b) => order[classify(basename(a))] - order[classify(basename(b))] || a.localeCompare(b));
  65. }
  66. // ---------------------------------------------------------------- tailwind (static parse, never executed)
  67. const UNKNOWN = Symbol('unknown');
  68. const WORD = /(?:[A-Za-z_$][\w$]*|\d[\d._]*(?:e[+-]?\d+)?|\.\.\.|=>)/y;
  69. function tokenize(source) {
  70. const tokens = [];
  71. let i = 0;
  72. while (i < source.length) {
  73. const c = source[i];
  74. if (/\s/.test(c)) { i += 1; continue; }
  75. if (source.startsWith('//', i)) { i = source.indexOf('\n', i); if (i < 0) break; continue; }
  76. if (source.startsWith('/*', i)) { const end = source.indexOf('*/', i + 2); i = end < 0 ? source.length : end + 2; continue; }
  77. if (c === '"' || c === "'" || c === '`') {
  78. let j = i + 1;
  79. let value = '';
  80. let dynamic = false;
  81. while (j < source.length && source[j] !== c) {
  82. if (source[j] === '\\') { value += source[j + 1] ?? ''; j += 2; continue; }
  83. if (c === '`' && source.startsWith('${', j)) dynamic = true;
  84. value += source[j];
  85. j += 1;
  86. }
  87. tokens.push({ type: dynamic ? 'dynamic' : 'string', value });
  88. i = j + 1;
  89. continue;
  90. }
  91. WORD.lastIndex = i;
  92. const word = WORD.exec(source);
  93. if (word) {
  94. tokens.push({ type: /^[\d]/.test(word[0]) ? 'number' : /^[A-Za-z_$]/.test(word[0]) ? 'ident' : 'punct', value: word[0] });
  95. i += word[0].length;
  96. continue;
  97. }
  98. tokens.push({ type: 'punct', value: c });
  99. i += 1;
  100. }
  101. return tokens;
  102. }
  103. class LiteralParser {
  104. constructor(tokens, skipped) {
  105. this.tokens = tokens;
  106. this.pos = 0;
  107. this.skipped = skipped;
  108. }
  109. peek() { return this.tokens[this.pos]; }
  110. is(value) { return this.peek()?.type === 'punct' && this.peek().value === value; }
  111. // Skips one expression we do not understand (function, identifier, call, spread target...).
  112. skipExpression(label) {
  113. let depth = 0;
  114. const start = this.pos;
  115. while (this.pos < this.tokens.length) {
  116. const token = this.peek();
  117. if (token.type === 'punct') {
  118. if ('([{'.includes(token.value)) depth += 1;
  119. else if (')]}'.includes(token.value)) { if (depth === 0) break; depth -= 1; }
  120. else if (token.value === ',' && depth === 0) break;
  121. }
  122. this.pos += 1;
  123. }
  124. if (this.pos > start) this.skipped.push(label);
  125. return UNKNOWN;
  126. }
  127. value(label) {
  128. const token = this.peek();
  129. if (!token) return UNKNOWN;
  130. if (token.type === 'string' || token.type === 'number') {
  131. // A literal followed by an operator (`'a' + b`) is an expression we skip.
  132. const next = this.tokens[this.pos + 1];
  133. if (next && next.type === 'punct' && !',}]'.includes(next.value)) return this.skipExpression(label);
  134. this.pos += 1;
  135. return String(token.value);
  136. }
  137. if (this.is('{')) return this.object(label);
  138. if (this.is('[')) return this.array(label);
  139. return this.skipExpression(label);
  140. }
  141. object(label) {
  142. const result = {};
  143. this.pos += 1;
  144. while (this.pos < this.tokens.length && !this.is('}')) {
  145. if (this.is('...')) { this.pos += 1; this.skipExpression(`${label}.(spread)`); }
  146. else {
  147. const key = this.peek();
  148. if (key.type === 'ident' || key.type === 'string' || key.type === 'number') {
  149. this.pos += 1;
  150. if (this.is(':')) { this.pos += 1; result[key.value] = this.value(`${label}.${key.value}`); }
  151. else this.skipExpression(`${label}.${key.value}`);
  152. } else this.skipExpression(`${label}.(computed)`);
  153. }
  154. if (this.is(',')) this.pos += 1;
  155. else if (!this.is('}')) this.pos += 1;
  156. }
  157. this.pos += 1;
  158. return result;
  159. }
  160. array(label) {
  161. const result = [];
  162. this.pos += 1;
  163. while (this.pos < this.tokens.length && !this.is(']')) {
  164. result.push(this.value(`${label}[${result.length}]`));
  165. if (this.is(',')) this.pos += 1;
  166. else if (!this.is(']')) this.pos += 1;
  167. }
  168. this.pos += 1;
  169. return result;
  170. }
  171. }
  172. /** Reads `theme` (and `theme.extend`) from a Tailwind config's source text. */
  173. export function parseTailwindTheme(source) {
  174. const tokens = tokenize(source);
  175. const skipped = [];
  176. for (let i = 0; i + 2 < tokens.length; i += 1) {
  177. if (tokens[i].value === 'theme' && tokens[i + 1].value === ':' && tokens[i + 2].value === '{') {
  178. const parser = new LiteralParser(tokens, skipped);
  179. parser.pos = i + 2;
  180. const theme = parser.object('theme');
  181. const extend = theme.extend && theme.extend !== UNKNOWN ? theme.extend : {};
  182. const pick = (key) => [theme[key], extend[key]].filter((part) => part && part !== UNKNOWN && typeof part === 'object');
  183. return { colors: pick('colors'), fontFamily: pick('fontFamily'), spacing: pick('spacing'), borderRadius: pick('borderRadius'), skipped };
  184. }
  185. }
  186. return { colors: [], fontFamily: [], spacing: [], borderRadius: [], skipped };
  187. }
  188. function flatten(object, prefix, out) {
  189. for (const [key, value] of Object.entries(object)) {
  190. const name = key === 'DEFAULT' ? prefix : prefix ? `${prefix}-${key}` : key;
  191. if (value && typeof value === 'object' && !Array.isArray(value)) flatten(value, name, out);
  192. else out.push([name, value]);
  193. }
  194. return out;
  195. }
  196. function quoteFamily(family) {
  197. return GENERIC_FAMILIES.has(family.toLowerCase()) || /^[\w-]+$/.test(family) ? family : `"${family}"`;
  198. }
  199. // ---------------------------------------------------------------- collection
  200. function emptySystem() {
  201. return { colors: [], fonts: [], spacing: [], radii: [] };
  202. }
  203. function classifyCustomProperty(name, value) {
  204. const colors = findColors(value);
  205. if (colors.length === 1 && colors[0].text.length === value.trim().length) return 'colors';
  206. const lower = name.toLowerCase();
  207. if (/font|family|typeface/.test(lower) && !/size|weight|leading|line|height|tracking|spacing/.test(lower) && /[a-z]/i.test(value)) return 'fonts';
  208. if (/radius|rounded|corner/.test(lower) && lengthPx(value) !== null) return 'radii';
  209. if (/space|spacing|gap|gutter|pad|margin|inset/.test(lower) && lengthPx(value) !== null) return 'spacing';
  210. return null;
  211. }
  212. function resolveVars(value, defined, depth = 0) {
  213. if (depth > 5 || !value.includes('var(')) return value;
  214. const resolved = value.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*))?\)/g, (whole, name, fallback) => defined.get(name) ?? fallback?.trim() ?? whole);
  215. return resolveVars(resolved, defined, depth + 1);
  216. }
  217. /**
  218. * Builds a design system from source files. Returns { system, report } where report lists what was read,
  219. * skipped and inferred, for the usage notes and the CLI summary.
  220. */
  221. export function importDesignSystem(workspace, files, name) {
  222. const system = emptySystem();
  223. const rootVars = new Map();
  224. const sources = new Set();
  225. const skipped = [];
  226. const literalColors = new Map();
  227. const literalFamilies = new Map();
  228. const literalSpacing = new Map();
  229. const rel = (path) => relative(workspace, path).split('\\').join('/') || basename(path);
  230. let tailwindUsed = false;
  231. // A token redefined with another value (a dark theme, a second stylesheet) is kept under a qualified label.
  232. const add = (section, token, value, use, source) => {
  233. const sameName = system[section].find((entry) => entry.token === token);
  234. if (sameName && sameName.value === value) return;
  235. const label = sameName ? `${token} (${use || source})` : token;
  236. if (system[section].some((entry) => entry.token === label)) return;
  237. system[section].push({ token: label, value, use });
  238. sources.add(source);
  239. };
  240. const readCss = (css, source) => {
  241. const decls = cssDeclarations(css);
  242. const defined = new Map();
  243. for (const decl of decls) if (decl.property.startsWith('--') && !defined.has(decl.property)) defined.set(decl.property, decl.value);
  244. for (const decl of decls) {
  245. if (decl.property.startsWith('--')) {
  246. let value = resolveVars(decl.value, defined).replace(/\s*!important$/, '').trim();
  247. const root = ROOT_SELECTOR.test(decl.selector);
  248. if (root && !rootVars.has(decl.property)) rootVars.set(decl.property, value);
  249. let use = root ? '' : decl.selector;
  250. if (HSL_CHANNELS.test(value) || RGB_CHANNELS.test(value)) {
  251. use = [use, `channels; use as ${HSL_CHANNELS.test(value) ? 'hsl' : 'rgb'}(var(${decl.property}))`].filter(Boolean).join('; ');
  252. value = `${HSL_CHANNELS.test(value) ? 'hsl' : 'rgb'}(${value})`;
  253. }
  254. const section = classifyCustomProperty(decl.property, value);
  255. if (section) add(section, decl.property, value, use, source);
  256. } else countLiterals(decl, source);
  257. }
  258. };
  259. const countLiterals = (decl, source) => {
  260. for (const found of findColors(decl.value)) bump(literalColors, colorKey(found.color), found.text, source);
  261. if (decl.property === 'font-family' && !decl.value.includes('var(')) {
  262. const primary = splitFamilies(decl.value).find((family) => !GENERIC_FAMILIES.has(normalizeFamily(family)));
  263. if (primary) bump(literalFamilies, normalizeFamily(primary), decl.value.replace(/\s*!important$/, ''), source);
  264. }
  265. if (/^(margin|padding|gap|row-gap|column-gap)/.test(decl.property) && !/var\(|calc\(/.test(decl.value)) {
  266. for (const part of decl.value.split(/\s+/)) {
  267. const px = lengthPx(part);
  268. if (px !== null) bump(literalSpacing, String(px), `${px}px`, source);
  269. }
  270. }
  271. };
  272. // Tailwind values that point at stylesheet variables (`hsl(var(--primary) / <alpha-value>)`) resolve to them.
  273. const viaVars = (raw) => (typeof raw === 'string' ? resolveVars(raw.replace(/\s*\/\s*<alpha-value>\s*/, ''), rootVars) : raw);
  274. for (const file of files) {
  275. const kind = classify(basename(file));
  276. const source = rel(file);
  277. const text = readFileSync(file, 'utf8');
  278. if (kind === 'css') readCss(text, source);
  279. else if (kind === 'html') {
  280. const styles = htmlStyleSources(text);
  281. for (const sheet of styles.sheets) readCss(sheet.css, source);
  282. for (const attribute of styles.attributes) for (const decl of inlineDeclarations(attribute.body)) countLiterals(decl, source);
  283. } else if (kind === 'tailwind') {
  284. const theme = parseTailwindTheme(text);
  285. tailwindUsed = true;
  286. skipped.push(...theme.skipped.map((label) => `${source}: ${label} (not a static literal; not executed)`));
  287. for (const part of theme.colors) {
  288. for (const [key, raw] of flatten(part, '', [])) {
  289. const value = viaVars(raw);
  290. if (typeof value === 'string' && parseColor(value)) add('colors', key, value, `tailwind colors${raw !== value ? ` (${raw})` : ''}`, source);
  291. else if (value !== UNKNOWN) skipped.push(`${source}: colors.${key} = ${String(value)} (not a color literal)`);
  292. }
  293. }
  294. for (const part of theme.fontFamily) {
  295. for (const [key, value] of Object.entries(part)) {
  296. const list = Array.isArray(value) ? (Array.isArray(value[0]) ? value[0] : value) : typeof value === 'string' ? value.split(',') : [];
  297. const families = list.filter((family) => typeof family === 'string').map((family) => family.trim().replace(/^['"]|['"]$/g, ''));
  298. if (families.length > 0) add('fonts', `font-${key}`, families.map(quoteFamily).join(', '), 'tailwind fontFamily', source);
  299. }
  300. }
  301. for (const [section, prefix, entries] of [['spacing', 'spacing', theme.spacing], ['radii', 'rounded', theme.borderRadius]]) {
  302. for (const part of entries) {
  303. for (const [key, raw] of flatten(part, '', [])) {
  304. const value = viaVars(raw);
  305. const label = `${section === 'radii' ? 'borderRadius' : 'spacing'}.${key || 'DEFAULT'}`;
  306. if (typeof value === 'string' && lengthPx(value) !== null) add(section, key ? `${prefix}-${key}` : prefix, value, `tailwind ${label}${raw !== value ? ` (${raw})` : ''}`, source);
  307. else if (value !== UNKNOWN) skipped.push(`${source}: ${label} = ${String(raw)} (not a plain length)`);
  308. }
  309. }
  310. }
  311. }
  312. }
  313. // Literal values used repeatedly but never named become candidates, so lint matches the existing pages.
  314. const named = system.colors.length + system.fonts.length > 0;
  315. const minimum = named ? 2 : 1;
  316. const coveredRgb = new Set(system.colors.map((entry) => rgbKey(parseColor(entry.value))));
  317. [...literalColors.entries()]
  318. .filter(([key, entry]) => entry.count >= minimum && !coveredRgb.has(rgbKey(parseColor(key))))
  319. .sort((a, b) => b[1].count - a[1].count)
  320. .slice(0, 16)
  321. .forEach(([, entry], index) => add('colors', `literal-color-${index + 1}`, entry.value, `literal, used ${entry.count}x`, [...entry.sources][0]));
  322. const coveredFamilies = new Set(system.fonts.flatMap((entry) => splitFamilies(entry.value).map(normalizeFamily)));
  323. [...literalFamilies.entries()]
  324. .filter(([family, entry]) => entry.count >= minimum && !coveredFamilies.has(family))
  325. .sort((a, b) => b[1].count - a[1].count)
  326. .slice(0, 4)
  327. .forEach(([, entry], index) => add('fonts', `literal-font-${index + 1}`, entry.value, `literal, used ${entry.count}x`, [...entry.sources][0]));
  328. // A Tailwind project spaces with the default scale, which a few repeated literals would misrepresent.
  329. if (system.spacing.length === 0 && !tailwindUsed) {
  330. [...literalSpacing.entries()]
  331. .filter(([, entry]) => entry.count >= (named ? 3 : 1))
  332. .sort((a, b) => Number(a[0]) - Number(b[0]))
  333. .slice(0, 12)
  334. .forEach(([px, entry]) => add('spacing', `literal-space-${px}`, entry.value, `literal, used ${entry.count}x`, [...entry.sources][0]));
  335. }
  336. const usage = [
  337. `Imported by import-design-system.mjs from ${sources.size} file(s); review the roles before relying on it.`,
  338. '- Use these tokens only. Where a token is a CSS custom property, define it in `:root` and reference it as `var(--name)`.',
  339. '- `literal` tokens were used repeatedly in the source without a name; keep, rename or delete them.',
  340. ];
  341. if (tailwindUsed) usage.push('- Tailwind tokens keep the theme key path: `primary-500` is `theme.colors.primary.500`. The config was read as text, never executed. Tailwind\'s built-in palette and spacing scale are not listed; add the steps the design should use.');
  342. if (skipped.length > 0) usage.push(`- Skipped ${skipped.length} dynamic or non-literal value(s); add them by hand if they matter:`, ...skipped.slice(0, 12).map((line) => ` - ${line}`));
  343. return { system: { name, sources: [...sources].sort(), ...system, usage: usage.join('\n') }, report: { files: files.length, sources: sources.size, skipped } };
  344. }
  345. function bump(map, key, value, source) {
  346. const entry = map.get(key) ?? { value, count: 0, sources: new Set() };
  347. entry.count += 1;
  348. entry.sources.add(source);
  349. map.set(key, entry);
  350. }
  351. export function slugName(name) {
  352. const slug = name
  353. .normalize('NFKC')
  354. .toLowerCase()
  355. .replace(/[^\p{L}\p{N}._-]+/gu, '-')
  356. .replace(/^[-.]+|[-.]+$/g, '')
  357. .slice(0, 60);
  358. return slug || 'design-system';
  359. }
  360. // ---------------------------------------------------------------- CLI
  361. function parseArgs(argv) {
  362. const options = { from: [], force: false, stdout: false };
  363. const positional = [];
  364. for (let i = 0; i < argv.length; i += 1) {
  365. const arg = argv[i];
  366. if (arg === '--name' || arg === '--out' || arg === '--from') {
  367. const value = argv[i + 1];
  368. if (value === undefined) throw new Error(`${arg} needs a value`);
  369. if (arg === '--from') options.from.push(value);
  370. else options[arg.slice(2)] = value;
  371. i += 1;
  372. } else if (arg === '--force') options.force = true;
  373. else if (arg === '--stdout') options.stdout = true;
  374. else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`);
  375. else positional.push(arg);
  376. }
  377. if (positional.length !== 1) throw new Error('expected exactly one workspace directory');
  378. return { workspace: resolve(positional[0]), ...options };
  379. }
  380. async function main(argv) {
  381. let options;
  382. try {
  383. options = parseArgs(argv);
  384. } catch (error) {
  385. console.error(`${error.message}\nUsage: node import-design-system.mjs <workspace> [--name <name>] [--out <file>] [--from <path>]... [--force] [--stdout]`);
  386. return 2;
  387. }
  388. if (!existsSync(options.workspace) || !statSync(options.workspace).isDirectory()) {
  389. console.error(`Not a directory: ${options.workspace}`);
  390. return 2;
  391. }
  392. const name = slugName(options.name ?? basename(options.workspace));
  393. const files = discoverSources(options.workspace, options.from);
  394. const { system, report } = importDesignSystem(options.workspace, files, name);
  395. const markdown = formatDesignSystem(system);
  396. const counts = `${system.colors.length} colors, ${system.fonts.length} fonts, ${system.spacing.length} spacing, ${system.radii.length} radii from ${report.sources}/${report.files} file(s); ${report.skipped.length} skipped`;
  397. if (options.stdout) {
  398. process.stdout.write(markdown);
  399. console.error(counts);
  400. return 0;
  401. }
  402. const out = resolve(options.workspace, options.out ?? join('design-system', `${name}.md`));
  403. await mkdir(dirname(out), { recursive: true });
  404. // 不带 --force 时排他创建:存在检查与写入合成一步,并发导入同一路径只有一个能成功。
  405. try {
  406. await writeFile(out, markdown, { encoding: 'utf8', flag: options.force ? 'w' : 'wx' });
  407. } catch (error) {
  408. if (error?.code !== 'EEXIST') throw error;
  409. console.error(`${out} already exists; pass --force to replace it or --name for another system.`);
  410. return 1;
  411. }
  412. console.log(out);
  413. console.log(counts);
  414. return 0;
  415. }
  416. const entry = process.argv[1] === undefined ? undefined : await realpath(process.argv[1]).catch(() => undefined);
  417. if (entry !== undefined && entry === (await realpath(fileURLToPath(import.meta.url)))) process.exitCode = await main(process.argv.slice(2));