файл пакета→ .shtukbase/packages/icons/lib/registry.ts
lib/registry.ts
177 строк, 9.4 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // The icon registry of a set (the convention /icons/conventions/icon-set.md): one JSON file per set, one record per
- // icon, so the same meaning keeps one icon and agents reuse before they draw. Pure parts take data; `loadSets` reads.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- export type IconRecord = {
- name: string; // kebab-case; the Lucide name where Lucide has the concept
- file: string; // the flat drawing, from the project root
- description: string; // one line: what it draws
- use: string; // where it fits
- avoid?: string; // where it does not
- aliases?: string[]; // words to find it by
- group?: string; // the colour group
- added?: { date?: string; by?: string; from?: string; why?: string };
- };
- export type Registry = { version?: number; set?: string; prefix?: string; viewBox?: string; style?: string; icons: IconRecord[] };
- export type IconSet = { id: string; path: string; dir: string; registry: Registry };
- export const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
- /** The rules for agents (the owner, 29.11.2026); the prompt prints them and the convention quotes them. */
- export const REUSE_RULES = [
- 'Search the registry by meaning and by aliases before you draw.',
- 'Reuse when the meaning matches: the same thing gets the same icon, in every package.',
- 'Draw a new icon only when no record means the same thing, and say in its record why the near ones did not fit.',
- 'One meaning has one icon; one icon is not reused for things that only look alike.',
- 'The balance: fewer than one new icon per few packages is normal; a new icon for a synonym is a mistake.',
- ];
- /** Every registry under /design/<set>/registry.json, or the ones the settings name (`sets:`). */
- export function loadSets(root: string, only: string[] = []): { sets: IconSet[]; errors: string[] } {
- const errors: string[] = [];
- const paths = only.length ? only : (existsSync(join(root, 'design')) ? readdirSync(join(root, 'design')).sort()
- .filter((n) => !n.startsWith('.') && statSync(join(root, 'design', n)).isDirectory() && existsSync(join(root, 'design', n, 'registry.json')))
- .map((n) => `/design/${n}/registry.json`) : []);
- const sets: IconSet[] = [];
- for (const p of paths) {
- const abs = join(root, p.replace(/^\/+/, ''));
- if (!existsSync(abs)) { errors.push(`${p}: no such registry`); continue; }
- try {
- const reg = JSON.parse(readFileSync(abs, 'utf8')) as Registry;
- if (!reg || !Array.isArray(reg.icons)) { errors.push(`${p}: no "icons" list`); continue; }
- const dir = p.replace(/\/registry\.json$/, '');
- sets.push({ id: reg.set || dir.split('/').pop() || 'set', path: p, dir, registry: reg });
- } catch (e) { errors.push(`${p}: not JSON (${(e as Error).message})`); }
- }
- return { sets, errors };
- }
- /** The SVG files a set holds: every .svg under its folder whose path has /flat/ (the drawings), from the root. */
- export function setFiles(root: string, set: IconSet): string[] {
- const out: string[] = [];
- const walk = (rel: string) => {
- const abs = join(root, rel.slice(1));
- if (!existsSync(abs)) return;
- for (const n of readdirSync(abs).sort()) {
- const r = `${rel}/${n}`;
- if (statSync(join(abs, n)).isDirectory()) walk(r);
- else if (n.toLowerCase().endsWith('.svg')) out.push(r);
- }
- };
- walk(`${set.dir}/flat`);
- return out;
- }
- export type Finding = { level: 'error' | 'warn'; text: string };
- /**
- * The registry and the files agree: every SVG has a record, every record has a file; names are kebab-case and
- * unique; no alias is shared or is another icon's name; every record has a description and a use. A near
- * duplicate (the same drawing, or the same aliases) is a warning: it reports, it does not fail.
- * files: the SVG paths the set holds; read: the text of a file (for the drawing comparison).
- */
- export function checkRegistry(reg: Registry, files: string[], read: (path: string) => string | null, where = 'registry'): Finding[] {
- const f: Finding[] = [];
- const err = (text: string) => f.push({ level: 'error', text: `${where}: ${text}` });
- const warn = (text: string) => f.push({ level: 'warn', text: `${where}: ${text}` });
- const names = new Map<string, number>();
- const words = new Map<string, string>(); // a name or an alias -> the icon it belongs to
- const recFiles = new Set<string>();
- for (const r of reg.icons) {
- const n = String(r?.name ?? '');
- if (!n) { err('a record without a name'); continue; }
- names.set(n, (names.get(n) ?? 0) + 1);
- if (!NAME_RE.test(n)) err(`"${n}": the name is not kebab-case`);
- if (!r.file) err(`"${n}": no file`);
- else {
- recFiles.add(r.file);
- if (read(r.file) === null) err(`"${n}": the file ${r.file} does not exist → draw it or drop the record`);
- }
- if (!String(r.description ?? '').trim()) err(`"${n}": no description (one line: what it draws)`);
- if (!String(r.use ?? '').trim()) err(`"${n}": no use (where it fits)`);
- }
- for (const [n, c] of names) if (c > 1) err(`the name "${n}" is used by ${c} records → one meaning, one icon`);
- for (const r of reg.icons) if (r?.name) words.set(r.name, r.name);
- for (const r of reg.icons) {
- for (const a of r?.aliases ?? []) {
- const w = String(a).trim().toLowerCase();
- if (!w) continue;
- const owner = words.get(w);
- if (owner && owner !== r.name) err(`"${r.name}": the alias "${w}" is ${names.has(w) ? 'the name of' : 'also an alias of'} "${owner}" → keep a word for one icon`);
- else words.set(w, r.name);
- }
- }
- for (const p of files) if (!recFiles.has(p)) err(`${p} has no record → add one (name, description, use, aliases) or remove the file`);
- // near duplicates: the same shapes (colours aside), or the same set of aliases
- const sig = new Map<string, string>();
- for (const r of reg.icons) {
- if (!r?.file) continue;
- const t = read(r.file);
- if (t === null) continue;
- const s = shapeSignature(t);
- if (s && sig.has(s)) warn(`"${r.name}" draws the same shapes as "${sig.get(s)}" → one meaning, one icon: merge them, or redraw one if the meanings differ`);
- else if (s) sig.set(s, r.name);
- }
- const al = new Map<string, string>();
- for (const r of reg.icons) {
- const k = [...new Set((r?.aliases ?? []).map((a) => String(a).toLowerCase()))].sort().join('|');
- if (k && al.has(k)) warn(`"${r.name}" has the same aliases as "${al.get(k)}" → are they one meaning?`);
- else if (k) al.set(k, r.name);
- }
- return f;
- }
- /**
- * The health lines of one set in the shape of /base/conventions.md: `health icon-set/<set>: full`, else a `missing` line
- * (the errors) and an `extra` line (the near duplicates), each followed by its details, indented.
- */
- export function healthLines(set: string, findings: Finding[]): string[] {
- const errs = findings.filter((f) => f.level === 'error'), warns = findings.filter((f) => f.level === 'warn');
- const subject = `health icon-set/${set}`;
- if (!errs.length && !warns.length) return [`${subject}: full`];
- const out: string[] = [];
- const short = (f: Finding) => f.text.replace(/^[^:]*: /, '').replace(/ → .*$/, '');
- if (errs.length) out.push(`${subject}: missing: ${errs.length} (${errs.slice(0, 3).map(short).join('; ')}${errs.length > 3 ? '; …' : ''})`, ...errs.map((f) => ` ${f.text}`));
- if (warns.length) out.push(`${subject}: extra: ${warns.length} near duplicate(s)`, ...warns.map((f) => ` ${f.text}`));
- return out;
- }
- const GEOM = new Set(['d', 'x', 'y', 'width', 'height', 'rx', 'ry', 'cx', 'cy', 'r', 'points', 'x1', 'y1', 'x2', 'y2', 'transform']);
- /** The shapes of a drawing without their colours, order-free: two drawings that differ only in colour match. */
- export function shapeSignature(svg: string): string {
- const out: string[] = [];
- const re = /<(path|rect|circle|ellipse|polygon|polyline|line)\b([^>]*)>/g;
- let m: RegExpExecArray | null;
- while ((m = re.exec(svg))) {
- const attrs: string[] = [];
- const ar = /([\w:-]+)\s*=\s*"([^"]*)"/g;
- let a: RegExpExecArray | null;
- while ((a = ar.exec(m[2]))) if (GEOM.has(a[1])) attrs.push(`${a[1]}=${a[2].replace(/\s+/g, ' ').trim()}`);
- out.push(`${m[1]}:${attrs.sort().join(',')}`);
- }
- return out.sort().join('|');
- }
- /** Searches a registry by meaning: the words of the query against name, aliases, description and use. Best first. */
- export function search(reg: Registry, query: string, limit = 8): { rec: IconRecord; score: number }[] {
- const q = tokens(query);
- if (!q.length) return [];
- const out: { rec: IconRecord; score: number }[] = [];
- for (const r of reg.icons) {
- const name = tokens(r.name), al = (r.aliases ?? []).flatMap(tokens), desc = tokens(r.description ?? ''), use = tokens(r.use ?? '');
- let score = 0;
- for (const w of q) {
- if (name.includes(w)) score += 5;
- else if (al.includes(w)) score += 4;
- else if (name.some((x) => stem(x) === stem(w)) || al.some((x) => stem(x) === stem(w))) score += 3;
- if (desc.some((x) => stem(x) === stem(w))) score += 1;
- if (use.some((x) => stem(x) === stem(w))) score += 1;
- }
- if (score) out.push({ rec: r, score });
- }
- return out.sort((a, b) => b.score - a.score || a.rec.name.localeCompare(b.rec.name)).slice(0, limit);
- }
- const STOP = new Set(['a', 'an', 'the', 'of', 'and', 'or', 'in', 'on', 'to', 'for', 'with', 'by', 'is', 'its', 'it', 'use', 'package']);
- const tokens = (s: string) => String(s).toLowerCase().split(/[^a-z0-9]+/).filter((w) => w && !STOP.has(w));
- const stem = (w: string) => w.replace(/(ies|es|s|ing|ed)$/, '');