@behavioral-agentic-design-system/core 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@behavioral-agentic-design-system/core",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "BADS core — tokens, shadcn/ui components, and the BADS template shell (app routes, customize tab, theme hooks). Forks consume this and re-export, keeping client repos to ~30 lines of glue.",
5
5
  "license": "MIT",
6
6
  "author": "Matthew Stephens <work@matthewstephens.com> (https://github.com/matthewlarn)",
@@ -38,7 +38,13 @@
38
38
  "bin": {
39
39
  "bads-build-tokens": "scripts/build-tokens.cjs",
40
40
  "bads-build-fonts": "scripts/build-fonts.cjs",
41
- "bads-sync": "scripts/bads-sync.mjs"
41
+ "bads-sync": "scripts/bads-sync.mjs",
42
+ "bads-a11y-lint": "scripts/a11y-lint.cjs",
43
+ "bads-wcag-audit": "scripts/wcag-audit.cjs",
44
+ "bads-check-stories": "scripts/check-stories.mjs",
45
+ "bads-fix-stories": "scripts/fix-stories.mjs",
46
+ "bads-generate-stories": "scripts/generate-stories.cjs",
47
+ "bads-oklch-to-hex": "scripts/oklch-to-hex.cjs"
42
48
  },
43
49
  "exports": {
44
50
  ".": "./src/index.ts",
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * a11y-lint — static accessibility checks against AAA WCAG 2.2 floor.
4
+ *
5
+ * Scans .tsx and .stories.tsx files under app/, components/, and packages/core/,
6
+ * and flags common AAA-blocking patterns. Complements:
7
+ * - scripts/wcag-audit.js (token contrast)
8
+ * - scripts/lint-target-size.js (touch-target sizes)
9
+ * - scripts/lint-tokens.js (token usage)
10
+ *
11
+ * Checks (each tied to a WCAG SC):
12
+ * 1.1.1 Non-text Content — <img> / <Image> without alt or aria-label
13
+ * 1.4.4 Resize Text — fontSize: "<n>px" inline (use rem/em or text-* utility)
14
+ * 1.4.6 Contrast (Enhanced) — hardcoded HEX colors (must use token)
15
+ * 2.1.1 Keyboard — onClick on non-button/<a> elements (warn)
16
+ * 2.4.4 Link Purpose — <a> with empty / "click here" text
17
+ * 2.4.13 Focus Appearance — outline-none / focus:outline-none w/o replacement
18
+ * 3.3.2 Labels or Instructions — <input> without associated <Label> or aria-label
19
+ * 4.1.2 Name, Role, Value — <button> with no text and no aria-label
20
+ * SADS-1 Font weight floor — text-xs/text-sm must be font-medium (500) or heavier
21
+ *
22
+ * Run:
23
+ * node scripts/a11y-lint.js # report violations, exit 1 on fail
24
+ * node scripts/a11y-lint.js --warn # report but exit 0 (advisory)
25
+ * node scripts/a11y-lint.js path/to.tsx # scan a specific file
26
+ */
27
+
28
+ 'use strict';
29
+
30
+ const fs = require('fs');
31
+ const path = require('path');
32
+
33
+ // Shipped as the `bads-a11y-lint` bin. process.cwd() means the same script
34
+ // scans the right tree whether it runs in upstream BADS (CWD = repo root) or
35
+ // in a client fork (CWD = fork root). The `packages/core/src/components` scan
36
+ // root no-ops in a fork (the dir is a stub) via the existsSync guard in walk().
37
+ const ROOT = process.cwd();
38
+ const advisory = process.argv.includes('--warn');
39
+ const explicitPaths = process.argv.slice(2).filter((a) => !a.startsWith('--'));
40
+
41
+ const SCAN_ROOTS = [
42
+ 'app',
43
+ 'components',
44
+ 'packages/core/src/components',
45
+ ];
46
+
47
+ function walk(dir, out = []) {
48
+ if (!fs.existsSync(dir)) return out;
49
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
50
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
51
+ const full = path.join(dir, entry.name);
52
+ if (entry.isDirectory()) {
53
+ walk(full, out);
54
+ } else if (/\.tsx?$/.test(entry.name)) {
55
+ out.push(full);
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+
61
+ const files = explicitPaths.length
62
+ ? explicitPaths.map((p) => path.resolve(p))
63
+ : SCAN_ROOTS.flatMap((r) => walk(path.join(ROOT, r)));
64
+
65
+ const issues = [];
66
+
67
+ function flag(file, line, sc, rule, message) {
68
+ issues.push({ file: path.relative(ROOT, file), line, sc, rule, message });
69
+ }
70
+
71
+ // ---- per-line scans -----------------------------------------------------
72
+
73
+ const HARDCODED_HEX = /(?:bg-|text-|border-|fill-|stroke-|from-|to-|via-|shadow-|ring-)\[#[0-9A-Fa-f]{3,8}\]|(?<!\$value":\s")#[0-9A-Fa-f]{6}(?![A-Fa-f0-9"])/;
74
+ const INLINE_PX_FONT = /fontSize:\s*['"]\d+px['"]/;
75
+ const ARBITRARY_TEXT_PX = /text-\[(\d+)px\]/g;
76
+ const FOCUS_OUTLINE_NONE = /(?:focus(?:-visible)?:)?outline-none(?!\s*[\w-]*(focus-visible:|ring-|outline-)|.*ring-)/;
77
+ const ANIMATE_NO_MOTION_SAFE = /(?<!motion-safe:)\banimate-(?:bounce|ping|pulse|spin|in|out)\b/;
78
+ // SADS-1 — small text (<18px = text-xs/text-sm) must be font-medium (500) or heavier.
79
+ // font-normal (400) at text-xs (14px) or text-sm (16px) is below the SADS weight floor.
80
+ // This detects explicit same-className pairings. Inherited weight from a parent is not flagged.
81
+ // Escape hatch: "// allow-font-normal-small" on the line above.
82
+ const SMALL_TEXT_LIGHT_WEIGHT = /\b(text-xs|text-sm)\b.+\b(font-normal|font-light|font-thin|font-extralight)\b|\b(font-normal|font-light|font-thin|font-extralight)\b.+\b(text-xs|text-sm)\b/;
83
+
84
+ const HEADING_REGEX = /<(h[1-6])([^>]*)>([^<]*)/g;
85
+ const IMG_REGEX = /<(?:img|Image|AvatarImage)\b([^>]*)\/?>/;
86
+ const ANCHOR_OPEN = /<a\b([^>]*)>([^<]*)<\/a>/;
87
+ const BUTTON_OPEN = /<(?:button|Button)\b([^>]*?)(?:\/>|>([^<]*)<\/(?:button|Button)>)/;
88
+ const INPUT_NO_LABEL = /<(?:input|Input|Textarea)\b((?:[^>]|\n)*?)\/?>/;
89
+ const ON_CLICK_NON_INTERACTIVE = /<(?:div|span|p)\b[^>]*onClick=/;
90
+
91
+ const VAGUE_LINK_TEXT = /^(?:click here|here|read more|learn more|more|click)\.?$/i;
92
+
93
+ for (const file of files) {
94
+ let src;
95
+ try { src = fs.readFileSync(file, 'utf8'); } catch { continue; }
96
+ // Skip generated files.
97
+ if (src.startsWith('/* GENERATED FROM tokens.json')) continue;
98
+ // Skip tests + e2e specs.
99
+ if (file.includes('/e2e/') || file.endsWith('.spec.ts') || file.endsWith('.test.ts')) continue;
100
+ // Skip story files except for headline checks (they're fine to be terse).
101
+ const isStory = file.endsWith('.stories.tsx');
102
+
103
+ const lines = src.split('\n');
104
+ for (let i = 0; i < lines.length; i++) {
105
+ const line = lines[i];
106
+ const lineNum = i + 1;
107
+
108
+ if (HARDCODED_HEX.test(line)) {
109
+ flag(file, lineNum, '1.4.6', 'hex-literal',
110
+ 'Hardcoded hex color. Use a semantic token or @theme variable instead.');
111
+ }
112
+
113
+ if (INLINE_PX_FONT.test(line)) {
114
+ flag(file, lineNum, '1.4.4', 'inline-px-font',
115
+ 'Inline pixel font size. Use a text-* utility or rem-based value so 200% zoom still works.');
116
+ }
117
+
118
+ let match;
119
+ ARBITRARY_TEXT_PX.lastIndex = 0;
120
+ while ((match = ARBITRARY_TEXT_PX.exec(line))) {
121
+ const px = parseInt(match[1], 10);
122
+ if (px < 14) {
123
+ flag(file, lineNum, '1.4.4', 'tiny-text',
124
+ `text-[${px}px] is below the 14px AAA accessibility floor. Use text-xs (14px) or larger.`);
125
+ }
126
+ }
127
+
128
+ // SADS-1 — small text (text-xs/text-sm, <18px) must be font-medium (500) or heavier.
129
+ if (SMALL_TEXT_LIGHT_WEIGHT.test(line)
130
+ && !/\/\/\s*allow-font-normal-small/.test(line)
131
+ && !(i > 0 && /allow-font-normal-small/.test(lines[i - 1]))) {
132
+ flag(file, lineNum, 'SADS-1', 'small-text-light-weight',
133
+ 'font-normal (or lighter) on text-xs/text-sm (<18px). SADS weight floor: font-medium (500) minimum below 18px. Add "// allow-font-normal-small" above to intentionally bypass.');
134
+ }
135
+
136
+ if (FOCUS_OUTLINE_NONE.test(line) && !/ring-|outline-|focus-visible:/.test(line)) {
137
+ flag(file, lineNum, '2.4.13', 'focus-removed',
138
+ 'outline-none without a replacement focus indicator. AAA 2.4.13 requires a visible focus marker.');
139
+ }
140
+
141
+ // Note: animate-* utilities don't need motion-safe: prefixes here because
142
+ // the base layer's @media (prefers-reduced-motion: reduce) rule already
143
+ // forces every animation/transition to 0.01ms with !important. Components
144
+ // are free to use animate-in / animate-out / animate-pulse etc.
145
+
146
+ if (!isStory && ON_CLICK_NON_INTERACTIVE.test(line)) {
147
+ flag(file, lineNum, '2.1.1', 'click-on-div',
148
+ 'onClick on a non-interactive element. Use <button> or <a>, or add role="button" + tabIndex={0} + onKeyDown.');
149
+ }
150
+
151
+ const imgMatch = line.match(IMG_REGEX);
152
+ if (imgMatch) {
153
+ const attrs = imgMatch[1];
154
+ const hasAlt = /\balt\s*=/.test(attrs);
155
+ const hasAria = /aria-(label|labelledby|hidden)\s*=/.test(attrs);
156
+ if (!hasAlt && !hasAria) {
157
+ flag(file, lineNum, '1.1.1', 'image-no-alt',
158
+ '<img>/Image/AvatarImage without alt or aria-*. Decorative images should set alt="".');
159
+ }
160
+ }
161
+
162
+ const anchorMatch = line.match(ANCHOR_OPEN);
163
+ if (anchorMatch) {
164
+ const text = anchorMatch[2].trim();
165
+ if (text && VAGUE_LINK_TEXT.test(text)) {
166
+ flag(file, lineNum, '2.4.4', 'vague-link',
167
+ `Link text "${text}" doesn't describe its purpose in isolation. AAA 2.4.9 wants link purpose from text alone.`);
168
+ }
169
+ }
170
+
171
+ const btnMatch = line.match(BUTTON_OPEN);
172
+ if (btnMatch) {
173
+ const attrs = btnMatch[1];
174
+ const text = (btnMatch[2] || '').trim();
175
+ const hasAria = /aria-(label|labelledby)\s*=/.test(attrs);
176
+ const hasTitle = /\btitle\s*=/.test(attrs);
177
+ const hasChildren = text.length > 0 || /<[A-Z]/.test(line.slice(line.indexOf('>') + 1));
178
+ if (!hasChildren && !hasAria && !hasTitle) {
179
+ flag(file, lineNum, '4.1.2', 'button-unlabeled',
180
+ 'Button with no text content and no aria-label. Icon-only buttons must set aria-label.');
181
+ }
182
+ }
183
+ }
184
+
185
+ // BADS-CHART — hand-rolled chart SVG bypasses the BADS Chart primitive.
186
+ // A raw <svg> that plots a data series (<path>/<polyline>/<line>) AND draws
187
+ // its own axis/value labels (2+ <text>) is a chart assembled by hand.
188
+ // <ChartContainer> (recharts) handles axis tick spacing, label
189
+ // collision/thinning, responsive sizing, and token-based theming — every one
190
+ // of which hand-placed <text> labels get wrong (overlapping x-axis labels is
191
+ // the classic failure, and no other gate inspects SVG geometry to catch it).
192
+ // Files that already import the chart primitive or recharts are exempt.
193
+ // File-level check (JSX charts span many lines). Stories are exempt.
194
+ // Escape hatch: `// allow-handrolled-chart` anywhere in the file, with a
195
+ // reason (e.g. a bespoke draw-in hero recharts can't express).
196
+ if (!file.endsWith('.stories.tsx')
197
+ && /<svg[\s>]/.test(src)
198
+ && (src.match(/<text[\s>]/g) || []).length >= 2
199
+ && /<(?:path|polyline|line)[\s>]/.test(src)
200
+ && !/components\/ui\/chart|ChartContainer|from\s+['"]recharts['"]/.test(src)
201
+ && !/allow-handrolled-chart/.test(src)) {
202
+ const svgLine = lines.findIndex((l) => /<svg[\s>]/.test(l)) + 1;
203
+ flag(file, svgLine || 1, 'BADS-CHART', 'handrolled-chart',
204
+ 'Hand-rolled chart SVG (data series + 2+ hand-placed <text> labels). Use the BADS Chart primitive — ChartContainer from "@<slug>/core/components/ui/chart". Recharts handles axis tick spacing and label collision/thinning that hand-placed <text> labels get wrong. Escape hatch: add "// allow-handrolled-chart" in the file with a reason.');
205
+ }
206
+ }
207
+
208
+ // ---- output ------------------------------------------------------------
209
+
210
+ if (issues.length === 0) {
211
+ console.log('✓ a11y-lint: no AAA violations found.');
212
+ process.exit(0);
213
+ }
214
+
215
+ const grouped = issues.reduce((acc, it) => {
216
+ (acc[it.file] = acc[it.file] || []).push(it);
217
+ return acc;
218
+ }, {});
219
+
220
+ for (const file of Object.keys(grouped).sort()) {
221
+ console.log(`\n${file}`);
222
+ for (const it of grouped[file]) {
223
+ const tag = `[SC ${it.sc} ${it.rule}]`;
224
+ console.log(` L${it.line} ${tag.padEnd(28)} ${it.message}`);
225
+ }
226
+ }
227
+
228
+ console.log(`\n${issues.length} issue${issues.length === 1 ? '' : 's'} across ${Object.keys(grouped).length} file${Object.keys(grouped).length === 1 ? '' : 's'}.`);
229
+ process.exit(advisory ? 0 : 1);
@@ -232,7 +232,7 @@ const chartChroma2 = tokens.chart?.chroma2Damping?.$value ?? '0.65';
232
232
  // its own L and a chroma multiplier on --primary's c). When absent, falls
233
233
  // back to the legacy hue-rotation behavior using a single --chart-lightness.
234
234
  // Clients opt in by adding chart.lightnessSteps + chart.chromaSteps to their
235
- // tokens.json (see Swimtopia for an example of a Pool Blue → Navy ramp).
235
+ // tokens.json (e.g. a client fork's brand-color → neutral ramp).
236
236
  const stepL = (mode, n) =>
237
237
  tokens.chart?.lightnessSteps?.[mode]?.[`step${n}`]?.$value;
238
238
  const stepC = (n) => tokens.chart?.chromaSteps?.[`step${n}`]?.$value;
@@ -556,7 +556,7 @@ const baseLayer = `@layer base {
556
556
  * role. Disabled state → cursor: not-allowed so "off" reads as
557
557
  * intentional rather than broken.
558
558
  *
559
- * Promoted from swimtopia-prototypes globals.css (2026-06-10) per
559
+ * Promoted from a client fork's globals.css (2026-06-10) per
560
560
  * Sir's "if it's clickable, the cursor says so" rule. */
561
561
  button:not(:disabled),
562
562
  a[href]:not([aria-disabled="true"]),
@@ -600,7 +600,7 @@ html, body {
600
600
  written to --x / --y on <html> before startViewTransition fires (see
601
601
  app/page.tsx toggleDark).
602
602
 
603
- Two deliberate choices, both learned the hard way (swimtopia, 2026-06):
603
+ Two deliberate choices, both learned the hard way (a client fork, 2026-06):
604
604
  1. Radius is a VIEWPORT unit (150vmax), not a percentage. circle(150%)
605
605
  resolves against the snapshot box, so on a large/wide desktop the wipe
606
606
  can finish before it has covered the viewport — a glitch at the END of
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Storybook coverage check.
4
+ *
5
+ * Strict rule: every primitive in packages/core/src/components/ui/*.tsx must
6
+ * have a matching components/<PascalCase>.stories.tsx. When a component file
7
+ * is touched in a commit, its story file must be touched in the same commit.
8
+ *
9
+ * Modes:
10
+ * pnpm check:stories → precommit mode (staged-only, used by hook)
11
+ * pnpm check:stories --all → audit every component (used by CI)
12
+ *
13
+ * On failure, prints violations + the fix command.
14
+ */
15
+
16
+ import { execSync } from "node:child_process";
17
+ import { existsSync, readdirSync } from "node:fs";
18
+ import { join, basename } from "node:path";
19
+
20
+ const ROOT = process.cwd();
21
+ const COMPONENTS_DIR = join(ROOT, "packages/core/src/components/ui");
22
+ const STORIES_DIR = join(ROOT, "components");
23
+
24
+ const ALL = process.argv.includes("--all");
25
+
26
+ function pascal(kebab) {
27
+ return kebab
28
+ .replace(/\.tsx$/, "")
29
+ .split(/[-_]/)
30
+ .map((w) => w[0].toUpperCase() + w.slice(1))
31
+ .join("");
32
+ }
33
+
34
+ function componentToStoryPath(componentRel) {
35
+ // packages/core/src/components/ui/dropdown-menu.tsx → components/DropdownMenu.stories.tsx
36
+ return `components/${pascal(basename(componentRel))}.stories.tsx`;
37
+ }
38
+
39
+ function listAllComponents() {
40
+ if (!existsSync(COMPONENTS_DIR)) return [];
41
+ return readdirSync(COMPONENTS_DIR)
42
+ .filter((f) => f.endsWith(".tsx"))
43
+ .map((f) => `packages/core/src/components/ui/${f}`);
44
+ }
45
+
46
+ function stagedFiles() {
47
+ const out = execSync("git diff --cached --name-only --diff-filter=ACMR", {
48
+ encoding: "utf8",
49
+ });
50
+ return out.split("\n").filter(Boolean);
51
+ }
52
+
53
+ function runAudit() {
54
+ const violations = [];
55
+ for (const c of listAllComponents()) {
56
+ const expected = componentToStoryPath(c);
57
+ if (!existsSync(join(ROOT, expected))) {
58
+ violations.push({ kind: "missing-story", component: c, expected });
59
+ }
60
+ }
61
+ return violations;
62
+ }
63
+
64
+ function runStaged() {
65
+ const staged = stagedFiles();
66
+ const stagedSet = new Set(staged);
67
+ const violations = [];
68
+
69
+ for (const file of staged) {
70
+ if (!file.startsWith("packages/core/src/components/ui/")) continue;
71
+ if (!file.endsWith(".tsx")) continue;
72
+ const expected = componentToStoryPath(file);
73
+ if (!existsSync(join(ROOT, expected))) {
74
+ violations.push({ kind: "missing-story", component: file, expected });
75
+ continue;
76
+ }
77
+ if (!stagedSet.has(expected)) {
78
+ violations.push({ kind: "stale-story", component: file, expected });
79
+ }
80
+ }
81
+
82
+ return violations;
83
+ }
84
+
85
+ const violations = ALL ? runAudit() : runStaged();
86
+
87
+ if (violations.length === 0) {
88
+ if (ALL) console.log("Storybook coverage: OK (every component has a story).");
89
+ process.exit(0);
90
+ }
91
+
92
+ console.error("");
93
+ console.error("✗ Storybook coverage violations:");
94
+ console.error("");
95
+ for (const v of violations) {
96
+ if (v.kind === "missing-story") {
97
+ console.error(` MISSING ${v.component}`);
98
+ console.error(` → expected story at ${v.expected}`);
99
+ } else {
100
+ console.error(` STALE ${v.component} was changed but ${v.expected} was not`);
101
+ }
102
+ }
103
+ console.error("");
104
+ console.error("Fix options:");
105
+ console.error(" • Auto-generate baseline stories: pnpm fix:stories");
106
+ console.error(" • Or in Claude Code, just say: 'fix the stories'");
107
+ console.error(" (Claude follows STORYBOOK_RULE.md to write full-matrix coverage)");
108
+ console.error("");
109
+ process.exit(1);