файл пакета→ .shtukbase/packages/design-tokens/test/contract.test.ts
test/contract.test.ts
193 строки, 11.8 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // The token contract v1 and its check `contract` (DTK-R03): the data, the reader other packages call, passing and failing
- // style fixtures, the project's choice, `--css`, and the style build. Run: `bun test` in the package.
- import { afterAll, describe, expect, test } from 'bun:test';
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { dirname, join } from 'node:path';
- import { buildStyle } from '../actions/build.ts';
- import { check } from '../checks/contract.ts';
- import { checkCss, defaultsCss, fallbackLine, fallbacks, parseContract, readContract, styleChoice, styleCssPath } from '../lib/contract.ts';
- const pkg = join(import.meta.dir, '..');
- const fixture = (n: string) => readFileSync(join(import.meta.dir, 'fixtures', n), 'utf8');
- const tmps: string[] = [];
- function project(files: Record<string, string>): string {
- const dir = mkdtempSync(join(tmpdir(), 'dtk-contract-'));
- tmps.push(dir);
- for (const [rel, text] of Object.entries(files)) {
- mkdirSync(dirname(join(dir, rel)), { recursive: true });
- writeFileSync(join(dir, rel), text);
- }
- return dir;
- }
- afterAll(() => { for (const d of tmps) rmSync(d, { recursive: true, force: true }); });
- const contract = readContract(project({}));
- const designPage = (style: string) => `---\ntype: Page\ntitle: Design\nstyle: ${style}\nlibraries: []\n---\n`;
- describe('the contract data', () => {
- test('the page copy equals the packaged contract', () => {
- expect(readFileSync(join(pkg, 'pages/design/contract.json'), 'utf8')).toBe(readFileSync(join(pkg, 'lib/contract.json'), 'utf8'));
- });
- test('required names: the shadcn theme; colours are the required names with a dark value', () => {
- const r = new Set(contract.required);
- for (const n of ['background', 'foreground', 'card', 'card-foreground', 'popover', 'popover-foreground', 'primary', 'primary-foreground', 'secondary', 'secondary-foreground', 'muted', 'muted-foreground', 'accent', 'accent-foreground', 'destructive', 'border', 'input', 'ring', 'chart-1', 'chart-2', 'chart-3', 'chart-4', 'chart-5', 'sidebar', 'sidebar-foreground', 'sidebar-primary', 'sidebar-primary-foreground', 'sidebar-accent', 'sidebar-accent-foreground', 'sidebar-border', 'sidebar-ring', 'radius'])
- expect(r.has(`--${n}`)).toBe(true);
- expect(contract.required.length).toBe(32);
- expect(contract.colors.length).toBe(31);
- expect(contract.colors.every((n) => r.has(n))).toBe(true);
- for (const n of ['--radius', '--font-sans', '--font-mono', '--shadow-sm', '--shadow-md', '--shadow-lg']) expect(contract.colors).not.toContain(n);
- for (const n of ['--font-sans', '--font-mono', '--shadow-sm', '--shadow-md', '--shadow-lg']) expect(contract.required).not.toContain(n);
- });
- test('the extension has --font-display, 12 hues with -soft/-tint/-ink and the sb names, all with a default', () => {
- const e = Object.keys(contract.extension);
- expect(e).toContain('--font-display');
- for (let i = 1; i <= 12; i++) for (const s of ['', '-soft', '-tint', '-ink']) expect(e).toContain(`--sb-hue-${i}${s}`);
- for (const n of ['--sb-shadow-lift', '--sb-shadow-sheet', '--sb-glow', '--sb-edge', '--sb-ease', '--sb-dur']) expect(e).toContain(n);
- expect(e.length).toBe(5 + 1 + 48 + 6);
- for (const n of ['--font-sans', '--font-mono', '--shadow-sm', '--shadow-md', '--shadow-lg']) expect(contract.extension[n]).toBeTruthy();
- expect(contract.extension['--font-display']).toBe('var(--font-sans)');
- });
- test('parseContract names the problem of a bad contract', () => {
- expect(parseContract(null).problem).toMatch(/not a JSON object/);
- expect(parseContract({ version: 1, required: ['card'], colors: [], extension: {} }).problem).toMatch(/required/);
- expect(parseContract({ version: 1, required: ['--a'], colors: ['--b'], extension: {} }).problem).toMatch(/not required/);
- expect(parseContract({ version: 1, required: ['--a'], colors: ['--a'], extension: { '--x': '' } }).problem).toMatch(/extension/);
- expect(parseContract({ version: 1, required: ['--a'], colors: ['--a'], extension: { '--x': '1px' } }).problem).toBeNull();
- });
- test("the project's own /design/contract.json wins when valid; a broken one falls back to the packaged", () => {
- const own = { version: 1, required: ['--a'], colors: ['--a'], extension: {} };
- expect(readContract(project({ 'design/contract.json': JSON.stringify(own) })).required).toEqual(['--a']);
- expect(readContract(project({ 'design/contract.json': '{ not json' })).required.length).toBe(32);
- });
- });
- describe('checkCss', () => {
- test('a style that meets the contract passes', () => {
- expect(checkCss(fixture('pass.css'), 'pass.css', contract)).toEqual([]);
- });
- test('missing names are named, in :root and in the dark scheme', () => {
- const out = checkCss(fixture('fail-missing.css'), 'f.css', contract);
- expect(out).toContain('f.css: :root has no --ring');
- expect(out).toContain('f.css: the dark scheme has no --card');
- expect(out).toContain('f.css: the dark scheme has no --sidebar-ring');
- expect(out.length).toBe(3);
- });
- test('no dark scheme at all is one finding', () => {
- const out = checkCss(fixture('fail-no-dark.css'), 'f.css', contract);
- expect(out.length).toBe(1);
- expect(out[0]).toMatch(/no dark scheme/);
- });
- test('[data-theme="dark"] alone, and a prefers-color-scheme: dark block, count as the dark scheme', () => {
- const pass = fixture('pass.css');
- expect(checkCss(pass.replace('.dark, [data-theme="dark"]', '[data-theme="dark"]'), 'a.css', contract)).toEqual([]);
- expect(checkCss(pass.replace('.dark, [data-theme="dark"] {', '@media (prefers-color-scheme: dark) {\n:root {').replace(/\}\n$/, '}\n}\n'), 'b.css', contract)).toEqual([]);
- });
- test('light-dark() in the light value carries the dark value', () => {
- const light = fixture('fail-no-dark.css').replace(/(--card): [^;]+;/, '$1: light-dark(white, black);');
- const dark = ':root {} .dark { --background: black; }';
- const out = checkCss(`${light}\n${dark}`, 'l.css', contract);
- expect(out).not.toContain('l.css: the dark scheme has no --card');
- expect(out).toContain('l.css: the dark scheme has no --foreground');
- });
- test('a colour that refers to a variable that does not exist is a finding', () => {
- const css = fixture('pass.css').replace(/(--primary): [^;]+;/, '$1: var(--nope);');
- expect(checkCss(css, 'v.css', contract)).toEqual(['v.css: light scheme: --primary refers to a variable that does not exist']);
- });
- test('a variable that resolves inside the stylesheet is fine', () => {
- const css = fixture('pass.css').replace(/(--sidebar): [^;]+;/, '$1: var(--card);');
- expect(checkCss(css, 'r.css', contract)).toEqual([]);
- });
- });
- describe('the extension fallbacks', () => {
- test('a style with no extension falls back to every default; the note groups the hues', () => {
- const miss = fallbacks(fixture('pass.css'), contract);
- expect(miss.length).toBe(55);
- expect(fallbackLine(miss)).toBe('--font-display, --sb-shadow-lift, --sb-shadow-sheet, --sb-glow, --sb-edge, --sb-ease, --sb-dur, --sb-hue-1 … --sb-hue-12 with -soft, -tint, -ink (48 names)');
- });
- test('names the style sets are not fallbacks', () => {
- const css = `${fixture('pass.css')}\n:root { --font-display: Outfit; --sb-glow: 0 0 0 1px red; }`;
- const miss = fallbacks(css, contract);
- expect(miss).not.toContain('--font-display');
- expect(miss).not.toContain('--sb-glow');
- expect(miss).toContain('--sb-edge');
- });
- test('defaultsCss writes the defaults of the missing names', () => {
- const css = defaultsCss(['--font-display', '--sb-dur', '--card'], contract);
- expect(css).toBe(':root {\n --font-display: var(--font-sans);\n --sb-dur: 160ms;\n}\n');
- expect(defaultsCss([], contract)).toBe('');
- });
- });
- describe('the check in a project', () => {
- test('no style chosen: silent', () => {
- expect(check(project({ 'design/design.md': designPage('""') }))).toEqual({ findings: [], notes: [] });
- expect(check(project({}))).toEqual({ findings: [], notes: [] });
- });
- test('the chosen style is read from /design/design.md', () => {
- const root = project({ 'design/design.md': designPage('demo-style'), 'design/demo-style/tokens.css': fixture('pass.css') });
- expect(styleChoice(root)).toEqual({ style: 'demo-style', libraries: [] });
- expect(styleCssPath(root)).toBe('design/demo-style/tokens.css');
- const r = check(root);
- expect(r.findings).toEqual([]);
- expect(r.notes.length).toBe(1);
- expect(r.notes[0]).toMatch(/^note: design\/demo-style\/tokens\.css leaves out optional names;.*--font-display/);
- });
- test('the libraries list is read', () => {
- const root = project({ 'design/design.md': '---\ntype: Page\nstyle: s\nlibraries: [ui-html, ui-react]\n---\n' });
- expect(styleChoice(root).libraries).toEqual(['ui-html', 'ui-react']);
- });
- test('a chosen style with no tokens.css is a finding', () => {
- const r = check(project({ 'design/design.md': designPage('demo-style') }));
- expect(r.findings.length).toBe(1);
- expect(r.findings[0]).toMatch(/^design\/demo-style\/tokens\.css: the file is missing/);
- });
- test('a chosen style that misses names fails', () => {
- const r = check(project({ 'design/design.md': designPage('demo-style'), 'design/demo-style/tokens.css': fixture('fail-missing.css') }));
- expect(r.findings.length).toBe(3);
- });
- test('a style with no extension but all of the extension set has no note', () => {
- const ext = Object.entries(contract.extension).map(([k, v]) => ` ${k}: ${v};`).join('\n');
- const root = project({ 'design/design.md': designPage('s'), 'design/s/tokens.css': `${fixture('pass.css')}\n:root {\n${ext}\n}\n` });
- expect(check(root)).toEqual({ findings: [], notes: [] });
- });
- test('--css judges a file by hand; a relative path is from the project root', () => {
- const root = project({ 'themes/x.css': fixture('fail-no-dark.css') });
- expect(check(root, 'themes/x.css').findings.length).toBe(1);
- const run = Bun.spawnSync(['bun', join(pkg, 'checks/contract.ts'), '--css', 'themes/x.css'], { cwd: root });
- expect(run.exitCode).toBe(1);
- expect(run.stdout.toString()).toMatch(/themes\/x\.css: no dark scheme/);
- const ok = Bun.spawnSync(['bun', join(pkg, 'checks/contract.ts'), '--css', 'themes/ok.css'], { cwd: project({ 'themes/ok.css': fixture('pass.css') }) });
- expect(ok.exitCode).toBe(0);
- expect(ok.stdout.toString()).toMatch(/^note: /);
- const bare = Bun.spawnSync(['bun', join(pkg, 'checks/contract.ts'), '--css'], { cwd: root });
- expect(bare.exitCode).toBe(1);
- });
- });
- describe('building a style', () => {
- const tokens = {
- $type: 'color',
- background: { $value: '#ffffff' },
- sb: { hue: { 1: { $value: '#aa3366' } } },
- radius: { $type: 'dimension', $value: { value: 0.5, unit: 'rem' } },
- 'font-sans': { $type: 'fontFamily', $value: ['Inter', 'sans-serif'] },
- };
- const dark = { background: { $value: '#000000' }, sb: { hue: { 1: { $value: '#ff77aa' } } } };
- test('buildStyle writes /design/<id>/tokens.css with contract names and the dark scheme on both selectors', () => {
- const root = project({ 'design/demo/tokens.json': JSON.stringify(tokens), 'design/demo/tokens.dark.json': JSON.stringify(dark) });
- const r = buildStyle('demo', root);
- expect(r.ok).toBe(true);
- const css = readFileSync(join(root, 'design/demo/tokens.css'), 'utf8');
- expect(css).toContain(' --background: #ffffff;');
- expect(css).toContain(' --sb-hue-1: #aa3366;');
- expect(css).toContain(' --font-sans: Inter, sans-serif;');
- expect(css).toContain('.dark, [data-theme="dark"] {\n --background: #000000;');
- });
- test('invalid tokens write nothing', () => {
- const root = project({ 'design/demo/tokens.json': JSON.stringify({ a: { $type: 'color', $value: 'red' } }), 'design/demo/tokens.dark.json': '{}' });
- const r = buildStyle('demo', root);
- expect(r.ok).toBe(false);
- expect(r.message).toMatch(/not built/);
- });
- });