файл пакета→ .shtukbase/packages/design-tokens/lib/contract.ts
lib/contract.ts
161 строка, 8.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // The token contract v1: which CSS custom properties a style must define, which of them need a dark value, and the
- // defaults of the optional extension. Other design packages call this file: `readContract`, `styleChoice`,
- // `styleCssPath`, `checkCss`, `fallbacks`, `defaultsCss`. The working directory is the project root.
- // The contract data is `lib/contract.json`; its copy `pages/design/contract.json` is what a project gets and may
- // extend (a project's own `/design/contract.json` wins when it is valid). Bun only, no dependencies.
- import { existsSync, readFileSync } from 'node:fs';
- import { join } from 'node:path';
- import { parseCss, resolveVars, themeOf } from '../../design-base/lib/css.ts';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- import packaged from './contract.json';
- export const CONTRACT_PAGE = 'design/contract.json';
- export const DESIGN_PAGE = 'design/design.md';
- export type Contract = {
- version: number;
- /** Every name a style must define in `:root` (light), with the leading `--`. */
- required: string[];
- /** The required names that are colours: each needs a value in the dark scheme too. */
- colors: string[];
- /** Optional names with the default that applies when a style does not set them. */
- extension: Record<string, string>;
- };
- const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
- const names = (v: unknown): string[] | null =>
- Array.isArray(v) && v.every((x) => typeof x === 'string' && /^--[\w-]+$/.test(x)) ? (v as string[]) : null;
- /** A contract object, or the problem with it. */
- export function parseContract(data: unknown): { contract: Contract | null; problem: string | null } {
- if (!isObj(data)) return { contract: null, problem: 'the contract is not a JSON object' };
- const required = names(data.required);
- const colors = names(data.colors);
- if (typeof data.version !== 'number') return { contract: null, problem: 'the contract has no numeric "version"' };
- if (!required) return { contract: null, problem: '"required" is a list of names like --card' };
- if (!colors) return { contract: null, problem: '"colors" is a list of names like --card' };
- const stray = colors.filter((c) => !required.includes(c));
- if (stray.length) return { contract: null, problem: `"colors" names that are not required: ${stray.join(', ')}` };
- const ext = data.extension;
- if (!isObj(ext) || Object.entries(ext).some(([k, v]) => !/^--[\w-]+$/.test(k) || typeof v !== 'string' || !v.trim()))
- return { contract: null, problem: '"extension" is an object {--name: default CSS value}' };
- return { contract: { version: data.version, required, colors, extension: ext as Record<string, string> }, problem: null };
- }
- /** The contract of the project (`/design/contract.json`), else the one this package carries. */
- export function readContract(root = process.cwd()): Contract {
- const p = join(root, CONTRACT_PAGE);
- if (existsSync(p)) {
- try {
- const { contract } = parseContract(JSON.parse(readFileSync(p, 'utf8')));
- if (contract) return contract;
- } catch { /* a broken file: the packaged contract applies */ }
- }
- return parseContract(packaged).contract as Contract;
- }
- /** The project's choice on `/design/design.md`: the style id and the library ids ('' and [] when not chosen). */
- export function styleChoice(root = process.cwd()): { style: string; libraries: string[] } {
- const p = join(root, DESIGN_PAGE);
- const fm = existsSync(p) ? readPage(p).fm : {};
- const style = typeof fm.style === 'string' ? fm.style.trim() : '';
- const libraries = Array.isArray(fm.libraries) ? fm.libraries.map((x: unknown) => String(x).trim()).filter(Boolean) : [];
- return { style: /^[\w.-]+$/.test(style) ? style : '', libraries };
- }
- /** Project path of the built tokens of the chosen style (`design/<style>/tokens.css`), or null when none is chosen. */
- export function styleCssPath(root = process.cwd()): string | null {
- const { style } = styleChoice(root);
- return style ? `design/${style}/tokens.css` : null;
- }
- export type Scheme = Map<string, string>;
- /** The light scheme (`:root`, `@theme`) and the dark one (`.dark`, `[data-theme="dark"]`, prefers-color-scheme: dark), own declarations only. */
- export function schemes(css: string): { light: Scheme; dark: Scheme | null } {
- const light: Scheme = new Map();
- let dark: Scheme | null = null;
- for (const b of parseCss(css)) {
- if (b.parents.length) continue;
- const media = b.at.some((a) => /prefers-color-scheme\s*:\s*dark/.test(a));
- const own = b.decls.filter((d) => d.prop.startsWith('--'));
- const roots = new Set<string>();
- if (b.prelude.startsWith('@theme')) roots.add('base');
- for (const s of b.selectors) {
- const t = themeOf(s, media);
- if (t === 'base' || t === 'dark') roots.add(t);
- }
- if (roots.has('base')) for (const d of own) light.set(d.prop, d.value);
- if (roots.has('dark')) {
- dark ??= new Map();
- for (const d of own) dark.set(d.prop, d.value);
- }
- }
- return { light, dark };
- }
- /** Problems of a stylesheet against the contract (one line each; `where` names the file in the lines). */
- export function checkCss(css: string, where: string, contract: Contract): string[] {
- const out: string[] = [];
- const { light, dark } = schemes(css);
- for (const n of contract.required) if (!light.has(n)) out.push(`${where}: :root has no ${n}`);
- const colors = contract.colors.filter((n) => light.has(n));
- if (!dark) out.push(`${where}: no dark scheme (.dark, [data-theme="dark"]) — every colour needs a dark value`);
- else
- for (const n of contract.colors) {
- // light-dark() in the light value carries both values.
- if (!dark.has(n) && !/light-dark\(/.test(light.get(n) ?? '')) out.push(`${where}: the dark scheme has no ${n}`);
- }
- const scheme = (name: string, own: Scheme) => {
- const vars = new Map([...light, ...own]);
- for (const n of colors) {
- if (!own.has(n) && name === 'dark') continue;
- const v = vars.get(n) as string;
- if (resolveVars(v, vars) === null) out.push(`${where}: ${name} scheme: ${n} refers to a variable that does not exist`);
- }
- };
- scheme('light', new Map());
- if (dark) scheme('dark', dark);
- return out;
- }
- /** Extension names the stylesheet does not set: the contract's defaults apply to them. */
- export function fallbacks(css: string, contract: Contract): string[] {
- const { light } = schemes(css);
- return Object.keys(contract.extension).filter((n) => !light.has(n));
- }
- /** A short line naming the fallbacks: the hue family is one item. */
- export function fallbackLine(missing: string[]): string {
- const hue = missing.filter((n) => /^--sb-hue-\d+(-soft|-tint|-ink)?$/.test(n));
- const rest = missing.filter((n) => !hue.includes(n));
- const items = [...rest];
- if (hue.length) items.push(`--sb-hue-1 … --sb-hue-12 with -soft, -tint, -ink (${hue.length} names)`);
- return items.join(', ');
- }
- /** A `:root { … }` block with the defaults of the given extension names, to put before a style's CSS. */
- export function defaultsCss(missing: string[], contract: Contract): string {
- const lines = missing.filter((n) => n in contract.extension).map((n) => ` ${n}: ${contract.extension[n]};`);
- return lines.length ? `:root {\n${lines.join('\n')}\n}\n` : '';
- }
- export type Health = { missing: string[]; fallbacks: string[]; extra: string[] };
- /** The health of a stylesheet against the contract, as names for the bands of a convention: `missing` (required names, a colour's
- * dark value as `--x (dark)`, a broken reference as `--x (broken in light)`), `fallbacks` (optional names left out) and `extra`
- * (names the style sets that the contract does not know). No band filled means `full`. */
- export function health(css: string, contract: Contract): Health {
- const { light, dark } = schemes(css);
- const missing = contract.required.filter((n) => !light.has(n));
- if (!dark) missing.push(...contract.colors.map((n) => `${n} (dark)`));
- else for (const n of contract.colors) if (!dark.has(n) && !/light-dark\(/.test(light.get(n) ?? '')) missing.push(`${n} (dark)`);
- for (const line of checkCss(css, '', contract)) {
- const m = /(light|dark) scheme: (--[\w-]+) refers to a variable that does not exist/.exec(line);
- if (m) missing.push(`${m[2]} (broken in ${m[1]})`);
- }
- // Tailwind v4 mirrors a theme name as --color-<name> (and animations as --animate-*): derived names, not extras
- const known = new Set([...contract.required, ...Object.keys(contract.extension), ...contract.colors.map((n) => `--color-${n.slice(2)}`)]);
- const extra = [...new Set([...light.keys(), ...(dark?.keys() ?? [])])].filter((n) => !known.has(n) && !n.startsWith('--animate-')).sort();
- return { missing, fallbacks: fallbacks(css, contract), extra };
- }